| 1 | // Copyright 2026 Deno Land Inc. Apache-2.0 license. |
| 2 | |
| 3 | //! The object-store side of an `r2_buckets` binding: the R2 object record, |
| 4 | //! the request shapes, and the reads and writes that `celld r2` and the cell |
| 5 | //! runtime share. Every engine reaches the fleet bucket through this module, |
| 6 | //! so an operator and a Worker cannot disagree about the key an object lives |
| 7 | //! under or the record it carries. The V8 ops live in `js/r2_ops.rs`. |
| 8 | |
| 9 | use crate::asyncrt; |
| 10 | use crate::bucket::BlobAttributes; |
| 11 | use crate::bucket::BlobConditions; |
| 12 | use crate::bucket::BlobMeta; |
| 13 | use crate::bucket::BlobRange; |
| 14 | use crate::bucket::BlobRead; |
| 15 | use crate::bucket::Bucket; |
| 16 | use crate::host_channels::R2_STORE; |
| 17 | use futures_util::StreamExt as _; |
| 18 | use object_store::MultipartUpload; |
| 19 | use serde::Deserialize; |
| 20 | use serde::Serialize; |
| 21 | use std::collections::BTreeMap; |
| 22 | use std::collections::HashMap; |
| 23 | use std::sync::Arc; |
| 24 | use std::sync::OnceLock; |
| 25 | use std::time::Instant; |
| 26 | |
| 27 | /// A page of an R2 listing. R2's own default and maximum is 1,000. |
| 28 | const LIST_LIMIT: usize = 1000; |
| 29 | |
| 30 | /// How many of a listing page's heads are in flight at once when the |
| 31 | /// caller asked for `include`. A page can hold a thousand objects, and |
| 32 | /// reading their metadata one round trip after another would make the |
| 33 | /// option unusable. |
| 34 | const LIST_HEADS: usize = 16; |
| 35 | |
| 36 | /// The part size a streaming `put` cuts at once it is too big to write in |
| 37 | /// one request. Above S3's 5 MiB floor, and a round number of pages. |
| 38 | const STREAM_PART: usize = 8 << 20; |
| 39 | |
| 40 | /// The user-metadata name the R2 object record lives under. See |
| 41 | /// [`Envelope`]. The bucket stores it as `celld_r2` on Azure, which |
| 42 | /// refuses a hyphen in a metadata name. |
| 43 | const ENVELOPE: &str = "celld-r2"; |
| 44 | |
| 45 | /// The key space one binding owns inside the fleet bucket. `bucket_name` |
| 46 | /// comes from the deployment manifest, which validates it, so the prefix |
| 47 | /// cannot escape into the fleet's own keys. |
| 48 | pub(crate) fn blob_key(bucket_name: &str, key: &str) -> String { |
| 49 | format!("r2/{bucket_name}/{key}") |
| 50 | } |
| 51 | |
| 52 | /// The fleet bucket, or the error every op answers without one. |
| 53 | pub(crate) fn store() -> Result<&'static Bucket, String> { |
| 54 | R2_STORE.get().ok_or_else(|| { |
| 55 | "R2 bindings need a fleet bucket: start celld with --bucket (or CELLD_BUCKET)".to_string() |
| 56 | }) |
| 57 | } |
| 58 | |
| 59 | // ---- the object record --------------------------------------------------- |
| 60 | |
| 61 | /// R2's `httpMetadata`. Five of the six are ordinary HTTP headers that |
| 62 | /// every backend stores as headers, and travel as headers. `cacheExpiry` |
| 63 | /// is not a header anywhere, so it travels in the [`Envelope`] with the |
| 64 | /// rest of the record. |
| 65 | #[derive(Default, Clone, Deserialize, Serialize)] |
| 66 | #[serde(default, rename_all = "camelCase")] |
| 67 | pub(crate) struct HttpMeta { |
| 68 | #[serde(skip_serializing_if = "Option::is_none")] |
| 69 | content_type: Option<String>, |
| 70 | #[serde(skip_serializing_if = "Option::is_none")] |
| 71 | content_language: Option<String>, |
| 72 | #[serde(skip_serializing_if = "Option::is_none")] |
| 73 | content_disposition: Option<String>, |
| 74 | #[serde(skip_serializing_if = "Option::is_none")] |
| 75 | content_encoding: Option<String>, |
| 76 | #[serde(skip_serializing_if = "Option::is_none")] |
| 77 | cache_control: Option<String>, |
| 78 | /// Milliseconds since the epoch, as R2 spells it. |
| 79 | #[serde(skip_serializing_if = "Option::is_none")] |
| 80 | cache_expiry: Option<i64>, |
| 81 | } |
| 82 | |
| 83 | /// Everything an R2 object carries that a blob store has no place for. |
| 84 | /// |
| 85 | /// A store keeps bytes, five content headers, and a flat map of ASCII |
| 86 | /// user metadata whose key case it is free to fold. R2 keeps that plus |
| 87 | /// case-sensitive `customMetadata` with arbitrary text in it, a |
| 88 | /// `cacheExpiry`, a set of checksums, and a storage class. So the record |
| 89 | /// is written as one JSON value under a single reserved user-metadata |
| 90 | /// name, escaped to ASCII, and the five content headers are *also* |
| 91 | /// written as headers so the stored object is a well-formed object rather |
| 92 | /// than a celld-private encoding. |
| 93 | /// |
| 94 | /// An object with no envelope — one this runtime wrote before the record |
| 95 | /// existed, or one another tool put in the bucket — still reads: its user |
| 96 | /// metadata is its `customMetadata`, and its headers are its |
| 97 | /// `httpMetadata`. That is the whole reason the envelope is additive. |
| 98 | #[derive(Default, Clone, Deserialize, Serialize)] |
| 99 | #[serde(default, rename_all = "camelCase")] |
| 100 | pub(crate) struct Envelope { |
| 101 | #[serde(skip_serializing_if = "BTreeMap::is_empty")] |
| 102 | pub(crate) custom: BTreeMap<String, String>, |
| 103 | pub(crate) http: HttpMeta, |
| 104 | /// Lowercase algorithm name (`md5`, `sha1`, `sha256`, `sha384`, |
| 105 | /// `sha512`) to lowercase hex. |
| 106 | #[serde(skip_serializing_if = "BTreeMap::is_empty")] |
| 107 | pub(crate) checksums: BTreeMap<String, String>, |
| 108 | #[serde(skip_serializing_if = "Option::is_none")] |
| 109 | pub(crate) storage_class: Option<String>, |
| 110 | } |
| 111 | |
| 112 | impl Envelope { |
| 113 | /// The record on an object the store answered. The five content |
| 114 | /// headers come off the response, because they are the object's own |
| 115 | /// headers and stay right even for an object written by another tool. |
| 116 | fn read(attributes: &BlobAttributes) -> Self { |
| 117 | let mut envelope = attributes |
| 118 | .metadata_value(ENVELOPE) |
| 119 | .and_then(|value| serde_json::from_str::<Self>(value).ok()) |
| 120 | .unwrap_or_else(|| Self { |
| 121 | custom: attributes |
| 122 | .metadata |
| 123 | .iter() |
| 124 | .map(|(name, value)| (name.clone(), value.clone())) |
| 125 | .collect(), |
| 126 | ..Self::default() |
| 127 | }); |
| 128 | envelope.http.content_type = attributes.content_type.clone(); |
| 129 | envelope.http.content_language = attributes.content_language.clone(); |
| 130 | envelope.http.content_disposition = attributes.content_disposition.clone(); |
| 131 | envelope.http.content_encoding = attributes.content_encoding.clone(); |
| 132 | envelope.http.cache_control = attributes.cache_control.clone(); |
| 133 | envelope |
| 134 | } |
| 135 | |
| 136 | /// The store-side attributes that carry this record. |
| 137 | pub(crate) fn write(&self) -> BlobAttributes { |
| 138 | BlobAttributes { |
| 139 | content_type: self.http.content_type.clone(), |
| 140 | content_language: self.http.content_language.clone(), |
| 141 | content_disposition: self.http.content_disposition.clone(), |
| 142 | content_encoding: self.http.content_encoding.clone(), |
| 143 | cache_control: self.http.cache_control.clone(), |
| 144 | metadata: vec![(ENVELOPE.to_string(), ascii_json(self))], |
| 145 | } |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | /// A JSON value with every non-ASCII character escaped. User metadata is |
| 150 | /// an HTTP header on all three backends and only US-ASCII survives the |
| 151 | /// trip; JSON's `\u` escapes make that lossless rather than lossy. |
| 152 | fn ascii_json<T: Serialize>(value: &T) -> String { |
| 153 | let json = serde_json::to_string(value).unwrap_or_else(|_| "{}".to_string()); |
| 154 | if json.is_ascii() { |
| 155 | return json; |
| 156 | } |
| 157 | // Only string contents can be non-ASCII in JSON, so escaping any such |
| 158 | // character in place stays valid JSON. |
| 159 | let mut out = String::with_capacity(json.len()); |
| 160 | for character in json.chars() { |
| 161 | match character.is_ascii() { |
| 162 | true => out.push(character), |
| 163 | false => { |
| 164 | let mut units = [0u16; 2]; |
| 165 | for unit in character.encode_utf16(&mut units) { |
| 166 | out.push_str(&format!("\\u{unit:04x}")); |
| 167 | } |
| 168 | } |
| 169 | } |
| 170 | } |
| 171 | out |
| 172 | } |
| 173 | |
| 174 | /// One R2 object, in the shape `__makeR2Bucket` turns into an `R2Object`. |
| 175 | /// `range` is present only on the answer to a `get`. |
| 176 | pub(crate) fn object_json( |
| 177 | key: &str, |
| 178 | meta: &BlobMeta, |
| 179 | range: Option<(u64, u64)>, |
| 180 | ) -> serde_json::Value { |
| 181 | let envelope = Envelope::read(&meta.attributes); |
| 182 | let mut json = serde_json::json!({ |
| 183 | "key": key, |
| 184 | "size": meta.size, |
| 185 | // R2 gives every write a version id. A versioned bucket has one; |
| 186 | // everywhere else the etag names the same thing — the bytes this |
| 187 | // key held at this moment. |
| 188 | "version": meta.version.clone().or_else(|| meta.etag.clone()), |
| 189 | "etag": meta.etag, |
| 190 | "uploaded": meta.uploaded_ms, |
| 191 | "http": envelope.http, |
| 192 | "custom": envelope.custom, |
| 193 | "checksums": envelope.checksums, |
| 194 | "storageClass": envelope.storage_class.unwrap_or_else(|| "Standard".to_string()), |
| 195 | }); |
| 196 | if let Some((offset, length)) = range { |
| 197 | json["range"] = serde_json::json!({ "offset": offset, "length": length }); |
| 198 | } |
| 199 | json |
| 200 | } |
| 201 | |
| 202 | // ---- requests ------------------------------------------------------------ |
| 203 | |
| 204 | /// R2's `onlyIf`, already normalized by the harness: the `Headers` form |
| 205 | /// and the `R2Conditional` form arrive here the same way. |
| 206 | #[derive(Default, Deserialize)] |
| 207 | #[serde(default, rename_all = "camelCase")] |
| 208 | pub(crate) struct Conditional { |
| 209 | etag_matches: Option<String>, |
| 210 | etag_does_not_match: Option<String>, |
| 211 | /// Milliseconds since the epoch. |
| 212 | uploaded_before: Option<i64>, |
| 213 | uploaded_after: Option<i64>, |
| 214 | } |
| 215 | |
| 216 | impl From<Conditional> for BlobConditions { |
| 217 | fn from(conditional: Conditional) -> Self { |
| 218 | Self { |
| 219 | if_match: conditional.etag_matches, |
| 220 | if_none_match: conditional.etag_does_not_match, |
| 221 | uploaded_before_ms: conditional.uploaded_before, |
| 222 | uploaded_after_ms: conditional.uploaded_after, |
| 223 | } |
| 224 | } |
| 225 | } |
| 226 | |
| 227 | /// R2's `R2Range`, normalized by the harness to the three fields R2 |
| 228 | /// documents. `suffix` wins over the other two, as it does on R2. |
| 229 | #[derive(Default, Deserialize)] |
| 230 | #[serde(default, rename_all = "camelCase")] |
| 231 | pub(crate) struct Range { |
| 232 | offset: Option<u64>, |
| 233 | length: Option<u64>, |
| 234 | suffix: Option<u64>, |
| 235 | } |
| 236 | |
| 237 | impl From<Range> for BlobRange { |
| 238 | fn from(range: Range) -> Self { |
| 239 | match (range.suffix, range.offset, range.length) { |
| 240 | (Some(suffix), _, _) => Self::Suffix(suffix), |
| 241 | (None, offset, Some(length)) => Self::Bounded { |
| 242 | offset: offset.unwrap_or(0), |
| 243 | length, |
| 244 | }, |
| 245 | (None, Some(offset), None) => Self::From(offset), |
| 246 | (None, None, None) => Self::Whole, |
| 247 | } |
| 248 | } |
| 249 | } |
| 250 | |
| 251 | #[derive(Default, Deserialize)] |
| 252 | #[serde(default, rename_all = "camelCase")] |
| 253 | pub(crate) struct GetRequest { |
| 254 | pub(crate) range: Option<Range>, |
| 255 | pub(crate) only_if: Option<Conditional>, |
| 256 | } |
| 257 | |
| 258 | #[derive(Default, Deserialize)] |
| 259 | #[serde(default, rename_all = "camelCase")] |
| 260 | pub(crate) struct PutRequest { |
| 261 | pub(crate) http: HttpMeta, |
| 262 | pub(crate) custom: BTreeMap<String, String>, |
| 263 | pub(crate) storage_class: Option<String>, |
| 264 | only_if: Option<Conditional>, |
| 265 | /// Algorithm name to the lowercase hex digest the caller asserts. |
| 266 | /// A mismatch is a refused write, as it is on R2. |
| 267 | verify: BTreeMap<String, String>, |
| 268 | } |
| 269 | |
| 270 | #[derive(Default, Deserialize)] |
| 271 | #[serde(default, rename_all = "camelCase")] |
| 272 | struct ListRequest { |
| 273 | prefix: String, |
| 274 | cursor: Option<String>, |
| 275 | start_after: Option<String>, |
| 276 | limit: Option<i64>, |
| 277 | delimiter: Option<String>, |
| 278 | /// `true` when the caller asked for `httpMetadata` or |
| 279 | /// `customMetadata`, which a listing does not carry and a head does. |
| 280 | include: bool, |
| 281 | } |
| 282 | |
| 283 | // ---- checksums ----------------------------------------------------------- |
| 284 | |
| 285 | /// The digests an R2 write computes over its own bytes. R2 always records |
| 286 | /// an md5 for an object written in one request, and records whichever |
| 287 | /// other digests the caller asserted; nothing else is computed, because |
| 288 | /// nothing else would ever be read back. |
| 289 | #[derive(Default)] |
| 290 | struct Digests { |
| 291 | md5: Option<md5::Md5>, |
| 292 | sha1: Option<sha1::Sha1>, |
| 293 | sha256: Option<sha2::Sha256>, |
| 294 | sha384: Option<sha2::Sha384>, |
| 295 | sha512: Option<sha2::Sha512>, |
| 296 | } |
| 297 | |
| 298 | impl Digests { |
| 299 | /// `md5` unless this write cannot honestly claim one, plus every |
| 300 | /// algorithm the caller asserted. |
| 301 | fn wanted(asserted: &BTreeMap<String, String>, md5: bool) -> Self { |
| 302 | let has = |name: &str| asserted.contains_key(name); |
| 303 | Self { |
| 304 | md5: (md5 || has("md5")).then(md5::Md5::default), |
| 305 | sha1: has("sha1").then(sha1::Sha1::default), |
| 306 | sha256: has("sha256").then(sha2::Sha256::default), |
| 307 | sha384: has("sha384").then(sha2::Sha384::default), |
| 308 | sha512: has("sha512").then(sha2::Sha512::default), |
| 309 | } |
| 310 | } |
| 311 | |
| 312 | fn update(&mut self, bytes: &[u8]) { |
| 313 | use sha2::Digest as _; |
| 314 | if let Some(digest) = &mut self.md5 { |
| 315 | digest.update(bytes); |
| 316 | } |
| 317 | if let Some(digest) = &mut self.sha1 { |
| 318 | digest.update(bytes); |
| 319 | } |
| 320 | if let Some(digest) = &mut self.sha256 { |
| 321 | digest.update(bytes); |
| 322 | } |
| 323 | if let Some(digest) = &mut self.sha384 { |
| 324 | digest.update(bytes); |
| 325 | } |
| 326 | if let Some(digest) = &mut self.sha512 { |
| 327 | digest.update(bytes); |
| 328 | } |
| 329 | } |
| 330 | |
| 331 | fn finish(self) -> BTreeMap<String, String> { |
| 332 | use sha2::Digest as _; |
| 333 | let mut out = BTreeMap::new(); |
| 334 | let mut take = |name: &str, digest: Option<Vec<u8>>| { |
| 335 | if let Some(digest) = digest { |
| 336 | out.insert(name.to_string(), hex(&digest)); |
| 337 | } |
| 338 | }; |
| 339 | take("md5", self.md5.map(|digest| digest.finalize().to_vec())); |
| 340 | take("sha1", self.sha1.map(|digest| digest.finalize().to_vec())); |
| 341 | take( |
| 342 | "sha256", |
| 343 | self.sha256.map(|digest| digest.finalize().to_vec()), |
| 344 | ); |
| 345 | take( |
| 346 | "sha384", |
| 347 | self.sha384.map(|digest| digest.finalize().to_vec()), |
| 348 | ); |
| 349 | take( |
| 350 | "sha512", |
| 351 | self.sha512.map(|digest| digest.finalize().to_vec()), |
| 352 | ); |
| 353 | out |
| 354 | } |
| 355 | } |
| 356 | |
| 357 | fn hex(bytes: &[u8]) -> String { |
| 358 | bytes.iter().fold(String::new(), |mut out, byte| { |
| 359 | out.push_str(&format!("{byte:02x}")); |
| 360 | out |
| 361 | }) |
| 362 | } |
| 363 | |
| 364 | /// Check the caller's asserted digests against the computed ones. R2 |
| 365 | /// refuses a write whose checksum does not match what arrived, which is |
| 366 | /// the entire point of sending one. |
| 367 | fn verify( |
| 368 | asserted: &BTreeMap<String, String>, |
| 369 | computed: &BTreeMap<String, String>, |
| 370 | ) -> Result<(), String> { |
| 371 | for (name, claimed) in asserted { |
| 372 | let claimed = claimed.trim().to_ascii_lowercase(); |
| 373 | match computed.get(name) { |
| 374 | Some(actual) if *actual == claimed => {} |
| 375 | Some(actual) => { |
| 376 | return Err(format!( |
| 377 | "R2 put: the {name} checksum of the body is {actual}, not the {claimed} the \ |
| 378 | caller asserted" |
| 379 | )) |
| 380 | } |
| 381 | None => return Err(format!("R2 put: celld cannot check a {name} checksum")), |
| 382 | } |
| 383 | } |
| 384 | Ok(()) |
| 385 | } |
| 386 | |
| 387 | /// One object's record, or `None` when the key does not exist. |
| 388 | /// |
| 389 | /// Shared with `celld r2 head`: an operator and a Worker must not be able |
| 390 | /// to disagree about which key an object lives under, and the answer is |
| 391 | /// only right because both sides scope the key the same way. |
| 392 | pub(crate) async fn head(bucket_name: &str, key: &str) -> Result<Option<BlobMeta>, String> { |
| 393 | store()? |
| 394 | .head_blob(&blob_key(bucket_name, key)) |
| 395 | .await |
| 396 | .map_err(|error| error.to_string()) |
| 397 | } |
| 398 | |
| 399 | /// One conditional read, with the body still on the wire. |
| 400 | /// |
| 401 | /// Shared with `celld r2 get`, which drains the body to stdout instead of |
| 402 | /// handing it to an isolate. |
| 403 | pub(crate) async fn read( |
| 404 | bucket_name: &str, |
| 405 | key: &str, |
| 406 | range: BlobRange, |
| 407 | conditions: &BlobConditions, |
| 408 | ) -> Result<BlobRead, String> { |
| 409 | store()? |
| 410 | .get_blob(&blob_key(bucket_name, key), range, conditions) |
| 411 | .await |
| 412 | .map_err(|error| error.to_string()) |
| 413 | } |
| 414 | |
| 415 | /// Remove every named key. Shared with `celld r2 delete`. |
| 416 | pub(crate) async fn delete(bucket_name: &str, keys: &[String]) -> Result<(), String> { |
| 417 | let store = store()?; |
| 418 | let keys = keys |
| 419 | .iter() |
| 420 | .map(|key| blob_key(bucket_name, key)) |
| 421 | .collect::<Vec<_>>(); |
| 422 | // `delete_blobs` reports what went; anything left is a failure the |
| 423 | // caller must see, because R2's delete either applies or throws. |
| 424 | let gone = store.delete_blobs(&keys).await; |
| 425 | if gone != keys.len() { |
| 426 | return Err(format!( |
| 427 | "R2 delete removed {gone} of {} keys; the rest failed", |
| 428 | keys.len() |
| 429 | )); |
| 430 | } |
| 431 | Ok(()) |
| 432 | } |
| 433 | |
| 434 | /// One listing page, in the shape `__makeR2Bucket` turns into an |
| 435 | /// `R2Objects`. `request_json` is R2's `R2ListOptions`, normalized by the |
| 436 | /// harness. |
| 437 | /// |
| 438 | /// Shared with `celld r2 list`, so an operator's listing applies the same |
| 439 | /// prefix scoping, the same cursor rule, and the same page bound as a |
| 440 | /// Worker's. |
| 441 | pub(crate) async fn list( |
| 442 | bucket_name: &str, |
| 443 | request_json: &str, |
| 444 | ) -> Result<serde_json::Value, String> { |
| 445 | let request = serde_json::from_str::<ListRequest>(request_json) |
| 446 | .map_err(|error| format!("invalid R2 list options: {error}"))?; |
| 447 | let store = store()?; |
| 448 | let limit = match request.limit.unwrap_or(0) { |
| 449 | limit if limit > 0 => (limit as usize).min(LIST_LIMIT), |
| 450 | _ => LIST_LIMIT, |
| 451 | }; |
| 452 | let scoped = blob_key(bucket_name, &request.prefix); |
| 453 | // R2 resumes from the cursor when it has one and ignores |
| 454 | // `startAfter`, which is the same knob for a first page. |
| 455 | let after = request |
| 456 | .cursor |
| 457 | .filter(|cursor| !cursor.is_empty()) |
| 458 | .or(request.start_after) |
| 459 | .filter(|after| !after.is_empty()) |
| 460 | .map(|after| blob_key(bucket_name, &after)); |
| 461 | let page = store |
| 462 | .list_page( |
| 463 | &scoped, |
| 464 | after.as_deref(), |
| 465 | limit, |
| 466 | request.delimiter.as_deref(), |
| 467 | ) |
| 468 | .await |
| 469 | .map_err(|error| error.to_string())?; |
| 470 | // The binding's key space is the caller's: strip the reserved |
| 471 | // prefix back off, so a listed key is one the caller can `get`. |
| 472 | let strip = blob_key(bucket_name, ""); |
| 473 | let unscope = |key: &str| key.strip_prefix(&strip).unwrap_or(key).to_string(); |
| 474 | // A listing carries no metadata on any object store; `include` is |
| 475 | // R2 saying it is worth one head per object to have it, and those |
| 476 | // heads go out together rather than one after another. |
| 477 | let objects = match request.include { |
| 478 | false => page |
| 479 | .objects |
| 480 | .iter() |
| 481 | .map(|entry| { |
| 482 | let meta = BlobMeta { |
| 483 | size: entry.size, |
| 484 | etag: entry.etag.clone(), |
| 485 | version: entry.version.clone(), |
| 486 | cas: None, |
| 487 | uploaded_ms: entry.uploaded_ms, |
| 488 | attributes: BlobAttributes::default(), |
| 489 | }; |
| 490 | object_json(&unscope(&entry.key), &meta, None) |
| 491 | }) |
| 492 | .collect::<Vec<_>>(), |
| 493 | true => { |
| 494 | let keys = page |
| 495 | .objects |
| 496 | .iter() |
| 497 | .map(|entry| entry.key.clone()) |
| 498 | .collect::<Vec<_>>(); |
| 499 | let heads = futures_util::stream::iter(keys) |
| 500 | .map(|key| async move { |
| 501 | store |
| 502 | .head_blob(&key) |
| 503 | .await |
| 504 | .map_err(|error| error.to_string()) |
| 505 | }) |
| 506 | .buffered(LIST_HEADS) |
| 507 | .collect::<Vec<_>>() |
| 508 | .await; |
| 509 | let mut objects = Vec::with_capacity(heads.len()); |
| 510 | for (entry, head) in page.objects.iter().zip(heads) { |
| 511 | // A key deleted between the listing and the head is one |
| 512 | // R2 would not have listed either. |
| 513 | if let Some(meta) = head? { |
| 514 | objects.push(object_json(&unscope(&entry.key), &meta, None)); |
| 515 | } |
| 516 | } |
| 517 | objects |
| 518 | } |
| 519 | }; |
| 520 | Ok(serde_json::json!({ |
| 521 | "objects": objects, |
| 522 | "prefixes": page.prefixes.iter().map(|prefix| unscope(prefix)).collect::<Vec<_>>(), |
| 523 | "truncated": page.truncated, |
| 524 | "cursor": page.cursor.as_deref().map(unscope), |
| 525 | })) |
| 526 | } |
| 527 | |
| 528 | /// Write `body` under `key`, honoring the request's conditions and |
| 529 | /// checksums. The single-request path: a caller that handed R2 a buffer |
| 530 | /// gets one PUT, and one md5 R2 would also have computed. |
| 531 | pub(crate) async fn put_once( |
| 532 | bucket_name: String, |
| 533 | key: String, |
| 534 | body: Vec<u8>, |
| 535 | request: PutRequest, |
| 536 | ) -> Result<String, String> { |
| 537 | let mut digests = Digests::wanted(&request.verify, true); |
| 538 | digests.update(&body); |
| 539 | let checksums = digests.finish(); |
| 540 | verify(&request.verify, &checksums)?; |
| 541 | let envelope = Envelope { |
| 542 | custom: request.custom, |
| 543 | http: request.http, |
| 544 | checksums, |
| 545 | storage_class: request.storage_class, |
| 546 | }; |
| 547 | let conditions = BlobConditions::from(request.only_if.unwrap_or_default()); |
| 548 | let meta = store()? |
| 549 | .put_blob( |
| 550 | &blob_key(&bucket_name, &key), |
| 551 | body.into(), |
| 552 | &envelope.write(), |
| 553 | &conditions, |
| 554 | ) |
| 555 | .await |
| 556 | .map_err(|error| error.to_string())?; |
| 557 | Ok(match meta { |
| 558 | // R2 answers a refused precondition with `null`, not a throw. |
| 559 | None => serde_json::json!({ "stored": false }).to_string(), |
| 560 | Some(meta) => serde_json::json!({ |
| 561 | "stored": true, |
| 562 | "object": object_json(&key, &meta, None), |
| 563 | }) |
| 564 | .to_string(), |
| 565 | }) |
| 566 | } |
| 567 | |
| 568 | /// A `put` whose body is a `ReadableStream`: the isolate hands over one |
| 569 | /// chunk at a time and the host decides, at the first part boundary, |
| 570 | /// whether this is one request or a multipart upload. |
| 571 | pub(crate) struct PutStream { |
| 572 | bucket_name: String, |
| 573 | key: String, |
| 574 | request: PutRequest, |
| 575 | digests: Digests, |
| 576 | /// Bytes not yet handed to the store. |
| 577 | buffered: Vec<u8>, |
| 578 | size: u64, |
| 579 | /// Open once the body outgrew a single request. |
| 580 | pub(crate) upload: Option<Box<dyn MultipartUpload>>, |
| 581 | pub(crate) touched: Instant, |
| 582 | } |
| 583 | |
| 584 | /// Open a streaming write. `request_json` is R2's `R2PutOptions`, |
| 585 | /// normalized by the harness. |
| 586 | /// |
| 587 | /// This is the one constructor, so `celld r2 put` and a Worker's |
| 588 | /// `env.BUCKET.put()` cannot store a different record for the same input: |
| 589 | /// the checksum set, the envelope, and the single-request/multipart choice |
| 590 | /// are all decided here and in [`PutStream::finish`]. |
| 591 | // The idle stamp only ages an abandoned write out; it never orders host |
| 592 | // work, so it stays on the ambient clock outside the execution domain. |
| 593 | // `allow`, not `expect`: Linux clippy does not report this call, so an |
| 594 | // expectation that macOS fulfills fails the public release build. |
| 595 | #[allow( |
| 596 | clippy::disallowed_methods, |
| 597 | reason = "the idle stamp ages an abandoned write out and orders no host work" |
| 598 | )] |
| 599 | pub(crate) fn open_put( |
| 600 | bucket_name: String, |
| 601 | key: String, |
| 602 | request_json: &str, |
| 603 | ) -> Result<PutStream, String> { |
| 604 | let request = serde_json::from_str::<PutRequest>(request_json) |
| 605 | .map_err(|error| format!("invalid R2 put options: {error}"))?; |
| 606 | // Fail before a byte moves if there is no bucket at all. |
| 607 | store()?; |
| 608 | let digests = Digests::wanted(&request.verify, true); |
| 609 | Ok(PutStream { |
| 610 | bucket_name, |
| 611 | key, |
| 612 | request, |
| 613 | digests, |
| 614 | buffered: Vec::new(), |
| 615 | size: 0, |
| 616 | upload: None, |
| 617 | touched: Instant::now(), |
| 618 | }) |
| 619 | } |
| 620 | |
| 621 | impl PutStream { |
| 622 | /// Take in one chunk, handing the store every whole part it makes. |
| 623 | pub(crate) async fn push(&mut self, chunk: Vec<u8>) -> Result<(), String> { |
| 624 | self.digests.update(&chunk); |
| 625 | self.size += chunk.len() as u64; |
| 626 | self.buffered.extend_from_slice(&chunk); |
| 627 | while self.buffered.len() > STREAM_PART { |
| 628 | let part = self.buffered.drain(..STREAM_PART).collect::<Vec<_>>(); |
| 629 | self.part(part).await?; |
| 630 | } |
| 631 | Ok(()) |
| 632 | } |
| 633 | |
| 634 | /// Hand one whole part to the store, opening the upload if this is the |
| 635 | /// first. |
| 636 | async fn part(&mut self, bytes: Vec<u8>) -> Result<(), String> { |
| 637 | if self.upload.is_none() { |
| 638 | // A precondition is checked against the version a write is |
| 639 | // about to replace, and a multipart completion takes none. A |
| 640 | // small streamed body still goes out as one conditional |
| 641 | // request; this one has outgrown that. |
| 642 | if self.request.only_if.is_some() { |
| 643 | return Err(format!( |
| 644 | "R2 put of {}: celld cannot apply `onlyIf` to a streamed body larger than \ |
| 645 | {STREAM_PART} bytes, because it is written as a multipart upload and a \ |
| 646 | multipart completion takes no precondition", |
| 647 | self.key |
| 648 | )); |
| 649 | } |
| 650 | // The record is fixed when the upload opens, so it can only |
| 651 | // carry checksums already known: the ones the caller asserted, |
| 652 | // which the completion refuses to apply if the bytes disagree. |
| 653 | // A computed md5 is not one of them, and R2's multipart |
| 654 | // objects do not carry one either. |
| 655 | if !self.request.verify.contains_key("md5") { |
| 656 | self.digests.md5 = None; |
| 657 | } |
| 658 | self.upload = Some( |
| 659 | store()? |
| 660 | .begin_multipart( |
| 661 | &blob_key(&self.bucket_name, &self.key), |
| 662 | &self.envelope().write(), |
| 663 | ) |
| 664 | .await |
| 665 | .map_err(|error| error.to_string())?, |
| 666 | ); |
| 667 | } |
| 668 | let upload = self.upload.as_mut().expect("just opened"); |
| 669 | upload |
| 670 | .put_part(bytes.into()) |
| 671 | .await |
| 672 | .map_err(|error| format!("R2 put of {}: {error}", self.key)) |
| 673 | } |
| 674 | |
| 675 | /// Close the stream out: one request if nothing was ever parted off, |
| 676 | /// the multipart completion otherwise. |
| 677 | pub(crate) async fn finish(&mut self) -> Result<String, String> { |
| 678 | let Some(mut upload) = self.upload.take() else { |
| 679 | return put_once( |
| 680 | std::mem::take(&mut self.bucket_name), |
| 681 | std::mem::take(&mut self.key), |
| 682 | std::mem::take(&mut self.buffered), |
| 683 | std::mem::take(&mut self.request), |
| 684 | ) |
| 685 | .await; |
| 686 | }; |
| 687 | let mut failed = None; |
| 688 | if !self.buffered.is_empty() { |
| 689 | let last = std::mem::take(&mut self.buffered); |
| 690 | if let Err(error) = upload.put_part(last.into()).await { |
| 691 | failed = Some(format!("R2 put of {}: {error}", self.key)); |
| 692 | } |
| 693 | } |
| 694 | let computed = std::mem::take(&mut self.digests).finish(); |
| 695 | if failed.is_none() { |
| 696 | failed = verify(&self.request.verify, &computed).err(); |
| 697 | } |
| 698 | // A body that did not match what the caller asserted is not |
| 699 | // written at all, so the parts already on the store go away. |
| 700 | if let Some(error) = failed { |
| 701 | if let Err(error) = upload.abort().await { |
| 702 | tracing::warn!(%error, key = self.key, "refused R2 write could not be aborted"); |
| 703 | } |
| 704 | return Err(error); |
| 705 | } |
| 706 | let result = upload |
| 707 | .complete() |
| 708 | .await |
| 709 | .map_err(|error| format!("R2 put of {}: {error}", self.key))?; |
| 710 | let meta = BlobMeta { |
| 711 | size: self.size, |
| 712 | etag: result.e_tag.clone(), |
| 713 | version: result.version, |
| 714 | cas: None, |
| 715 | uploaded_ms: asyncrt::wall_ms(), |
| 716 | // The record the object actually carries, which is the one |
| 717 | // written when the upload opened. |
| 718 | attributes: self.envelope().write(), |
| 719 | }; |
| 720 | Ok(serde_json::json!({ |
| 721 | "stored": true, |
| 722 | "object": object_json(&self.key, &meta, None), |
| 723 | }) |
| 724 | .to_string()) |
| 725 | } |
| 726 | |
| 727 | /// The record a multipart-sized body is stored with. |
| 728 | fn envelope(&self) -> Envelope { |
| 729 | Envelope { |
| 730 | custom: self.request.custom.clone(), |
| 731 | http: self.request.http.clone(), |
| 732 | checksums: self.request.verify.clone(), |
| 733 | storage_class: self.request.storage_class.clone(), |
| 734 | } |
| 735 | } |
| 736 | } |
| 737 | |
| 738 | /// The open writes, by host id. |
| 739 | /// |
| 740 | /// The inner lock is asynchronous because the work it guards is: a Worker |
| 741 | /// may have several calls against one write in flight, and they have to |
| 742 | /// queue behind each other rather than find the entry missing. The outer |
| 743 | /// lock only ever guards the map. |
| 744 | pub(crate) type Open<T> = std::sync::Mutex<HashMap<u64, Arc<tokio::sync::Mutex<T>>>>; |
| 745 | |
| 746 | static PUTS: OnceLock<Open<PutStream>> = OnceLock::new(); |
| 747 | |
| 748 | pub(crate) fn puts() -> &'static Open<PutStream> { |
| 749 | PUTS.get_or_init(|| std::sync::Mutex::new(HashMap::new())) |
| 750 | } |