| 1 | // Copyright 2026 Deno Land Inc. Apache-2.0 license. |
| 2 | |
| 3 | //! The engine's single object-store client: the `object_store` crate |
| 4 | //! `celld-ltx` already links, bound to one bucket. Replaces aws-sdk-s3. |
| 5 | //! No call site streamed a body, so everything is in-memory `Bytes`. |
| 6 | //! |
| 7 | //! Two conditional-write dialects share the surface. An `s3://` (or |
| 8 | //! bare) spec speaks the S3 dialect: the CAS token is the etag, sent as |
| 9 | //! If-Match / If-None-Match with SigV4 credentials. An `az://` spec |
| 10 | //! speaks the same etag dialect on Azure Blob Storage: Put Blob honors |
| 11 | //! both headers, so only the client and the credentials differ. A |
| 12 | //! `gs://` spec speaks the Cloud Storage XML API dialect: the CAS token |
| 13 | //! is the object generation, sent as x-goog-if-generation-match with |
| 14 | //! OAuth credentials. The distinction is the dialect, not the endpoint — |
| 15 | //! GCS accepts S3-style requests on the same host but does not apply |
| 16 | //! If-Match to a PUT, so only the generation dialect can fence there. |
| 17 | //! Callers never see the difference: the token is an opaque `String` a |
| 18 | //! read answers and a conditional write consumes. |
| 19 | //! |
| 20 | //! Error contract, relied on by the self-fence: `put_cas` answers |
| 21 | //! `Ok(None)` only for a clean 412/409 rejection; every other failure |
| 22 | //! surfaces as `Err`. An `Err` is ambiguous — the write may have |
| 23 | //! committed — unless `cas_write_did_not_commit` recognizes an answer |
| 24 | //! that proves the store wrote no object. In the same spirit a response |
| 25 | //! that carries no CAS token is an error, never an empty token a later |
| 26 | //! conditional write would trust. |
| 27 | |
| 28 | use anyhow::anyhow; |
| 29 | use anyhow::Context; |
| 30 | use bytes::Bytes; |
| 31 | use futures_util::stream::BoxStream; |
| 32 | use futures_util::StreamExt; |
| 33 | use object_store::aws::AmazonS3Builder; |
| 34 | use object_store::aws::S3ConditionalPut; |
| 35 | use object_store::azure::authority_hosts; |
| 36 | use object_store::azure::AzureConfigKey; |
| 37 | use object_store::azure::MicrosoftAzureBuilder; |
| 38 | use object_store::gcp::GoogleCloudStorageBuilder; |
| 39 | use object_store::list::PaginatedListOptions; |
| 40 | use object_store::list::PaginatedListStore; |
| 41 | use object_store::path::Path; |
| 42 | use object_store::path::PathPart; |
| 43 | use object_store::Attribute; |
| 44 | use object_store::Attributes; |
| 45 | use object_store::ClientOptions; |
| 46 | use object_store::Error; |
| 47 | use object_store::GetOptions; |
| 48 | use object_store::GetRange; |
| 49 | use object_store::MultipartUpload; |
| 50 | use object_store::ObjectMeta; |
| 51 | use object_store::ObjectStore; |
| 52 | use object_store::PutMode; |
| 53 | use object_store::PutMultipartOptions; |
| 54 | use object_store::PutOptions; |
| 55 | use object_store::PutPayload; |
| 56 | use object_store::RetryConfig; |
| 57 | use object_store::UpdateVersion; |
| 58 | use std::borrow::Cow; |
| 59 | use std::sync::Arc; |
| 60 | use std::time::Duration; |
| 61 | |
| 62 | #[cfg(all(test, celld_internal_tests))] |
| 63 | mod internal_tests { |
| 64 | include!(env!("CELLD_INTERNAL_BUCKET_TESTS")); |
| 65 | } |
| 66 | |
| 67 | /// The part size of [`Bucket::put_large`] and the range size of |
| 68 | /// [`Bucket::get_large`]: comfortably above S3's 5 MiB part minimum, small |
| 69 | /// enough that one part fits the client's per-request timeout on a slow link. |
| 70 | const LARGE_PART: usize = 16 << 20; |
| 71 | /// Parts uploading at once in [`Bucket::put_large`]; with [`LARGE_PART`] this |
| 72 | /// bounds the memory an upload holds. |
| 73 | const LARGE_PARTS_IN_FLIGHT: usize = 4; |
| 74 | |
| 75 | /// The stored form of an empty blob key segment. See [`Bucket::blob_path`]. |
| 76 | const EMPTY_SEGMENT: &str = "%"; |
| 77 | |
| 78 | /// Explicit credentials for a managed installation; everything else comes |
| 79 | /// from the standard `AWS_*` environment. |
| 80 | pub struct StaticCredentials { |
| 81 | pub access_key_id: String, |
| 82 | pub secret_access_key: String, |
| 83 | pub session_token: Option<String>, |
| 84 | } |
| 85 | |
| 86 | /// Which conditional-write dialect the bucket speaks, and therefore |
| 87 | /// what the opaque CAS token holds: the etag on S3 and on Azure Blob |
| 88 | /// Storage, the object generation on GCS. GCS ignores etags on writes, |
| 89 | /// so its tokens must come from the generation everywhere — reads, |
| 90 | /// heads, and put results. Azure needs no third dialect: Put Blob |
| 91 | /// applies If-None-Match and If-Match to the etag, exactly as S3 does, |
| 92 | /// so the two share [`Self::token`] and [`Self::update`]. |
| 93 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 94 | #[doc(hidden)] |
| 95 | pub enum StorageBackend { |
| 96 | S3, |
| 97 | Gcs, |
| 98 | Azure, |
| 99 | Local, |
| 100 | } |
| 101 | |
| 102 | impl StorageBackend { |
| 103 | fn scheme(self) -> &'static str { |
| 104 | match self { |
| 105 | StorageBackend::S3 => "s3", |
| 106 | StorageBackend::Gcs => "gs", |
| 107 | StorageBackend::Azure => "az", |
| 108 | StorageBackend::Local => "dev", |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | /// The CAS token a read or applied write answers: etag or generation, |
| 113 | /// per dialect. A response without one cannot be fenced against, so a |
| 114 | /// missing or empty token is an error — never an empty string a later |
| 115 | /// conditional write would send as a real precondition. |
| 116 | #[doc(hidden)] |
| 117 | pub fn token(self, e_tag: Option<String>, version: Option<String>) -> anyhow::Result<String> { |
| 118 | let (token, header) = match self { |
| 119 | StorageBackend::S3 | StorageBackend::Azure | StorageBackend::Local => (e_tag, "ETag"), |
| 120 | StorageBackend::Gcs => (version, "x-goog-generation"), |
| 121 | }; |
| 122 | match token { |
| 123 | Some(token) if !token.is_empty() => Ok(token), |
| 124 | _ => Err(anyhow!( |
| 125 | "response carries no {header}, so there is no CAS token" |
| 126 | )), |
| 127 | } |
| 128 | } |
| 129 | |
| 130 | /// The precondition a conditional update sends for a held token. |
| 131 | #[doc(hidden)] |
| 132 | pub fn update(self, token: &str) -> UpdateVersion { |
| 133 | match self { |
| 134 | StorageBackend::S3 | StorageBackend::Azure | StorageBackend::Local => UpdateVersion { |
| 135 | e_tag: Some(token.to_string()), |
| 136 | version: None, |
| 137 | }, |
| 138 | StorageBackend::Gcs => UpdateVersion { |
| 139 | e_tag: None, |
| 140 | version: Some(token.to_string()), |
| 141 | }, |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | /// What a conditional write sends on the wire, named for an operator |
| 146 | /// reading a probe failure. The dialects use different headers, so a |
| 147 | /// message that names only one sends half the fleet looking in the |
| 148 | /// wrong place. |
| 149 | fn precondition(self) -> &'static str { |
| 150 | match self { |
| 151 | StorageBackend::S3 | StorageBackend::Azure | StorageBackend::Local => { |
| 152 | "If-Match / If-None-Match" |
| 153 | } |
| 154 | StorageBackend::Gcs => "x-goog-if-generation-match", |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | /// How a user-metadata name that celld writes is spelled on this |
| 159 | /// backend. |
| 160 | /// |
| 161 | /// Azure Blob Storage requires a metadata name to be a C# identifier, |
| 162 | /// and it refuses the whole write with `400 InvalidMetadata` when a name |
| 163 | /// holds a hyphen. celld names such as `celld-r2` failed every R2 write |
| 164 | /// and lost every telemetry batch on an `az://` bucket |
| 165 | /// (denoland/celld#209). Azure therefore gets an underscore for each |
| 166 | /// hyphen, and [`BlobAttributes::metadata_value`] reads either spelling. |
| 167 | /// |
| 168 | /// The other backends keep the hyphen. An object that a fleet already |
| 169 | /// wrote carries the hyphenated name, and a proxy in front of an |
| 170 | /// S3-compatible store can drop a header name that holds an underscore |
| 171 | /// (nginx does by default). The LTX timestamp key makes the same |
| 172 | /// per-backend choice in `celld_ltx::TimestampMetadataKey`. |
| 173 | fn metadata_name(self, name: &str) -> Cow<'_, str> { |
| 174 | match self { |
| 175 | StorageBackend::Azure => Cow::Owned(name.replace('-', "_")), |
| 176 | StorageBackend::S3 | StorageBackend::Gcs | StorageBackend::Local => Cow::Borrowed(name), |
| 177 | } |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | /// One object-store bucket, optionally scoped to a key prefix. Cheap to |
| 182 | /// clone; each `open` builds its own HTTP transport, so a dedicated |
| 183 | /// instance also isolates its traffic. |
| 184 | #[derive(Clone)] |
| 185 | pub struct Bucket { |
| 186 | pub store: Arc<dyn ObjectStore>, |
| 187 | /// The same client as `store`, reached through the paginated listing |
| 188 | /// trait. `ObjectStore::list_with_delimiter` drains every continuation |
| 189 | /// page into one buffer before it returns, so it cannot answer "the |
| 190 | /// first N" without paying for all of them. `PaginatedListStore` takes |
| 191 | /// a page size and returns a resumption token, which is what bounds a |
| 192 | /// listing's cost rather than only its output. It is a separate trait, |
| 193 | /// so the concrete client has to be kept here as it is built — |
| 194 | /// `Arc<dyn ObjectStore>` cannot be widened to it later. |
| 195 | paginated: Arc<dyn PaginatedListStore>, |
| 196 | /// Conditional writes only, built with retries OFF: a retried CAS put |
| 197 | /// can land on the first attempt's own token change and report a clean |
| 198 | /// 412 — converting "may have committed" into a false rejection. The |
| 199 | /// ambiguity must surface as `Err` so the caller reconciles. |
| 200 | pub cas_store: Arc<dyn ObjectStore>, |
| 201 | pub backend: StorageBackend, |
| 202 | /// Bucket name, for messages — the store is already bound to it. |
| 203 | pub name: String, |
| 204 | /// Empty, or a slash-terminated key prefix every operation is scoped |
| 205 | /// to. Call sites keep forming unprefixed keys; this type is the one |
| 206 | /// place that knows where in the bucket a fleet lives. |
| 207 | pub prefix: String, |
| 208 | } |
| 209 | |
| 210 | /// One page of [`Bucket::common_prefixes_page`]. |
| 211 | pub struct CommonPrefixPage { |
| 212 | /// The children this page listed, in the store's key order. |
| 213 | pub prefixes: Vec<String>, |
| 214 | /// Present exactly when the store truncated the page, so a caller |
| 215 | /// learns that more children exist without a second request. |
| 216 | pub page_token: Option<String>, |
| 217 | } |
| 218 | |
| 219 | /// One bounded page of object descriptions from a recursive listing. |
| 220 | pub(crate) struct ObjectPage { |
| 221 | pub objects: Vec<ObjectMeta>, |
| 222 | pub page_token: Option<String>, |
| 223 | } |
| 224 | |
| 225 | /// Whether a conditional write reached a provider-enforced conflict. |
| 226 | /// Azure reports a failed `If-None-Match` as `Precondition`, while some |
| 227 | /// stores report the same create conflict as `AlreadyExists`. Both are a |
| 228 | /// clean lost race. Every other error remains ambiguous. |
| 229 | #[doc(hidden)] |
| 230 | pub fn is_clean_cas_rejection(error: &Error) -> bool { |
| 231 | matches!( |
| 232 | error, |
| 233 | Error::Precondition { .. } | Error::AlreadyExists { .. } |
| 234 | ) |
| 235 | } |
| 236 | |
| 237 | /// Whether a failed conditional write proves that the store holds no new |
| 238 | /// object. A caller that renews a lease uses this to skip the readback |
| 239 | /// that resolves an ambiguous write, because the readback costs a round |
| 240 | /// trip out of the authority a store blip is already eating. |
| 241 | /// |
| 242 | /// Every variant below is either a rejection the client made before it |
| 243 | /// sent a request, or a store answer that precedes the object write: |
| 244 | /// `object_store` maps 401 to `Unauthenticated` and 403 to |
| 245 | /// `PermissionDenied`, and each of the four object stores this engine |
| 246 | /// speaks to authorizes a `PUT` before it applies one. A `PUT` that |
| 247 | /// answers 404 reached no bucket, so it wrote nothing. |
| 248 | /// |
| 249 | /// `Error::Generic` is absent on purpose, and it carries every 5xx, every |
| 250 | /// timeout and every connection failure. A connection that never opened |
| 251 | /// also wrote nothing, but `object_store` 0.12 keeps `RetryError` (and so |
| 252 | /// the `Connect` error kind) private, so no public API separates it from |
| 253 | /// a 500 that can have committed. Matching the message text would decide |
| 254 | /// a lease fence on a string, therefore the whole variant stays ambiguous |
| 255 | /// until the upstream type is reachable. |
| 256 | #[doc(hidden)] |
| 257 | pub fn cas_write_did_not_commit(error: &anyhow::Error) -> bool { |
| 258 | // `put_cas` wraps the store error in context, so read the chain rather |
| 259 | // than the outermost error. A chain that carries no `object_store` |
| 260 | // error at all -- an applied write whose response had no CAS token -- |
| 261 | // does not match, which leaves it ambiguous. That is the safe answer. |
| 262 | error.downcast_ref::<Error>().is_some_and(|error| { |
| 263 | matches!( |
| 264 | error, |
| 265 | Error::Unauthenticated { .. } |
| 266 | | Error::PermissionDenied { .. } |
| 267 | | Error::NotFound { .. } |
| 268 | | Error::InvalidPath { .. } |
| 269 | | Error::NotSupported { .. } |
| 270 | | Error::NotImplemented |
| 271 | | Error::UnknownConfigurationKey { .. } |
| 272 | ) |
| 273 | }) |
| 274 | } |
| 275 | |
| 276 | /// Split a `[s3://|gs://|az://]NAME[/PREFIX]` bucket spec into the |
| 277 | /// backend, the bucket name and a normalized key prefix: empty, or |
| 278 | /// slash-terminated. A spec without a scheme stays S3-compatible, and a |
| 279 | /// spec without a PREFIX keeps every key at the bucket root, so a fleet |
| 280 | /// provisioned before either existed never moves its objects. |
| 281 | /// Scheme names are ASCII case-insensitive, as URI schemes require. |
| 282 | /// |
| 283 | /// On `az://` the NAME is the container, and the storage account comes |
| 284 | /// from `AZURE_STORAGE_ACCOUNT_NAME`. The second path segment is the key |
| 285 | /// prefix on all three schemes, so the account cannot live there without |
| 286 | /// making `az://` parse differently from the other two. |
| 287 | #[doc(hidden)] |
| 288 | pub fn split_spec(spec: &str) -> (StorageBackend, &str, String) { |
| 289 | let strip_scheme = |scheme: &str| { |
| 290 | spec.get(..scheme.len()) |
| 291 | .filter(|candidate| candidate.eq_ignore_ascii_case(scheme)) |
| 292 | .map(|_| &spec[scheme.len()..]) |
| 293 | }; |
| 294 | let (backend, spec) = if let Some(rest) = strip_scheme("gs://") { |
| 295 | (StorageBackend::Gcs, rest) |
| 296 | } else if let Some(rest) = strip_scheme("az://") { |
| 297 | (StorageBackend::Azure, rest) |
| 298 | } else if let Some(rest) = strip_scheme("s3://") { |
| 299 | (StorageBackend::S3, rest) |
| 300 | } else { |
| 301 | (StorageBackend::S3, spec) |
| 302 | }; |
| 303 | let (name, prefix) = spec.split_once('/').unwrap_or((spec, "")); |
| 304 | let parts = prefix.split('/').filter(|part| !part.is_empty()); |
| 305 | ( |
| 306 | backend, |
| 307 | name, |
| 308 | parts.map(|part| format!("{part}/")).collect(), |
| 309 | ) |
| 310 | } |
| 311 | |
| 312 | /// The S3 endpoint the environment supplies when no explicit one was |
| 313 | /// given: the AWS SDK's standard `AWS_ENDPOINT_URL`, then the older |
| 314 | /// `AWS_ENDPOINT` — the same variables `AmazonS3Builder::from_env` |
| 315 | /// injects into the client. Resolved here so the path-style decision and |
| 316 | /// the client always agree about whether an endpoint is in play. |
| 317 | #[doc(hidden)] |
| 318 | pub fn resolve_env_endpoint() -> Option<String> { |
| 319 | ["AWS_ENDPOINT_URL", "AWS_ENDPOINT"] |
| 320 | .iter() |
| 321 | .find_map(|var| std::env::var(var).ok().filter(|value| !value.is_empty())) |
| 322 | } |
| 323 | |
| 324 | /// The byte range a `get` asked for. R2 spells a range four ways and so |
| 325 | /// does `object_store`, so the request reaches the backend as the caller |
| 326 | /// wrote it rather than widened to a whole-object read. |
| 327 | #[derive(Clone, Copy)] |
| 328 | pub enum BlobRange { |
| 329 | /// The whole object. |
| 330 | Whole, |
| 331 | /// `offset` onwards, to the end of the object. |
| 332 | From(u64), |
| 333 | /// `length` bytes starting at `offset`. |
| 334 | Bounded { offset: u64, length: u64 }, |
| 335 | /// The last `length` bytes. |
| 336 | Suffix(u64), |
| 337 | } |
| 338 | |
| 339 | /// R2's `onlyIf`, split by who can answer it. The etag halves ride down |
| 340 | /// to the store as If-Match / If-None-Match, so no concurrent write slips |
| 341 | /// between the check and the read. The upload-time halves are checked |
| 342 | /// here: R2 compares milliseconds and an HTTP date carries only seconds, |
| 343 | /// so If-Modified-Since would answer a different question for every |
| 344 | /// object written in the same second as the bound. |
| 345 | #[derive(Default, Clone)] |
| 346 | pub struct BlobConditions { |
| 347 | pub if_match: Option<String>, |
| 348 | pub if_none_match: Option<String>, |
| 349 | pub uploaded_before_ms: Option<i64>, |
| 350 | pub uploaded_after_ms: Option<i64>, |
| 351 | } |
| 352 | |
| 353 | impl BlobConditions { |
| 354 | /// Whether an etag satisfies the halves the store checks. Used on the |
| 355 | /// write path, which evaluates the whole condition itself against a |
| 356 | /// head rather than sending it, because a write's precondition has to |
| 357 | /// be paired with the CAS token of the very version it inspected. |
| 358 | fn etag_met(&self, etag: Option<&str>) -> bool { |
| 359 | let matches = |list: &str| match list.trim() { |
| 360 | "*" => etag.is_some(), |
| 361 | list => list |
| 362 | .split(',') |
| 363 | .any(|candidate| etag_eq(candidate, etag.unwrap_or_default())), |
| 364 | }; |
| 365 | self.if_match.as_deref().is_none_or(&matches) |
| 366 | && !self.if_none_match.as_deref().is_some_and(&matches) |
| 367 | } |
| 368 | |
| 369 | /// Whether an upload time satisfies the halves this module checks. |
| 370 | fn time_met(&self, uploaded_ms: i64) -> bool { |
| 371 | self.uploaded_before_ms |
| 372 | .is_none_or(|before| uploaded_ms < before) |
| 373 | && self |
| 374 | .uploaded_after_ms |
| 375 | .is_none_or(|after| uploaded_ms > after) |
| 376 | } |
| 377 | |
| 378 | fn is_empty(&self) -> bool { |
| 379 | self.if_match.is_none() |
| 380 | && self.if_none_match.is_none() |
| 381 | && self.uploaded_before_ms.is_none() |
| 382 | && self.uploaded_after_ms.is_none() |
| 383 | } |
| 384 | } |
| 385 | |
| 386 | /// Etag comparison, weak-marker and quote insensitive. R2 hands a Worker |
| 387 | /// the unquoted etag and takes either spelling back. |
| 388 | fn etag_eq(left: &str, right: &str) -> bool { |
| 389 | let bare = |value: &str| { |
| 390 | value |
| 391 | .trim() |
| 392 | .trim_start_matches("W/") |
| 393 | .trim_matches('"') |
| 394 | .to_string() |
| 395 | }; |
| 396 | bare(left) == bare(right) |
| 397 | } |
| 398 | |
| 399 | /// The HTTP headers and the user metadata an object carries. The five |
| 400 | /// headers are the ones every backend stores as headers, and are R2's |
| 401 | /// `httpMetadata` minus `cacheExpiry`, which no backend has a header for. |
| 402 | /// `metadata` is the backend's user metadata, kept under its own |
| 403 | /// `x-amz-meta-` / `x-goog-meta-` / `x-ms-meta-` prefix; what an R2 |
| 404 | /// binding puts in there is the binding's business, not this module's. |
| 405 | /// The one thing this module decides is how a written name is spelled, |
| 406 | /// because only this module knows which backend refuses which name. |
| 407 | #[derive(Default, Clone)] |
| 408 | pub struct BlobAttributes { |
| 409 | pub content_type: Option<String>, |
| 410 | pub content_language: Option<String>, |
| 411 | pub content_disposition: Option<String>, |
| 412 | pub content_encoding: Option<String>, |
| 413 | pub cache_control: Option<String>, |
| 414 | pub metadata: Vec<(String, String)>, |
| 415 | } |
| 416 | |
| 417 | impl BlobAttributes { |
| 418 | /// The headers and user metadata on a response. Every other attribute |
| 419 | /// `object_store` parses is a transport detail, not the object's. |
| 420 | fn read(attributes: &Attributes) -> Self { |
| 421 | let value = |attribute: &Attribute| { |
| 422 | attributes |
| 423 | .get(attribute) |
| 424 | .map(|value| value.as_ref().to_string()) |
| 425 | }; |
| 426 | Self { |
| 427 | content_type: value(&Attribute::ContentType), |
| 428 | content_language: value(&Attribute::ContentLanguage), |
| 429 | content_disposition: value(&Attribute::ContentDisposition), |
| 430 | content_encoding: value(&Attribute::ContentEncoding), |
| 431 | cache_control: value(&Attribute::CacheControl), |
| 432 | metadata: user_metadata(attributes), |
| 433 | } |
| 434 | } |
| 435 | |
| 436 | /// The same, as the store's write-side attribute set, with each |
| 437 | /// metadata name spelled for `backend`. |
| 438 | fn write(&self, backend: StorageBackend) -> Attributes { |
| 439 | let mut attributes = Attributes::new(); |
| 440 | let mut set = |attribute: Attribute, value: &Option<String>| { |
| 441 | if let Some(value) = value { |
| 442 | attributes.insert(attribute, value.clone().into()); |
| 443 | } |
| 444 | }; |
| 445 | set(Attribute::ContentType, &self.content_type); |
| 446 | set(Attribute::ContentLanguage, &self.content_language); |
| 447 | set(Attribute::ContentDisposition, &self.content_disposition); |
| 448 | set(Attribute::ContentEncoding, &self.content_encoding); |
| 449 | set(Attribute::CacheControl, &self.cache_control); |
| 450 | for (name, value) in &self.metadata { |
| 451 | attributes.insert( |
| 452 | Attribute::Metadata(Cow::Owned(backend.metadata_name(name).into_owned())), |
| 453 | value.clone().into(), |
| 454 | ); |
| 455 | } |
| 456 | attributes |
| 457 | } |
| 458 | |
| 459 | /// The value under a metadata name that celld writes, in whichever |
| 460 | /// spelling the backend stored. A store can fold the case of a name, so |
| 461 | /// case does not matter. Both spellings match on every backend, so an |
| 462 | /// object copied out of an Azure container into another store still |
| 463 | /// reads. |
| 464 | pub fn metadata_value(&self, name: &str) -> Option<&str> { |
| 465 | self.metadata |
| 466 | .iter() |
| 467 | .find(|(stored, _)| { |
| 468 | stored.len() == name.len() |
| 469 | && stored.bytes().zip(name.bytes()).all(|(stored, wanted)| { |
| 470 | stored.eq_ignore_ascii_case(&wanted) || (stored == b'_' && wanted == b'-') |
| 471 | }) |
| 472 | }) |
| 473 | .map(|(_, value)| value.as_str()) |
| 474 | } |
| 475 | } |
| 476 | |
| 477 | /// What every answer about an object knows, whatever asked for it. |
| 478 | pub struct BlobMeta { |
| 479 | pub size: u64, |
| 480 | pub etag: Option<String>, |
| 481 | /// The backend's version id, where the bucket has versioning on. |
| 482 | pub version: Option<String>, |
| 483 | /// The conditional-write token for exactly this version, in the |
| 484 | /// backend's dialect — the etag on S3 and Azure, the generation on |
| 485 | /// GCS. A conditional write pairs the check it made on this metadata |
| 486 | /// with the token, so a racing write cannot land in between. |
| 487 | pub cas: Option<String>, |
| 488 | pub uploaded_ms: i64, |
| 489 | pub attributes: BlobAttributes, |
| 490 | } |
| 491 | |
| 492 | /// A blob a `get` answered, with its body still on the wire. |
| 493 | pub struct Blob { |
| 494 | pub meta: BlobMeta, |
| 495 | /// The slice of the object this response carries, `(offset, length)`. |
| 496 | /// A bounded read that runs past the end is clamped by the store, so |
| 497 | /// this is what was served rather than what was asked for. |
| 498 | pub range: (u64, u64), |
| 499 | pub body: BoxStream<'static, Result<Vec<u8>, String>>, |
| 500 | } |
| 501 | |
| 502 | /// What a conditional read found. |
| 503 | pub enum BlobRead { |
| 504 | /// No such key. |
| 505 | Missing, |
| 506 | /// The key is there and the condition refused it. R2 answers the |
| 507 | /// object's metadata with no body, so the caller sees what it has. |
| 508 | Unmet(BlobMeta), |
| 509 | Hit(Blob), |
| 510 | } |
| 511 | |
| 512 | /// One object in a listing page. |
| 513 | pub struct BlobEntry { |
| 514 | pub key: String, |
| 515 | pub size: u64, |
| 516 | pub etag: Option<String>, |
| 517 | pub version: Option<String>, |
| 518 | pub uploaded_ms: i64, |
| 519 | } |
| 520 | |
| 521 | /// One page of a listing. |
| 522 | pub struct BlobPage { |
| 523 | pub objects: Vec<BlobEntry>, |
| 524 | /// The keys a delimiter rolled up, in key order and deduplicated. |
| 525 | pub prefixes: Vec<String>, |
| 526 | pub truncated: bool, |
| 527 | /// The last key this page consumed, whether it was listed or rolled |
| 528 | /// up. The next page resumes strictly after it, which is what R2's |
| 529 | /// opaque cursor does. |
| 530 | pub cursor: Option<String>, |
| 531 | } |
| 532 | |
| 533 | /// The user metadata on a response, as name/value pairs. `object_store` |
| 534 | /// parses the backend's `x-amz-meta-` / `x-goog-meta-` / `x-ms-meta-` |
| 535 | /// headers into `Attribute::Metadata`; every other attribute is a standard |
| 536 | /// HTTP header and not part of R2's `customMetadata`. |
| 537 | fn user_metadata(attributes: &Attributes) -> Vec<(String, String)> { |
| 538 | attributes |
| 539 | .iter() |
| 540 | .filter_map(|(attribute, value)| match attribute { |
| 541 | Attribute::Metadata(name) => { |
| 542 | Some((name.as_ref().to_string(), value.as_ref().to_string())) |
| 543 | } |
| 544 | _ => None, |
| 545 | }) |
| 546 | .collect() |
| 547 | } |
| 548 | |
| 549 | /// The paginated listing an injected store cannot serve. |
| 550 | /// |
| 551 | /// A test build constructs a bucket over plain injected stores, and a |
| 552 | /// paginated listing serves an operator command rather than a node |
| 553 | /// decision, so no injected store reaches one. Refusing is louder than an |
| 554 | /// empty page, which a caller would read as a fleet that holds no cells. |
| 555 | #[cfg(celld_internal_tests)] |
| 556 | #[derive(Debug)] |
| 557 | struct UnpaginatedStore; |
| 558 | |
| 559 | #[cfg(celld_internal_tests)] |
| 560 | #[async_trait::async_trait] |
| 561 | impl PaginatedListStore for UnpaginatedStore { |
| 562 | async fn list_paginated( |
| 563 | &self, |
| 564 | _prefix: Option<&str>, |
| 565 | _options: PaginatedListOptions, |
| 566 | ) -> object_store::Result<object_store::list::PaginatedListResult> { |
| 567 | Err(object_store::Error::NotSupported { |
| 568 | source: "an injected store serves no paginated listing".into(), |
| 569 | }) |
| 570 | } |
| 571 | } |
| 572 | |
| 573 | impl Bucket { |
| 574 | /// Builds a bucket from separate ordinary and paginated stores. |
| 575 | #[cfg(celld_internal_tests)] |
| 576 | #[doc(hidden)] |
| 577 | pub fn with_paginated_store_for_test( |
| 578 | store: Arc<dyn ObjectStore>, |
| 579 | paginated: Arc<dyn PaginatedListStore>, |
| 580 | prefix: String, |
| 581 | ) -> Self { |
| 582 | Self { |
| 583 | cas_store: store.clone(), |
| 584 | store, |
| 585 | paginated, |
| 586 | backend: StorageBackend::S3, |
| 587 | name: "telemetry-test".to_string(), |
| 588 | prefix, |
| 589 | } |
| 590 | } |
| 591 | |
| 592 | /// Builds a bucket over injected ordinary and conditional-write stores. |
| 593 | #[cfg(celld_internal_tests)] |
| 594 | #[doc(hidden)] |
| 595 | pub fn with_stores( |
| 596 | store: Arc<dyn ObjectStore>, |
| 597 | cas_store: Arc<dyn ObjectStore>, |
| 598 | backend: StorageBackend, |
| 599 | name: String, |
| 600 | prefix: String, |
| 601 | ) -> Self { |
| 602 | Self { |
| 603 | store, |
| 604 | paginated: Arc::new(UnpaginatedStore), |
| 605 | cas_store, |
| 606 | backend, |
| 607 | name, |
| 608 | prefix, |
| 609 | } |
| 610 | } |
| 611 | |
| 612 | /// `bucket` is `[s3://|gs://|az://]NAME[/PREFIX]`. With a PREFIX every |
| 613 | /// key this client reads or writes lives under `PREFIX/`, so several |
| 614 | /// fleets can share one bucket without colliding. |
| 615 | /// |
| 616 | /// A `gs://` bucket authenticates through Google Application Default |
| 617 | /// Credentials (or the `GOOGLE_*` service-account environment) and |
| 618 | /// takes no S3 endpoint, static credentials, or region — the bucket |
| 619 | /// carries its own location. |
| 620 | /// |
| 621 | /// An `az://` bucket names an Azure Blob Storage container, takes its |
| 622 | /// account from `AZURE_STORAGE_ACCOUNT_NAME`, and authenticates with a |
| 623 | /// storage account key, a managed identity, or a workload identity. It |
| 624 | /// takes no S3 endpoint, static credentials, or region either. |
| 625 | /// |
| 626 | /// `app` labels this client's traffic in the User-Agent (the aws |
| 627 | /// AppName format, `app/<name>`), keeping e.g. the lease safety lane |
| 628 | /// observable in black-box storage traces. |
| 629 | pub fn open( |
| 630 | bucket: &str, |
| 631 | endpoint: Option<&str>, |
| 632 | region: &str, |
| 633 | credentials: Option<StaticCredentials>, |
| 634 | app: Option<&str>, |
| 635 | ) -> anyhow::Result<Bucket> { |
| 636 | anyhow::ensure!( |
| 637 | !bucket.starts_with("dev://"), |
| 638 | "dev:// storage is internal to `celld dev` and is not a fleet bucket" |
| 639 | ); |
| 640 | Self::open_with_sources( |
| 641 | bucket, |
| 642 | endpoint, |
| 643 | region, |
| 644 | credentials, |
| 645 | app, |
| 646 | CloudSources::from_process(), |
| 647 | ) |
| 648 | } |
| 649 | |
| 650 | /// Open the machine-local development store. Only the `celld dev` |
| 651 | /// supervisor and its child node receive this constructor; fleet flags |
| 652 | /// continue to resolve exclusively through the cloud backend parser. |
| 653 | pub(crate) fn open_dev(database: &std::path::Path) -> anyhow::Result<Bucket> { |
| 654 | let store = Arc::new(crate::local_store::LocalStore::open(database)?); |
| 655 | Ok(Bucket { |
| 656 | store: store.clone(), |
| 657 | paginated: store.clone(), |
| 658 | cas_store: store, |
| 659 | backend: StorageBackend::Local, |
| 660 | name: database.display().to_string(), |
| 661 | prefix: String::new(), |
| 662 | }) |
| 663 | } |
| 664 | |
| 665 | /// The body of [`Self::open`], taking the cloud configuration instead |
| 666 | /// of deriving it from the `GOOGLE_*` and `AZURE_*` environments. A |
| 667 | /// caller that passes explicit sources is independent of that |
| 668 | /// environment. |
| 669 | #[doc(hidden)] |
| 670 | pub fn open_with_sources( |
| 671 | bucket: &str, |
| 672 | endpoint: Option<&str>, |
| 673 | region: &str, |
| 674 | credentials: Option<StaticCredentials>, |
| 675 | app: Option<&str>, |
| 676 | sources: CloudSources, |
| 677 | ) -> anyhow::Result<Bucket> { |
| 678 | let CloudSources { |
| 679 | gcs: gcs_builder, |
| 680 | azure: azure_env, |
| 681 | } = sources; |
| 682 | let (backend, bucket, prefix) = split_spec(bucket); |
| 683 | // The prefix is spliced into keys as plain text and stripped off |
| 684 | // listed keys the same way. A character `object_store` would |
| 685 | // percent-encode would make the two disagree, so refuse it here |
| 686 | // rather than mis-parse every listing later. |
| 687 | let illegal = |c: char| !c.is_ascii_alphanumeric() && !"-_./".contains(c); |
| 688 | if prefix.contains(illegal) { |
| 689 | anyhow::bail!("bucket prefix accepts only letters, digits and -_./: {prefix:?}"); |
| 690 | } |
| 691 | // These bounds mirror the aws-sdk TimeoutConfig they replace |
| 692 | // (connect 3 s / attempt 15 s / operation 30 s) — a correctness |
| 693 | // condition for the node self-fence, not tuning. The read-timeout |
| 694 | // knob collapses into the per-request bound. |
| 695 | let mut options = ClientOptions::new() |
| 696 | .with_timeout(Duration::from_secs(15)) |
| 697 | .with_connect_timeout(Duration::from_secs(3)) |
| 698 | .with_allow_http(true); |
| 699 | if let Some(app) = app { |
| 700 | options = options.with_user_agent( |
| 701 | hyper::header::HeaderValue::from_str(&format!("celld app/{app}")) |
| 702 | .context("app user agent")?, |
| 703 | ); |
| 704 | } |
| 705 | let retry = RetryConfig { |
| 706 | max_retries: 2, |
| 707 | retry_timeout: Duration::from_secs(30), |
| 708 | ..RetryConfig::default() |
| 709 | }; |
| 710 | // A conditional write retries zero times, and that is a correctness |
| 711 | // bound rather than a conservative default. A retry inside the |
| 712 | // transport repeats a `PUT` that can already have committed, and it |
| 713 | // repeats it with the same If-Match token, so the second attempt |
| 714 | // answers 412 for a write the first one applied. The caller then |
| 715 | // reads a clean lost race where it in fact still holds the record. |
| 716 | // A transport retry also spends the renewal attempt's own deadline: |
| 717 | // the actor bounds a renewal CAS to half of the remaining authority, |
| 718 | // and a hidden second attempt inside that bound removes the readback |
| 719 | // the core needs to resolve the first. Ownership of the retry belongs |
| 720 | // to the core, which schedules it against the authority that remains. |
| 721 | let cas_retry = RetryConfig { |
| 722 | max_retries: 0, |
| 723 | retry_timeout: Duration::from_secs(30), |
| 724 | ..RetryConfig::default() |
| 725 | }; |
| 726 | let (store, paginated, cas_store): ( |
| 727 | Arc<dyn ObjectStore>, |
| 728 | Arc<dyn PaginatedListStore>, |
| 729 | Arc<dyn ObjectStore>, |
| 730 | ) = match backend { |
| 731 | StorageBackend::S3 => { |
| 732 | // An endpoint can also arrive through the environment: |
| 733 | // `AmazonS3Builder::from_env` reads the AWS SDK's standard |
| 734 | // AWS_ENDPOINT_URL / AWS_ENDPOINT into the client. The |
| 735 | // path-style decision below must see that endpoint too — |
| 736 | // an env-supplied endpoint with virtual-hosted-style |
| 737 | // requests half-configures the client, and against an |
| 738 | // S3-compatible store every operation then fails with a |
| 739 | // NoSuchBucket that names the key prefix, pointing well |
| 740 | // away from the cause. An explicit argument (--endpoint / |
| 741 | // S3_ENDPOINT, resolved by the caller) still wins. |
| 742 | let endpoint = endpoint.map(str::to_string).or_else(resolve_env_endpoint); |
| 743 | let mut builder = AmazonS3Builder::from_env() |
| 744 | .with_bucket_name(bucket) |
| 745 | .with_region(region) |
| 746 | .with_conditional_put(S3ConditionalPut::ETagMatch) |
| 747 | .with_retry(retry) |
| 748 | .with_client_options(options); |
| 749 | if let Some(endpoint) = endpoint.as_deref() { |
| 750 | // Path-style against explicit S3-compatible endpoints, exactly |
| 751 | // as the aws client's force_path_style(endpoint.is_some()). |
| 752 | builder = builder |
| 753 | .with_endpoint(endpoint) |
| 754 | .with_virtual_hosted_style_request(false); |
| 755 | } else { |
| 756 | builder = builder.with_virtual_hosted_style_request(true); |
| 757 | } |
| 758 | if let Some(credentials) = credentials { |
| 759 | builder = builder |
| 760 | .with_access_key_id(credentials.access_key_id) |
| 761 | .with_secret_access_key(credentials.secret_access_key); |
| 762 | if let Some(token) = credentials.session_token { |
| 763 | builder = builder.with_token(token); |
| 764 | } |
| 765 | } |
| 766 | let cas_builder = builder.clone().with_retry(cas_retry); |
| 767 | let client = Arc::new(builder.build().context("build s3 client")?); |
| 768 | ( |
| 769 | client.clone(), |
| 770 | client, |
| 771 | Arc::new(cas_builder.build().context("build s3 cas client")?), |
| 772 | ) |
| 773 | } |
| 774 | StorageBackend::Gcs => { |
| 775 | // The generation dialect only. celld's S3 client fences |
| 776 | // with If-Match, which GCS does not apply to a PUT; and |
| 777 | // this GCS client authenticates with OAuth, not HMAC keys. |
| 778 | // So an S3 endpoint or S3 static credentials with gs:// is |
| 779 | // a configuration error, not something to quietly |
| 780 | // reinterpret. |
| 781 | if endpoint.is_some() { |
| 782 | anyhow::bail!( |
| 783 | "a gs:// bucket takes no S3 endpoint; unset --endpoint / S3_ENDPOINT" |
| 784 | ); |
| 785 | } |
| 786 | if credentials.is_some() { |
| 787 | anyhow::bail!( |
| 788 | "a gs:// bucket cannot use S3 static credentials; it authenticates \ |
| 789 | with Google Application Default Credentials" |
| 790 | ); |
| 791 | } |
| 792 | let builder = gcs_builder |
| 793 | .with_bucket_name(bucket) |
| 794 | .with_retry(retry) |
| 795 | .with_client_options(options); |
| 796 | let cas_builder = builder.clone().with_retry(cas_retry); |
| 797 | let client = Arc::new(builder.build().context("build gcs client")?); |
| 798 | ( |
| 799 | client.clone(), |
| 800 | client, |
| 801 | Arc::new(cas_builder.build().context("build gcs cas client")?), |
| 802 | ) |
| 803 | } |
| 804 | StorageBackend::Azure => { |
| 805 | // The etag dialect again — Put Blob applies If-None-Match |
| 806 | // and If-Match — but a different client and different |
| 807 | // credentials. So an S3 endpoint or S3 static credentials |
| 808 | // with az:// is a configuration error, exactly as it is |
| 809 | // with gs://, and not something to quietly reinterpret. |
| 810 | if endpoint.is_some() { |
| 811 | anyhow::bail!( |
| 812 | "an az:// bucket takes no S3 endpoint; unset --endpoint / S3_ENDPOINT" |
| 813 | ); |
| 814 | } |
| 815 | if credentials.is_some() { |
| 816 | anyhow::bail!( |
| 817 | "an az:// bucket cannot use S3 static credentials; it authenticates \ |
| 818 | with an Azure storage account key, a managed identity, or a \ |
| 819 | workload identity" |
| 820 | ); |
| 821 | } |
| 822 | let builder = azure_builder_for(&azure_env, bucket)? |
| 823 | .with_retry(retry) |
| 824 | .with_client_options(options); |
| 825 | let cas_builder = builder.clone().with_retry(cas_retry); |
| 826 | let client = Arc::new(builder.build().context("build azure client")?); |
| 827 | ( |
| 828 | client.clone(), |
| 829 | client, |
| 830 | Arc::new(cas_builder.build().context("build azure cas client")?), |
| 831 | ) |
| 832 | } |
| 833 | StorageBackend::Local => { |
| 834 | unreachable!("the local development store has its own constructor") |
| 835 | } |
| 836 | }; |
| 837 | Ok(Bucket { |
| 838 | store, |
| 839 | paginated, |
| 840 | cas_store, |
| 841 | backend, |
| 842 | name: bucket.to_string(), |
| 843 | prefix, |
| 844 | }) |
| 845 | } |
| 846 | |
| 847 | /// The bucket's URL scheme, `s3`, `gs` or `az`, for operator-facing |
| 848 | /// messages. |
| 849 | pub fn scheme(&self) -> &'static str { |
| 850 | self.backend.scheme() |
| 851 | } |
| 852 | |
| 853 | /// The dialect this bucket speaks, for choosing the matching |
| 854 | /// replication store. |
| 855 | #[doc(hidden)] |
| 856 | pub fn backend(&self) -> StorageBackend { |
| 857 | self.backend |
| 858 | } |
| 859 | |
| 860 | /// Scope a caller's key to this client's prefix. |
| 861 | fn key(&self, key: &str) -> String { |
| 862 | format!("{}{key}", self.prefix) |
| 863 | } |
| 864 | |
| 865 | /// The inverse of [`Self::key`]: a listing answers with full keys, and |
| 866 | /// every caller parses back the key it asked for, not the prefix. |
| 867 | fn unkey<'a>(&self, key: &'a str) -> &'a str { |
| 868 | key.strip_prefix(self.prefix.as_str()).unwrap_or(key) |
| 869 | } |
| 870 | |
| 871 | /// The location of a blob: the only way a blob key becomes a [`Path`], |
| 872 | /// and [`Self::listed_key`] is its inverse. |
| 873 | /// |
| 874 | /// Each segment is percent-encoded the way `Path::from` encodes it, so a |
| 875 | /// blob written before this mapping existed is still at its location. |
| 876 | /// `Path::from` also drops an empty segment, and that made `a/b`, `/a/b`, |
| 877 | /// `a//b`, and `a/b/` one object where R2 keeps four. An empty segment |
| 878 | /// is therefore stored as [`EMPTY_SEGMENT`], which `Path::from` never |
| 879 | /// produces because it encodes every `%`. |
| 880 | fn blob_path(&self, key: &str) -> Path { |
| 881 | let prefix = self |
| 882 | .prefix |
| 883 | .split('/') |
| 884 | .filter(|segment| !segment.is_empty()) |
| 885 | .map(PathPart::from); |
| 886 | // An empty key is the scope itself, not one empty segment below it. |
| 887 | let key = key |
| 888 | .split('/') |
| 889 | .filter(|_| !key.is_empty()) |
| 890 | .map(|segment| match segment { |
| 891 | "" => PathPart::parse(EMPTY_SEGMENT).expect("a lone % is a valid path part"), |
| 892 | segment => PathPart::from(segment), |
| 893 | }); |
| 894 | Path::from_iter(prefix.chain(key)) |
| 895 | } |
| 896 | |
| 897 | /// The key a caller wrote, recovered from a listed location. |
| 898 | /// |
| 899 | /// A listing answers with the encoded form [`Self::blob_path`] wrote, so |
| 900 | /// handing it back unchanged gives an R2 caller `p%C5%99ehled.html` for |
| 901 | /// `přehled.html`, and a `get` of it names no object |
| 902 | /// (denoland/celld#232). The encoding escapes `%` inside a segment, so |
| 903 | /// a lone `%` segment can only be an empty one. |
| 904 | /// |
| 905 | /// A location that celld did not write can decode to bytes that are not |
| 906 | /// UTF-8, such as `a%FF`, and that is an error. A lossy decode lists it |
| 907 | /// as `a\u{FFFD}`, which names no object, and the cursor re-encodes that |
| 908 | /// key as `a%EF%BF%BD`, which sorts before `a%FF`. A one-key page then |
| 909 | /// returns the same location again, and the listing never ends. |
| 910 | fn listed_key(&self, location: &Path) -> anyhow::Result<String> { |
| 911 | let segments = self |
| 912 | .unkey(location.as_ref()) |
| 913 | .split('/') |
| 914 | .map(|segment| match segment { |
| 915 | EMPTY_SEGMENT => Ok(std::borrow::Cow::Borrowed("")), |
| 916 | segment => percent_encoding::percent_decode_str(segment).decode_utf8(), |
| 917 | }) |
| 918 | .collect::<Result<Vec<_>, _>>() |
| 919 | .with_context(|| { |
| 920 | format!( |
| 921 | "list {}://{}/{location}: the key is not UTF-8", |
| 922 | self.scheme(), |
| 923 | self.name |
| 924 | ) |
| 925 | })?; |
| 926 | Ok(segments.join("/")) |
| 927 | } |
| 928 | |
| 929 | /// Body and CAS token, or `None` when the key does not exist. |
| 930 | pub async fn get(&self, key: &str) -> anyhow::Result<Option<(Bytes, String)>> { |
| 931 | let key = self.key(key); |
| 932 | match self.store.get(&Path::from(key.as_str())).await { |
| 933 | Ok(result) => { |
| 934 | let token = self |
| 935 | .backend |
| 936 | .token(result.meta.e_tag.clone(), result.meta.version.clone()) |
| 937 | .with_context(|| format!("read {}://{}/{key}", self.scheme(), self.name))?; |
| 938 | let bytes = result.bytes().await.with_context(|| { |
| 939 | format!("read body {}://{}/{key}", self.scheme(), self.name) |
| 940 | })?; |
| 941 | Ok(Some((bytes, token))) |
| 942 | } |
| 943 | Err(Error::NotFound { .. }) => Ok(None), |
| 944 | Err(error) => { |
| 945 | Err(anyhow!(error).context(format!("read {}://{}/{key}", self.scheme(), self.name))) |
| 946 | } |
| 947 | } |
| 948 | } |
| 949 | |
| 950 | /// Size and CAS token, or `None` when the key does not exist. |
| 951 | pub async fn head(&self, key: &str) -> anyhow::Result<Option<(u64, String)>> { |
| 952 | let key = self.key(key); |
| 953 | match self.store.head(&Path::from(key.as_str())).await { |
| 954 | Ok(meta) => { |
| 955 | let token = self |
| 956 | .backend |
| 957 | .token(meta.e_tag, meta.version) |
| 958 | .with_context(|| format!("head {}://{}/{key}", self.scheme(), self.name))?; |
| 959 | Ok(Some((meta.size, token))) |
| 960 | } |
| 961 | Err(Error::NotFound { .. }) => Ok(None), |
| 962 | Err(error) => { |
| 963 | Err(anyhow!(error).context(format!("head {}://{}/{key}", self.scheme(), self.name))) |
| 964 | } |
| 965 | } |
| 966 | } |
| 967 | |
| 968 | /// Write a large object from a stream in parts (homeflare: container |
| 969 | /// image tars, which are gigabytes). A single `put` has to finish within |
| 970 | /// the client's per-request timeout and holds the whole body in memory; |
| 971 | /// a part is one request of [`LARGE_PART`] bytes. The upload completes |
| 972 | /// only when `reader` reaches its end; an error aborts it, so a reader |
| 973 | /// cut short leaves nothing under the key. |
| 974 | pub async fn put_large( |
| 975 | &self, |
| 976 | key: &str, |
| 977 | mut reader: impl tokio::io::AsyncRead + Unpin, |
| 978 | ) -> anyhow::Result<u64> { |
| 979 | use tokio::io::AsyncReadExt; |
| 980 | let path = Path::from(self.key(key).as_str()); |
| 981 | let scoped = self.key(key); |
| 982 | let upload = self.store.put_multipart(&path).await.with_context(|| { |
| 983 | format!("begin multipart {}://{}/{scoped}", self.scheme(), self.name) |
| 984 | })?; |
| 985 | let mut writer = object_store::WriteMultipart::new_with_chunk_size(upload, LARGE_PART); |
| 986 | let mut buf = vec![0u8; 1 << 20]; |
| 987 | let mut total = 0u64; |
| 988 | let result: anyhow::Result<()> = async { |
| 989 | loop { |
| 990 | let n = reader.read(&mut buf).await.context("read the upload")?; |
| 991 | if n == 0 { |
| 992 | return Ok(()); |
| 993 | } |
| 994 | total += n as u64; |
| 995 | writer |
| 996 | .wait_for_capacity(LARGE_PARTS_IN_FLIGHT) |
| 997 | .await |
| 998 | .with_context(|| format!("write {}://{}/{scoped}", self.scheme(), self.name))?; |
| 999 | writer.write(&buf[..n]); |
| 1000 | } |
| 1001 | } |
| 1002 | .await; |
| 1003 | match result { |
| 1004 | Ok(()) => { |
| 1005 | writer.finish().await.with_context(|| { |
| 1006 | format!("complete {}://{}/{scoped}", self.scheme(), self.name) |
| 1007 | })?; |
| 1008 | Ok(total) |
| 1009 | } |
| 1010 | Err(error) => { |
| 1011 | let _ = writer.abort().await; |
| 1012 | Err(error) |
| 1013 | } |
| 1014 | } |
| 1015 | } |
| 1016 | |
| 1017 | /// Read a large object into `file` with ranged reads of [`LARGE_PART`] |
| 1018 | /// bytes, each its own request, so no one request has to carry the |
| 1019 | /// whole object within the client's timeout. `None` when the key does |
| 1020 | /// not exist. |
| 1021 | pub async fn get_large( |
| 1022 | &self, |
| 1023 | key: &str, |
| 1024 | file: &mut tokio::fs::File, |
| 1025 | ) -> anyhow::Result<Option<u64>> { |
| 1026 | use tokio::io::AsyncWriteExt; |
| 1027 | let Some((size, _)) = self.head(key).await? else { |
| 1028 | return Ok(None); |
| 1029 | }; |
| 1030 | let path = Path::from(self.key(key).as_str()); |
| 1031 | let scoped = self.key(key); |
| 1032 | let mut offset = 0u64; |
| 1033 | while offset < size { |
| 1034 | let end = (offset + LARGE_PART as u64).min(size); |
| 1035 | let options = GetOptions { |
| 1036 | range: Some(GetRange::Bounded(offset..end)), |
| 1037 | ..GetOptions::default() |
| 1038 | }; |
| 1039 | let bytes = self |
| 1040 | .store |
| 1041 | .get_opts(&path, options) |
| 1042 | .await |
| 1043 | .with_context(|| format!("read {}://{}/{scoped}", self.scheme(), self.name))? |
| 1044 | .bytes() |
| 1045 | .await |
| 1046 | .with_context(|| format!("read {}://{}/{scoped}", self.scheme(), self.name))?; |
| 1047 | if bytes.is_empty() { |
| 1048 | anyhow::bail!( |
| 1049 | "read {}://{}/{scoped}: empty range at {offset} of {size}", |
| 1050 | self.scheme(), |
| 1051 | self.name |
| 1052 | ); |
| 1053 | } |
| 1054 | file.write_all(&bytes) |
| 1055 | .await |
| 1056 | .context("write the downloaded object")?; |
| 1057 | offset += bytes.len() as u64; |
| 1058 | } |
| 1059 | file.flush().await.context("write the downloaded object")?; |
| 1060 | Ok(Some(size)) |
| 1061 | } |
| 1062 | |
| 1063 | pub async fn put(&self, key: &str, body: impl Into<PutPayload>) -> anyhow::Result<()> { |
| 1064 | let key = self.key(key); |
| 1065 | self.store |
| 1066 | .put(&Path::from(key.as_str()), body.into()) |
| 1067 | .await |
| 1068 | .with_context(|| format!("write {}://{}/{key}", self.scheme(), self.name))?; |
| 1069 | Ok(()) |
| 1070 | } |
| 1071 | |
| 1072 | /// Size plus one user-metadata value (`x-amz-meta-*` / `x-goog-meta-*` |
| 1073 | /// / `x-ms-meta-*`), or `None` when the key does not exist. A plain |
| 1074 | /// `head` cannot see user metadata; this one can, under either spelling |
| 1075 | /// of the name. |
| 1076 | pub async fn head_with_meta( |
| 1077 | &self, |
| 1078 | key: &str, |
| 1079 | name: &str, |
| 1080 | ) -> anyhow::Result<Option<(u64, Option<String>)>> { |
| 1081 | let key = self.key(key); |
| 1082 | let options = GetOptions { |
| 1083 | head: true, |
| 1084 | ..GetOptions::default() |
| 1085 | }; |
| 1086 | match self |
| 1087 | .store |
| 1088 | .get_opts(&Path::from(key.as_str()), options) |
| 1089 | .await |
| 1090 | { |
| 1091 | Ok(result) => { |
| 1092 | let value = BlobAttributes::read(&result.attributes) |
| 1093 | .metadata_value(name) |
| 1094 | .map(str::to_string); |
| 1095 | Ok(Some((result.meta.size, value))) |
| 1096 | } |
| 1097 | Err(Error::NotFound { .. }) => Ok(None), |
| 1098 | Err(error) => { |
| 1099 | Err(anyhow!(error).context(format!("head {}://{}/{key}", self.scheme(), self.name))) |
| 1100 | } |
| 1101 | } |
| 1102 | } |
| 1103 | |
| 1104 | /// Plain write carrying user metadata (`x-amz-meta-*` / `x-goog-meta-*` |
| 1105 | /// / `x-ms-meta-*`), each name spelled for the backend. |
| 1106 | pub async fn put_with_meta( |
| 1107 | &self, |
| 1108 | key: &str, |
| 1109 | body: impl Into<PutPayload>, |
| 1110 | meta: &[(&'static str, &str)], |
| 1111 | ) -> anyhow::Result<()> { |
| 1112 | let key = self.key(key); |
| 1113 | let attributes = BlobAttributes { |
| 1114 | metadata: meta |
| 1115 | .iter() |
| 1116 | .map(|(name, value)| (name.to_string(), value.to_string())) |
| 1117 | .collect(), |
| 1118 | ..BlobAttributes::default() |
| 1119 | }; |
| 1120 | let options = PutOptions { |
| 1121 | attributes: attributes.write(self.backend), |
| 1122 | ..PutOptions::default() |
| 1123 | }; |
| 1124 | self.store |
| 1125 | .put_opts(&Path::from(key.as_str()), body.into(), options) |
| 1126 | .await |
| 1127 | .with_context(|| format!("write {}://{}/{key}", self.scheme(), self.name))?; |
| 1128 | Ok(()) |
| 1129 | } |
| 1130 | |
| 1131 | /// Conditional write. `token: None` requires the key to be absent; |
| 1132 | /// `Some` requires the current CAS token — the etag on S3 and on |
| 1133 | /// Azure Blob Storage (If-Match), the generation on GCS |
| 1134 | /// (x-goog-if-generation-match). |
| 1135 | /// `Ok(Some(new_token))` applied, `Ok(None)` cleanly rejected; any |
| 1136 | /// other failure is ambiguous and stays an error. |
| 1137 | pub async fn put_cas( |
| 1138 | &self, |
| 1139 | key: &str, |
| 1140 | body: impl Into<PutPayload>, |
| 1141 | token: Option<&str>, |
| 1142 | ) -> anyhow::Result<Option<String>> { |
| 1143 | let key = self.key(key); |
| 1144 | let mode = match token { |
| 1145 | None => PutMode::Create, |
| 1146 | Some(token) => PutMode::Update(self.backend.update(token)), |
| 1147 | }; |
| 1148 | match self |
| 1149 | .cas_store |
| 1150 | .put_opts( |
| 1151 | &Path::from(key.as_str()), |
| 1152 | body.into(), |
| 1153 | PutOptions::from(mode), |
| 1154 | ) |
| 1155 | .await |
| 1156 | { |
| 1157 | Ok(result) => { |
| 1158 | // The write applied; a result without a usable token still |
| 1159 | // surfaces as `Err`, which callers already treat as "may |
| 1160 | // have committed" and reconcile. |
| 1161 | let token = self |
| 1162 | .backend |
| 1163 | .token(result.e_tag, result.version) |
| 1164 | .with_context(|| { |
| 1165 | format!( |
| 1166 | "conditional write {}://{}/{key} applied without a CAS token", |
| 1167 | self.scheme(), |
| 1168 | self.name |
| 1169 | ) |
| 1170 | })?; |
| 1171 | Ok(Some(token)) |
| 1172 | } |
| 1173 | Err(error) if is_clean_cas_rejection(&error) => Ok(None), |
| 1174 | Err(error) => Err(anyhow!(error).context(format!( |
| 1175 | "conditional write {}://{}/{key} may have committed", |
| 1176 | self.scheme(), |
| 1177 | self.name |
| 1178 | ))), |
| 1179 | } |
| 1180 | } |
| 1181 | |
| 1182 | /// Idempotent: deleting an absent key succeeds, as S3's DELETE does. |
| 1183 | pub async fn delete(&self, key: &str) -> anyhow::Result<()> { |
| 1184 | let key = self.key(key); |
| 1185 | match self.store.delete(&Path::from(key.as_str())).await { |
| 1186 | Ok(()) | Err(Error::NotFound { .. }) => Ok(()), |
| 1187 | Err(error) => Err(anyhow!(error).context(format!( |
| 1188 | "delete {}://{}/{key}", |
| 1189 | self.scheme(), |
| 1190 | self.name |
| 1191 | ))), |
| 1192 | } |
| 1193 | } |
| 1194 | |
| 1195 | /// Batched delete: the S3-family backends fold this into DeleteObjects |
| 1196 | /// requests (up to 1,000 keys per class A operation) — the lab priced |
| 1197 | /// bundle GC's one-key-at-a-time deletes at 9k operations an hour. |
| 1198 | /// Returns the keys that are now gone; an absent key counts as gone, |
| 1199 | /// and a key that fails stays listed for the next pass. |
| 1200 | pub async fn delete_many(&self, keys: &[String]) -> Vec<String> { |
| 1201 | self.delete_paths( |
| 1202 | keys.iter() |
| 1203 | .map(|key| Path::from(self.key(key).as_str())) |
| 1204 | .collect(), |
| 1205 | ) |
| 1206 | .await |
| 1207 | } |
| 1208 | |
| 1209 | /// [`Self::delete_many`] for blob keys, which address their objects |
| 1210 | /// through [`Self::blob_path`]. Returns how many are now gone. |
| 1211 | pub async fn delete_blobs(&self, keys: &[String]) -> usize { |
| 1212 | self.delete_paths(keys.iter().map(|key| self.blob_path(key)).collect()) |
| 1213 | .await |
| 1214 | .len() |
| 1215 | } |
| 1216 | |
| 1217 | async fn delete_paths(&self, paths: Vec<Path>) -> Vec<String> { |
| 1218 | let count = paths.len(); |
| 1219 | let locations = futures_util::stream::iter(paths.into_iter().map(Ok)).boxed(); |
| 1220 | let mut gone = Vec::with_capacity(count); |
| 1221 | let mut results = self.store.delete_stream(locations); |
| 1222 | while let Some(result) = results.next().await { |
| 1223 | match result { |
| 1224 | Ok(path) => gone.push(self.unkey(path.as_ref()).to_string()), |
| 1225 | Err(Error::NotFound { path, .. }) => { |
| 1226 | gone.push(self.unkey(&path).to_string()); |
| 1227 | } |
| 1228 | Err(error) => { |
| 1229 | tracing::warn!(%error, "batched delete left a key for the next pass"); |
| 1230 | } |
| 1231 | } |
| 1232 | } |
| 1233 | gone |
| 1234 | } |
| 1235 | |
| 1236 | /// Every object under `prefix/`; the client paginates internally. |
| 1237 | /// Listed keys come back the way the caller wrote them, because the |
| 1238 | /// caller parses them and knows nothing of the fleet's prefix. |
| 1239 | pub async fn list(&self, prefix: &str) -> anyhow::Result<Vec<ObjectMeta>> { |
| 1240 | let path = Path::from(self.key(prefix.trim_end_matches('/'))); |
| 1241 | let mut stream = self.store.list(Some(&path)); |
| 1242 | let mut objects = Vec::new(); |
| 1243 | while let Some(meta) = stream.next().await { |
| 1244 | let mut meta = |
| 1245 | meta.with_context(|| format!("list {}://{}/{path}", self.scheme(), self.name))?; |
| 1246 | if !self.prefix.is_empty() { |
| 1247 | // The listing gave object_store a valid key, so re-parsing |
| 1248 | // the tail of it cannot fail. |
| 1249 | meta.location = Path::parse(self.unkey(meta.location.as_ref())).unwrap(); |
| 1250 | } |
| 1251 | objects.push(meta); |
| 1252 | } |
| 1253 | Ok(objects) |
| 1254 | } |
| 1255 | |
| 1256 | /// Does anything exist under `prefix/`? One page at most. |
| 1257 | pub async fn list_any(&self, prefix: &str) -> anyhow::Result<bool> { |
| 1258 | let path = Path::from(self.key(prefix.trim_end_matches('/'))); |
| 1259 | match self.store.list(Some(&path)).next().await { |
| 1260 | None => Ok(false), |
| 1261 | Some(Ok(_)) => Ok(true), |
| 1262 | Some(Err(error)) => Err(anyhow!(error).context(format!( |
| 1263 | "list {}://{}/{path}", |
| 1264 | self.scheme(), |
| 1265 | self.name |
| 1266 | ))), |
| 1267 | } |
| 1268 | } |
| 1269 | |
| 1270 | /// One provider page of objects under `prefix/`. |
| 1271 | /// |
| 1272 | /// The opaque token resumes the same listing with the same prefix and |
| 1273 | /// limit. A maintenance caller must finish and release this page before |
| 1274 | /// it asks for the next one, or pagination would bound requests without |
| 1275 | /// bounding retained object descriptions. |
| 1276 | pub(crate) async fn objects_page( |
| 1277 | &self, |
| 1278 | prefix: &str, |
| 1279 | page_token: Option<String>, |
| 1280 | max_keys: usize, |
| 1281 | ) -> anyhow::Result<ObjectPage> { |
| 1282 | // `PaginatedListStore` does not append the separator that |
| 1283 | // `ObjectStore::list` appends to a path-segment prefix. |
| 1284 | let path = if prefix.is_empty() { |
| 1285 | self.key("") |
| 1286 | } else { |
| 1287 | self.key(&format!("{}/", prefix.trim_end_matches('/'))) |
| 1288 | }; |
| 1289 | let mut result = self |
| 1290 | .paginated |
| 1291 | .list_paginated( |
| 1292 | Some(path.as_str()), |
| 1293 | PaginatedListOptions { |
| 1294 | max_keys: Some(max_keys), |
| 1295 | page_token, |
| 1296 | ..PaginatedListOptions::default() |
| 1297 | }, |
| 1298 | ) |
| 1299 | .await |
| 1300 | .with_context(|| format!("list {}://{}/{path}", self.scheme(), self.name))?; |
| 1301 | if !self.prefix.is_empty() { |
| 1302 | for object in &mut result.result.objects { |
| 1303 | object.location = Path::parse(self.unkey(object.location.as_ref())).unwrap(); |
| 1304 | } |
| 1305 | } |
| 1306 | Ok(ObjectPage { |
| 1307 | objects: result.result.objects, |
| 1308 | page_token: result.page_token, |
| 1309 | }) |
| 1310 | } |
| 1311 | |
| 1312 | /// One page of the immediate child "directories" that start with `prefix`. |
| 1313 | /// |
| 1314 | /// `start_after` resumes from a child a previous page returned, and |
| 1315 | /// `page_token` continues the same walk. Pass one or the other: a |
| 1316 | /// token is exact and works on every backend, while `start_after` |
| 1317 | /// survives between separate processes, so an operator can resume a |
| 1318 | /// listing by name. |
| 1319 | /// |
| 1320 | /// The store compares `start_after` against object keys, not against |
| 1321 | /// children, and every key below `prefix/child/` sorts after that |
| 1322 | /// prefix itself. So the page that resumes a walk repeats the child it |
| 1323 | /// resumed from, and the caller drops it. The reverse error would skip |
| 1324 | /// a cell, so the boundary is deliberately inclusive. |
| 1325 | pub async fn common_prefixes_page( |
| 1326 | &self, |
| 1327 | prefix: &str, |
| 1328 | start_after: Option<&str>, |
| 1329 | page_token: Option<String>, |
| 1330 | max_keys: usize, |
| 1331 | ) -> anyhow::Result<CommonPrefixPage> { |
| 1332 | // Keep the caller's exact prefix. Most callers use a directory prefix |
| 1333 | // such as `cells/`, but a class-filtered cell walk uses `cells/Class:` |
| 1334 | // so the store excludes every other class before it applies the bound. |
| 1335 | let path = self.key(prefix); |
| 1336 | if start_after.is_some() && self.backend == StorageBackend::Azure { |
| 1337 | anyhow::bail!( |
| 1338 | "az:// cannot resume a listing by name, because Azure listing has no \ |
| 1339 | start-after; drop --after and list the whole container" |
| 1340 | ); |
| 1341 | } |
| 1342 | let result = self |
| 1343 | .paginated |
| 1344 | .list_paginated( |
| 1345 | Some(path.as_str()), |
| 1346 | PaginatedListOptions { |
| 1347 | offset: start_after.map(|child| self.key(&format!("{child}/"))), |
| 1348 | delimiter: Some(std::borrow::Cow::Borrowed("/")), |
| 1349 | max_keys: Some(max_keys), |
| 1350 | page_token, |
| 1351 | ..PaginatedListOptions::default() |
| 1352 | }, |
| 1353 | ) |
| 1354 | .await |
| 1355 | .with_context(|| format!("list {}://{}/{path}", self.scheme(), self.name))?; |
| 1356 | Ok(CommonPrefixPage { |
| 1357 | prefixes: result |
| 1358 | .result |
| 1359 | .common_prefixes |
| 1360 | .into_iter() |
| 1361 | .map(|child| self.unkey(child.as_ref()).to_string()) |
| 1362 | .collect(), |
| 1363 | page_token: result.page_token, |
| 1364 | }) |
| 1365 | } |
| 1366 | |
| 1367 | /// Immediate child "directories" under `prefix/` (delimiter listing), |
| 1368 | /// as full prefixes with the trailing slash stripped. |
| 1369 | /// |
| 1370 | /// Every page is drained into one buffer, so the cost is the whole |
| 1371 | /// listing. A caller that only needs a bounded answer must use |
| 1372 | /// [`Self::common_prefixes_page`] instead. |
| 1373 | pub async fn common_prefixes(&self, prefix: &str) -> anyhow::Result<Vec<String>> { |
| 1374 | let path = Path::from(self.key(prefix.trim_end_matches('/'))); |
| 1375 | let result = self |
| 1376 | .store |
| 1377 | .list_with_delimiter(Some(&path)) |
| 1378 | .await |
| 1379 | .with_context(|| format!("list {}://{}/{path}", self.scheme(), self.name))?; |
| 1380 | Ok(result |
| 1381 | .common_prefixes |
| 1382 | .into_iter() |
| 1383 | .map(|p| self.unkey(p.as_ref()).to_string()) |
| 1384 | .collect()) |
| 1385 | } |
| 1386 | |
| 1387 | // ---- R2 binding primitives ------------------------------------------ |
| 1388 | // |
| 1389 | // An `r2_buckets` binding is served out of the fleet bucket under the |
| 1390 | // reserved `r2/<bucket_name>/` prefix, so a Worker's blobs share the |
| 1391 | // durability and the credentials of everything else celld stores and |
| 1392 | // need no second bucket. These are the only operations that reach past |
| 1393 | // the in-memory `Bytes` contract the rest of this module keeps: a blob |
| 1394 | // is a Worker's payload and can be far larger than a fleet object, so |
| 1395 | // it is read as a stream and a large write goes through multipart. |
| 1396 | |
| 1397 | /// Everything about an object except its bytes, or `None` when the key |
| 1398 | /// does not exist. This is R2's `head`, and the read half of every |
| 1399 | /// conditional write. |
| 1400 | pub async fn head_blob(&self, key: &str) -> anyhow::Result<Option<BlobMeta>> { |
| 1401 | let path = self.blob_path(key); |
| 1402 | let key = self.key(key); |
| 1403 | let options = GetOptions { |
| 1404 | head: true, |
| 1405 | ..GetOptions::default() |
| 1406 | }; |
| 1407 | match self.store.get_opts(&path, options).await { |
| 1408 | Ok(result) => Ok(Some(self.blob_meta(&result.meta, &result.attributes))), |
| 1409 | Err(Error::NotFound { .. }) => Ok(None), |
| 1410 | Err(error) => { |
| 1411 | Err(anyhow!(error).context(format!("head {}://{}/{key}", self.scheme(), self.name))) |
| 1412 | } |
| 1413 | } |
| 1414 | } |
| 1415 | |
| 1416 | /// One blob a `get` answered, with its body still on the wire. |
| 1417 | pub async fn get_blob( |
| 1418 | &self, |
| 1419 | key: &str, |
| 1420 | range: BlobRange, |
| 1421 | conditions: &BlobConditions, |
| 1422 | ) -> anyhow::Result<BlobRead> { |
| 1423 | let scoped = self.key(key); |
| 1424 | let options = GetOptions { |
| 1425 | range: match range { |
| 1426 | BlobRange::Whole => None, |
| 1427 | BlobRange::From(offset) => Some(GetRange::Offset(offset)), |
| 1428 | BlobRange::Bounded { offset, length } => { |
| 1429 | Some(GetRange::Bounded(offset..offset.saturating_add(length))) |
| 1430 | } |
| 1431 | BlobRange::Suffix(length) => Some(GetRange::Suffix(length)), |
| 1432 | }, |
| 1433 | if_match: conditions.if_match.clone(), |
| 1434 | if_none_match: conditions.if_none_match.clone(), |
| 1435 | ..GetOptions::default() |
| 1436 | }; |
| 1437 | let result = match self.store.get_opts(&self.blob_path(key), options).await { |
| 1438 | Ok(result) => result, |
| 1439 | // Only an absent key is a miss. A range that overshoots the end |
| 1440 | // of the object is served short, as R2 serves it; a range that |
| 1441 | // *starts* past the end is a 416, and it stays an error rather |
| 1442 | // than being turned into a miss, because that is what R2 does |
| 1443 | // with one too. |
| 1444 | Err(Error::NotFound { .. }) => return Ok(BlobRead::Missing), |
| 1445 | // The store says only that the condition failed. R2 answers a |
| 1446 | // refused `onlyIf` with the object itself, minus the body, so |
| 1447 | // one more head fills in what the caller is entitled to see. |
| 1448 | Err(Error::Precondition { .. } | Error::NotModified { .. }) => { |
| 1449 | return Ok(match self.head_blob(key).await? { |
| 1450 | Some(meta) => BlobRead::Unmet(meta), |
| 1451 | None => BlobRead::Missing, |
| 1452 | }) |
| 1453 | } |
| 1454 | Err(error) => { |
| 1455 | return Err(anyhow!(error).context(format!( |
| 1456 | "read {}://{}/{scoped}", |
| 1457 | self.scheme(), |
| 1458 | self.name |
| 1459 | ))) |
| 1460 | } |
| 1461 | }; |
| 1462 | let meta = self.blob_meta(&result.meta, &result.attributes); |
| 1463 | // The upload-time half of `onlyIf` is answered here, against the |
| 1464 | // millisecond the object carries. The body is dropped unread. |
| 1465 | if !conditions.time_met(meta.uploaded_ms) { |
| 1466 | return Ok(BlobRead::Unmet(meta)); |
| 1467 | } |
| 1468 | // `range` is the slice this response actually carries, which is |
| 1469 | // what the caller reads; a bounded request past the end is clamped |
| 1470 | // here rather than by the store. |
| 1471 | let served = result.range.clone(); |
| 1472 | let label = format!("read body {}://{}/{scoped}", self.scheme(), self.name); |
| 1473 | let body = result |
| 1474 | .into_stream() |
| 1475 | .map(move |chunk| match chunk { |
| 1476 | Ok(bytes) => Ok(bytes.to_vec()), |
| 1477 | Err(error) => Err(format!("{label}: {error}")), |
| 1478 | }) |
| 1479 | .boxed(); |
| 1480 | Ok(BlobRead::Hit(Blob { |
| 1481 | meta, |
| 1482 | range: (served.start, served.end.saturating_sub(served.start)), |
| 1483 | body, |
| 1484 | })) |
| 1485 | } |
| 1486 | |
| 1487 | /// A plain (non-multipart) write, carrying R2's `httpMetadata` and |
| 1488 | /// `customMetadata`. |
| 1489 | /// |
| 1490 | /// `conditions` is R2's `onlyIf`, and is answered by reading the |
| 1491 | /// object first and pairing the verdict with that version's CAS token: |
| 1492 | /// the check and the write then apply to the same version, and a racing |
| 1493 | /// write between them is refused rather than overwritten. `Ok(None)` is |
| 1494 | /// a refused precondition — R2 reports one as a `null` return, not a |
| 1495 | /// throw — and every other failure stays an error. |
| 1496 | pub async fn put_blob( |
| 1497 | &self, |
| 1498 | key: &str, |
| 1499 | body: PutPayload, |
| 1500 | attributes: &BlobAttributes, |
| 1501 | conditions: &BlobConditions, |
| 1502 | ) -> anyhow::Result<Option<BlobMeta>> { |
| 1503 | let size = body.content_length() as u64; |
| 1504 | let mode = match conditions.is_empty() { |
| 1505 | true => PutMode::Overwrite, |
| 1506 | false => match self.head_blob(key).await? { |
| 1507 | Some(current) => { |
| 1508 | if !conditions.etag_met(current.etag.as_deref()) |
| 1509 | || !conditions.time_met(current.uploaded_ms) |
| 1510 | { |
| 1511 | return Ok(None); |
| 1512 | } |
| 1513 | let Some(cas) = current.cas else { |
| 1514 | return Err(anyhow!( |
| 1515 | "conditional R2 write of {}://{}/{key} cannot be fenced: \ |
| 1516 | the store answered no version token", |
| 1517 | self.scheme(), |
| 1518 | self.name |
| 1519 | )); |
| 1520 | }; |
| 1521 | PutMode::Update(self.backend.update(&cas)) |
| 1522 | } |
| 1523 | // Nothing there: only a condition that an absent object can |
| 1524 | // satisfy may write, and it writes as a create so that a |
| 1525 | // racing create loses. |
| 1526 | None => match conditions.etag_met(None) { |
| 1527 | true => PutMode::Create, |
| 1528 | false => return Ok(None), |
| 1529 | }, |
| 1530 | }, |
| 1531 | }; |
| 1532 | let conditional = !matches!(mode, PutMode::Overwrite); |
| 1533 | let store = match conditional { |
| 1534 | true => &self.cas_store, |
| 1535 | false => &self.store, |
| 1536 | }; |
| 1537 | let scoped = self.key(key); |
| 1538 | let options = PutOptions { |
| 1539 | mode, |
| 1540 | attributes: attributes.write(self.backend), |
| 1541 | ..PutOptions::default() |
| 1542 | }; |
| 1543 | match store.put_opts(&self.blob_path(key), body, options).await { |
| 1544 | Ok(result) => Ok(Some(BlobMeta { |
| 1545 | size, |
| 1546 | cas: self |
| 1547 | .backend |
| 1548 | .token(result.e_tag.clone(), result.version.clone()) |
| 1549 | .ok(), |
| 1550 | etag: result.e_tag, |
| 1551 | version: result.version, |
| 1552 | uploaded_ms: crate::asyncrt::wall_ms(), |
| 1553 | attributes: attributes.clone(), |
| 1554 | })), |
| 1555 | // A racing write took the version this one checked. The |
| 1556 | // caller's precondition is no longer true, which is the answer |
| 1557 | // R2 would have given had the race gone the other way. |
| 1558 | Err(error) if conditional && is_clean_cas_rejection(&error) => Ok(None), |
| 1559 | Err(error) => Err(anyhow!(error).context(format!( |
| 1560 | "write {}://{}/{scoped}", |
| 1561 | self.scheme(), |
| 1562 | self.name |
| 1563 | ))), |
| 1564 | } |
| 1565 | } |
| 1566 | |
| 1567 | /// One listing page: every object whose full key starts with `prefix`, |
| 1568 | /// in key order, resuming strictly after `after`. `limit` bounds the |
| 1569 | /// page, counting a rolled-up prefix as R2 counts one — against the |
| 1570 | /// same limit as an object. |
| 1571 | /// |
| 1572 | /// `prefix` is a raw string prefix, as R2's is, not the directory |
| 1573 | /// prefix the rest of this module lists by: the store is asked for the |
| 1574 | /// enclosing directory and the tail is matched here. |
| 1575 | /// |
| 1576 | /// `delimiter` is R2's: the run of a key between the end of `prefix` |
| 1577 | /// and the delimiter's first occurrence after it stands in for every |
| 1578 | /// key sharing it, and those keys are not listed individually. |
| 1579 | pub async fn list_page( |
| 1580 | &self, |
| 1581 | prefix: &str, |
| 1582 | after: Option<&str>, |
| 1583 | limit: usize, |
| 1584 | delimiter: Option<&str>, |
| 1585 | ) -> anyhow::Result<BlobPage> { |
| 1586 | let directory = prefix.rsplit_once('/').map_or("", |(head, _)| head); |
| 1587 | let path = self.blob_path(directory); |
| 1588 | let mut stream = match after { |
| 1589 | Some(after) => self |
| 1590 | .store |
| 1591 | .list_with_offset(Some(&path), &self.blob_path(after)), |
| 1592 | None => self.store.list(Some(&path)), |
| 1593 | }; |
| 1594 | let delimiter = delimiter.filter(|delimiter| !delimiter.is_empty()); |
| 1595 | let mut page = BlobPage { |
| 1596 | objects: Vec::with_capacity(limit.min(1024)), |
| 1597 | prefixes: Vec::new(), |
| 1598 | truncated: false, |
| 1599 | cursor: None, |
| 1600 | }; |
| 1601 | // The rolled-up prefixes seen so far. A listing is in key order, so |
| 1602 | // a run of keys under one prefix is contiguous and only the newest |
| 1603 | // prefix can repeat — but a delimiter is any string, not only `/`, |
| 1604 | // so `prefix` can be re-entered later and the set is kept whole. |
| 1605 | // Ordered, because nothing in the engine may hold state a replay |
| 1606 | // would walk in a different order. |
| 1607 | let mut rolled = std::collections::BTreeSet::new(); |
| 1608 | while let Some(meta) = stream.next().await { |
| 1609 | let meta = |
| 1610 | meta.with_context(|| format!("list {}://{}/{path}", self.scheme(), self.name))?; |
| 1611 | let key = self.listed_key(&meta.location)?; |
| 1612 | let key = key.as_str(); |
| 1613 | let Some(remainder) = key.strip_prefix(prefix) else { |
| 1614 | continue; |
| 1615 | }; |
| 1616 | let group = delimiter.and_then(|delimiter| { |
| 1617 | remainder |
| 1618 | .find(delimiter) |
| 1619 | .map(|at| format!("{prefix}{}", &remainder[..at + delimiter.len()])) |
| 1620 | }); |
| 1621 | // A prefix already rolled up costs nothing and does not end the |
| 1622 | // page: it is the same entry the caller has already been given. |
| 1623 | if let Some(group) = &group { |
| 1624 | if rolled.contains(group) { |
| 1625 | page.cursor = Some(key.to_string()); |
| 1626 | continue; |
| 1627 | } |
| 1628 | } |
| 1629 | if page.objects.len() + page.prefixes.len() == limit { |
| 1630 | page.truncated = true; |
| 1631 | break; |
| 1632 | } |
| 1633 | match group { |
| 1634 | Some(group) => { |
| 1635 | rolled.insert(group.clone()); |
| 1636 | page.prefixes.push(group); |
| 1637 | } |
| 1638 | None => page.objects.push(BlobEntry { |
| 1639 | key: key.to_string(), |
| 1640 | size: meta.size, |
| 1641 | etag: meta.e_tag, |
| 1642 | version: meta.version, |
| 1643 | uploaded_ms: meta.last_modified.timestamp_millis(), |
| 1644 | }), |
| 1645 | } |
| 1646 | page.cursor = Some(key.to_string()); |
| 1647 | } |
| 1648 | if !page.truncated { |
| 1649 | page.cursor = None; |
| 1650 | } |
| 1651 | Ok(page) |
| 1652 | } |
| 1653 | |
| 1654 | /// Open a multipart upload carrying R2's `httpMetadata` and |
| 1655 | /// `customMetadata`. The parts and the completion ride on the returned |
| 1656 | /// handle. |
| 1657 | pub async fn begin_multipart( |
| 1658 | &self, |
| 1659 | key: &str, |
| 1660 | attributes: &BlobAttributes, |
| 1661 | ) -> anyhow::Result<Box<dyn MultipartUpload>> { |
| 1662 | let path = self.blob_path(key); |
| 1663 | let key = self.key(key); |
| 1664 | let options = PutMultipartOptions { |
| 1665 | attributes: attributes.write(self.backend), |
| 1666 | ..PutMultipartOptions::default() |
| 1667 | }; |
| 1668 | self.store |
| 1669 | .put_multipart_opts(&path, options) |
| 1670 | .await |
| 1671 | .with_context(|| format!("begin multipart {}://{}/{key}", self.scheme(), self.name)) |
| 1672 | } |
| 1673 | |
| 1674 | /// One object's metadata, in the shape every R2 answer carries. |
| 1675 | fn blob_meta(&self, meta: &ObjectMeta, attributes: &Attributes) -> BlobMeta { |
| 1676 | BlobMeta { |
| 1677 | size: meta.size, |
| 1678 | etag: meta.e_tag.clone(), |
| 1679 | version: meta.version.clone(), |
| 1680 | cas: self |
| 1681 | .backend |
| 1682 | .token(meta.e_tag.clone(), meta.version.clone()) |
| 1683 | .ok(), |
| 1684 | uploaded_ms: meta.last_modified.timestamp_millis(), |
| 1685 | attributes: BlobAttributes::read(attributes), |
| 1686 | } |
| 1687 | } |
| 1688 | |
| 1689 | /// The head_bucket replacement: prove the bucket is reachable and the |
| 1690 | /// credential is accepted with one list page. Scoped to the prefix, so |
| 1691 | /// a credential scoped to it validates too. |
| 1692 | pub async fn validate(&self) -> anyhow::Result<()> { |
| 1693 | let scope = (!self.prefix.is_empty()).then(|| Path::from(self.prefix.as_str())); |
| 1694 | match self.store.list(scope.as_ref()).next().await { |
| 1695 | None | Some(Ok(_)) => Ok(()), |
| 1696 | Some(Err(error)) => { |
| 1697 | Err(anyhow!(error).context(format!("validate {}://{}", self.scheme(), self.name))) |
| 1698 | } |
| 1699 | } |
| 1700 | } |
| 1701 | |
| 1702 | /// Run the conditional-write contract against the live bucket. |
| 1703 | /// |
| 1704 | /// A store can accept a precondition header and then ignore it, and no |
| 1705 | /// capability API answers whether it does. So the probe provokes the |
| 1706 | /// two rejections a conforming store must produce, and checks it |
| 1707 | /// produced them. celld decides which node owns a cell with a |
| 1708 | /// conditional write, so a store that applies a write it must reject |
| 1709 | /// lets two nodes own one cell (denoland/celld#137). |
| 1710 | /// |
| 1711 | /// The two outcomes are separated because they need different |
| 1712 | /// responses. A `Violation` is a property of the store and never |
| 1713 | /// clears, so it can stop a node. An `Err` is ambiguous — a network |
| 1714 | /// fault, a rejected credential — and a retry can clear it, so a |
| 1715 | /// caller that must not fail on a transient blip keeps serving. |
| 1716 | pub(crate) async fn probe_cas_steps(&self) -> anyhow::Result<StorageProbeVerdict> { |
| 1717 | let key = Self::probe_key("cas"); |
| 1718 | let verdict = self.cas_contract(&key).await; |
| 1719 | // The object is debris on every path, so retire it before the |
| 1720 | // verdict. A delete that fails leaves one tiny object under |
| 1721 | // `probe/`, which nothing lists and nothing reads — but a |
| 1722 | // credential that cannot delete accrues one per boot, so say so. |
| 1723 | if let Err(error) = self.delete(&key).await { |
| 1724 | tracing::warn!(%error, "the conditional-write probe could not delete its object"); |
| 1725 | } |
| 1726 | verdict |
| 1727 | } |
| 1728 | |
| 1729 | /// Run every storage check that a node needs before it serves. |
| 1730 | /// |
| 1731 | /// A clear unsupported-operation response is permanent, so it becomes a |
| 1732 | /// contract violation. Other errors remain ambiguous so the startup |
| 1733 | /// caller can retry the complete probe with fresh keys. |
| 1734 | pub(crate) async fn probe_startup_storage_steps(&self) -> anyhow::Result<StorageProbeVerdict> { |
| 1735 | match self.probe_cas_steps().await { |
| 1736 | Ok(StorageProbeVerdict::Conformant) => {} |
| 1737 | Ok(violation) => return Ok(violation), |
| 1738 | Err(error) if is_unsupported_operation(&error) => { |
| 1739 | return Ok(StorageProbeVerdict::Violation( |
| 1740 | "the store does not support conditional writes, so celld cannot acquire a cell" |
| 1741 | .to_string(), |
| 1742 | )); |
| 1743 | } |
| 1744 | Err(error) => return Err(error), |
| 1745 | } |
| 1746 | |
| 1747 | match self.probe_range_steps().await { |
| 1748 | Err(error) if is_unsupported_operation(&error) || is_invalid_range_response(&error) => { |
| 1749 | Ok(StorageProbeVerdict::Violation( |
| 1750 | "the store does not honor ranged reads, so celld cannot read stored cell data" |
| 1751 | .to_string(), |
| 1752 | )) |
| 1753 | } |
| 1754 | result => result, |
| 1755 | } |
| 1756 | } |
| 1757 | |
| 1758 | fn probe_key(kind: &str) -> String { |
| 1759 | let nanos = crate::asyncrt::wall_ms().max(0) as u128 * 1_000_000; |
| 1760 | // Unique per probe, so several nodes probing at once touch |
| 1761 | // disjoint keys and no probe reads another one's object as the |
| 1762 | // store misbehaving — a collision surfaces as a false `Violation`, |
| 1763 | // which stops a node. The random half carries that alone, because |
| 1764 | // a container fleet shares pid 1 and a clock before the epoch |
| 1765 | // leaves `nanos` at zero. |
| 1766 | format!( |
| 1767 | "probe/{kind}-{nanos}-{}-{:016x}", |
| 1768 | crate::asyncrt::process_tag(), |
| 1769 | rand::RngCore::next_u64(&mut crate::asyncrt::rng("cas_probe")) |
| 1770 | ) |
| 1771 | } |
| 1772 | |
| 1773 | /// [`Self::probe_cas_steps`] collapsed to one answer, where any wrong |
| 1774 | /// answer fails the check. |
| 1775 | pub async fn probe_cas(&self) -> anyhow::Result<()> { |
| 1776 | match self.probe_cas_steps().await? { |
| 1777 | StorageProbeVerdict::Conformant => Ok(()), |
| 1778 | StorageProbeVerdict::Violation(reason) => Err(anyhow!(reason)), |
| 1779 | } |
| 1780 | } |
| 1781 | |
| 1782 | /// The four steps, against one key. Steps 2 and 4 must be rejected; |
| 1783 | /// a store that applies either one cannot fence. |
| 1784 | async fn cas_contract(&self, key: &str) -> anyhow::Result<StorageProbeVerdict> { |
| 1785 | let precondition = self.backend.precondition(); |
| 1786 | let ambiguous = || { |
| 1787 | format!( |
| 1788 | "the store answered a conditional write with an error where celld requires a \ |
| 1789 | clean rejection, so celld cannot tell a lost race from a failed write and \ |
| 1790 | reconciles forever; the store must answer {precondition} with a rejection" |
| 1791 | ) |
| 1792 | }; |
| 1793 | |
| 1794 | // 1. A create on an absent key applies, and answers the token that |
| 1795 | // steps 3 and 4 need. |
| 1796 | let Some(token) = self |
| 1797 | .put_cas(key, b"probe-create".to_vec(), None) |
| 1798 | .await |
| 1799 | .context("the conditional-write probe could not create its object")? |
| 1800 | else { |
| 1801 | return Ok(StorageProbeVerdict::Violation( |
| 1802 | "the store rejected a conditional create of an object that does not exist" |
| 1803 | .to_string(), |
| 1804 | )); |
| 1805 | }; |
| 1806 | |
| 1807 | // 2. A create over the object step 1 wrote must be rejected. |
| 1808 | if self |
| 1809 | .put_cas(key, b"probe-recreate".to_vec(), None) |
| 1810 | .await |
| 1811 | .with_context(ambiguous)? |
| 1812 | .is_some() |
| 1813 | { |
| 1814 | return Ok(StorageProbeVerdict::Violation(format!( |
| 1815 | "the store overwrote an object although the write was conditional on that object \ |
| 1816 | being absent; the store accepts {precondition} and does not enforce it, so two \ |
| 1817 | nodes can own one cell" |
| 1818 | ))); |
| 1819 | } |
| 1820 | |
| 1821 | // 3. An update that carries the current token applies, and that |
| 1822 | // retires the token step 4 reuses. |
| 1823 | if self |
| 1824 | .put_cas(key, b"probe-update".to_vec(), Some(&token)) |
| 1825 | .await |
| 1826 | .context("the conditional-write probe could not update its object")? |
| 1827 | .is_none() |
| 1828 | { |
| 1829 | return Ok(StorageProbeVerdict::Violation( |
| 1830 | "the store rejected a conditional update that carried the current token" |
| 1831 | .to_string(), |
| 1832 | )); |
| 1833 | } |
| 1834 | |
| 1835 | // 4. The token is stale now, so the update must be rejected. This |
| 1836 | // step is the fencing contract itself. |
| 1837 | if self |
| 1838 | .put_cas(key, b"probe-stale".to_vec(), Some(&token)) |
| 1839 | .await |
| 1840 | .with_context(ambiguous)? |
| 1841 | .is_some() |
| 1842 | { |
| 1843 | return Ok(StorageProbeVerdict::Violation(format!( |
| 1844 | "the store applied a conditional write that carried a stale token; the store \ |
| 1845 | accepts {precondition} and does not enforce it, so two nodes can own one cell" |
| 1846 | ))); |
| 1847 | } |
| 1848 | |
| 1849 | Ok(StorageProbeVerdict::Conformant) |
| 1850 | } |
| 1851 | |
| 1852 | async fn probe_range_steps(&self) -> anyhow::Result<StorageProbeVerdict> { |
| 1853 | let key = Self::probe_key("range"); |
| 1854 | let verdict = self.range_contract(&key).await; |
| 1855 | if let Err(error) = self.delete(&key).await { |
| 1856 | tracing::warn!(%error, "the ranged-read probe could not delete its object"); |
| 1857 | } |
| 1858 | verdict |
| 1859 | } |
| 1860 | |
| 1861 | async fn range_contract(&self, key: &str) -> anyhow::Result<StorageProbeVerdict> { |
| 1862 | const BODY: &[u8] = b"celld-range-probe"; |
| 1863 | const START: u64 = 6; |
| 1864 | const END: u64 = 11; |
| 1865 | let requested = START..END; |
| 1866 | |
| 1867 | self.put(key, BODY.to_vec()) |
| 1868 | .await |
| 1869 | .context("the ranged-read probe could not create its object")?; |
| 1870 | let scoped = self.key(key); |
| 1871 | let result = self |
| 1872 | .store |
| 1873 | .get_opts( |
| 1874 | &Path::from(scoped.as_str()), |
| 1875 | GetOptions { |
| 1876 | range: Some(GetRange::Bounded(requested.clone())), |
| 1877 | ..GetOptions::default() |
| 1878 | }, |
| 1879 | ) |
| 1880 | .await |
| 1881 | .with_context(|| { |
| 1882 | format!( |
| 1883 | "the ranged-read probe could not read {}://{}/{scoped}", |
| 1884 | self.scheme(), |
| 1885 | self.name |
| 1886 | ) |
| 1887 | })?; |
| 1888 | let served = result.range.clone(); |
| 1889 | let bytes = result |
| 1890 | .bytes() |
| 1891 | .await |
| 1892 | .context("the ranged-read probe could not read its response body")?; |
| 1893 | if served != requested || bytes.as_ref() != &BODY[START as usize..END as usize] { |
| 1894 | return Ok(StorageProbeVerdict::Violation( |
| 1895 | "the store does not honor ranged reads because it returned a different range or different bytes" |
| 1896 | .to_string(), |
| 1897 | )); |
| 1898 | } |
| 1899 | Ok(StorageProbeVerdict::Conformant) |
| 1900 | } |
| 1901 | } |
| 1902 | |
| 1903 | /// What one storage-contract check found. |
| 1904 | pub(crate) enum StorageProbeVerdict { |
| 1905 | /// The store returned every result that this check requires. |
| 1906 | Conformant, |
| 1907 | /// The store answered wrongly, and the string says how. This never |
| 1908 | /// clears on a retry, so a caller can act on it. |
| 1909 | Violation(String), |
| 1910 | } |
| 1911 | |
| 1912 | /// Whether an operation failed because the store clearly does not implement |
| 1913 | /// it. The public object-store errors preserve that result structurally, but |
| 1914 | /// its HTTP adapters keep a 405 or 501 status only in a private source error. |
| 1915 | fn is_unsupported_operation(error: &anyhow::Error) -> bool { |
| 1916 | error.chain().any(|cause| { |
| 1917 | if matches!( |
| 1918 | cause.downcast_ref::<Error>(), |
| 1919 | Some(Error::NotSupported { .. } | Error::NotImplemented) |
| 1920 | ) { |
| 1921 | return true; |
| 1922 | } |
| 1923 | let text = cause.to_string(); |
| 1924 | text.contains("status 405") |
| 1925 | || text.contains("status 501") |
| 1926 | || text.contains("405 Method Not Allowed") |
| 1927 | || text.contains("501 Not Implemented") |
| 1928 | }) |
| 1929 | } |
| 1930 | |
| 1931 | /// Whether the object-store client rejected a successful HTTP response because |
| 1932 | /// it did not describe the requested byte range. The locked object-store |
| 1933 | /// library keeps these parser types private, so their messages are the only |
| 1934 | /// available boundary. A dependency update must verify these messages. |
| 1935 | fn is_invalid_range_response(error: &anyhow::Error) -> bool { |
| 1936 | error.chain().any(|cause| { |
| 1937 | let text = cause.to_string(); |
| 1938 | text == "Received non-partial response when range requested" |
| 1939 | || text == "Content-Range header not present in partial response" |
| 1940 | || text.starts_with("Failed to parse value for CONTENT_RANGE header:") |
| 1941 | || text == "Content-Range header contained non UTF-8 characters" |
| 1942 | || (text.starts_with("Requested ") && text.contains(", got ")) |
| 1943 | }) |
| 1944 | } |
| 1945 | |
| 1946 | /// The replica-lane store for a `gs://` fleet bucket: its own transport |
| 1947 | /// and connection pool, authenticated like [`Bucket::open`]'s gs:// path |
| 1948 | /// (OAuth via Application Default Credentials or the `GOOGLE_*` env), |
| 1949 | /// with the same bounded retry policy the S3 replica lane uses. Replica |
| 1950 | /// writes are plain puts, so retries stay on. |
| 1951 | #[doc(hidden)] |
| 1952 | pub fn gcs_replica_store(bucket: &str) -> anyhow::Result<Arc<dyn ObjectStore>> { |
| 1953 | gcs_replica_store_with_builder(GoogleCloudStorageBuilder::from_env(), bucket) |
| 1954 | } |
| 1955 | |
| 1956 | /// The body of [`gcs_replica_store`], taking the base builder for the same |
| 1957 | /// reason [`Bucket::open_with_sources`] does. |
| 1958 | #[doc(hidden)] |
| 1959 | pub fn gcs_replica_store_with_builder( |
| 1960 | builder: GoogleCloudStorageBuilder, |
| 1961 | bucket: &str, |
| 1962 | ) -> anyhow::Result<Arc<dyn ObjectStore>> { |
| 1963 | Ok(Arc::new( |
| 1964 | builder |
| 1965 | .with_bucket_name(bucket) |
| 1966 | .with_retry(celld_ltx::client::object_store::replica_retry_config()) |
| 1967 | .build() |
| 1968 | .context("build gcs replica store")?, |
| 1969 | )) |
| 1970 | } |
| 1971 | |
| 1972 | /// The replica-lane store for an `az://` fleet bucket: its own transport |
| 1973 | /// and connection pool, authenticated like [`Bucket::open`]'s az:// path, |
| 1974 | /// with the same bounded retry policy the S3 replica lane uses. Replica |
| 1975 | /// writes are plain puts, so retries stay on. |
| 1976 | #[doc(hidden)] |
| 1977 | pub fn azure_replica_store(container: &str) -> anyhow::Result<Arc<dyn ObjectStore>> { |
| 1978 | azure_replica_store_with_env(&AzureEnv::from_process(), container) |
| 1979 | } |
| 1980 | |
| 1981 | /// The body of [`azure_replica_store`], taking the environment for the |
| 1982 | /// same reason [`Bucket::open_with_sources`] does. |
| 1983 | #[doc(hidden)] |
| 1984 | pub fn azure_replica_store_with_env( |
| 1985 | env: &AzureEnv, |
| 1986 | container: &str, |
| 1987 | ) -> anyhow::Result<Arc<dyn ObjectStore>> { |
| 1988 | Ok(Arc::new( |
| 1989 | azure_builder_for(env, container)? |
| 1990 | .with_retry(celld_ltx::client::object_store::replica_retry_config()) |
| 1991 | .build() |
| 1992 | .context("build azure replica store")?, |
| 1993 | )) |
| 1994 | } |
| 1995 | |
| 1996 | /// The `AZURE_*` variables an `az://` bucket can inspect. celld captures |
| 1997 | /// them instead of letting `MicrosoftAzureBuilder::from_env` read the |
| 1998 | /// process environment, because the fleet client must decide which |
| 1999 | /// recognized settings it honors, and a caller can supply an explicit set. |
| 2000 | /// Names that `AzureConfigKey` does not parse are inert |
| 2001 | /// and stay ignored, as they are in `from_env`. |
| 2002 | #[derive(Clone, Default)] |
| 2003 | #[doc(hidden)] |
| 2004 | pub struct AzureEnv { |
| 2005 | variables: Vec<(String, String)>, |
| 2006 | } |
| 2007 | |
| 2008 | impl AzureEnv { |
| 2009 | /// Every `AZURE_*` variable in the process environment. |
| 2010 | fn from_process() -> AzureEnv { |
| 2011 | AzureEnv::from_pairs(std::env::vars().filter(|(name, _)| name.starts_with("AZURE_"))) |
| 2012 | } |
| 2013 | |
| 2014 | #[doc(hidden)] |
| 2015 | pub fn from_pairs<K, V>(pairs: impl IntoIterator<Item = (K, V)>) -> AzureEnv |
| 2016 | where |
| 2017 | K: Into<String>, |
| 2018 | V: Into<String>, |
| 2019 | { |
| 2020 | AzureEnv { |
| 2021 | variables: pairs |
| 2022 | .into_iter() |
| 2023 | .map(|(name, value)| (name.into(), value.into())) |
| 2024 | .filter(|(_, value)| !value.is_empty()) |
| 2025 | .collect(), |
| 2026 | } |
| 2027 | } |
| 2028 | } |
| 2029 | |
| 2030 | /// The cloud configuration [`Bucket::open`] derives from the process |
| 2031 | /// environment: the GCS builder, and the `AZURE_*` variables. Bundled so |
| 2032 | /// the seam that makes construction environment-independent stays one |
| 2033 | /// parameter as backends are added. |
| 2034 | #[doc(hidden)] |
| 2035 | pub struct CloudSources { |
| 2036 | pub gcs: GoogleCloudStorageBuilder, |
| 2037 | pub azure: AzureEnv, |
| 2038 | } |
| 2039 | |
| 2040 | impl CloudSources { |
| 2041 | fn from_process() -> CloudSources { |
| 2042 | CloudSources { |
| 2043 | gcs: GoogleCloudStorageBuilder::from_env(), |
| 2044 | azure: AzureEnv::from_process(), |
| 2045 | } |
| 2046 | } |
| 2047 | } |
| 2048 | |
| 2049 | /// Is this a setting an `az://` bucket accepts? celld supports three |
| 2050 | /// credential families — a storage account key, a managed identity, and |
| 2051 | /// a workload identity — on the public Azure cloud, and no other |
| 2052 | /// recognized Azure setting. |
| 2053 | /// |
| 2054 | /// This is an allowlist, and the wildcard arm is the point of it. |
| 2055 | /// `AzureConfigKey` is `#[non_exhaustive]`, so a key that a later |
| 2056 | /// `object_store` adds falls to `false` and refuses, instead of reaching |
| 2057 | /// the client unexamined. A denylist gave the opposite default and let |
| 2058 | /// three settings through: `AZURE_USE_FABRIC_ENDPOINT` retargets the |
| 2059 | /// client at OneLake, the four `AZURE_FABRIC_*` variables form a fourth |
| 2060 | /// credential that wins ahead of the account key, and |
| 2061 | /// `AZURE_SKIP_SIGNATURE` makes every request anonymous. |
| 2062 | fn accepts_azure_config_key(key: &AzureConfigKey) -> bool { |
| 2063 | matches!( |
| 2064 | key, |
| 2065 | // The account, and the account-key credential. |
| 2066 | AzureConfigKey::AccountName |
| 2067 | | AzureConfigKey::AccessKey |
| 2068 | // A managed identity: the defaults reach IMDS, and any one |
| 2069 | // of these three selects a user-assigned identity. |
| 2070 | | AzureConfigKey::ClientId |
| 2071 | | AzureConfigKey::ObjectId |
| 2072 | | AzureConfigKey::MsiResourceId |
| 2073 | // A workload identity, with ClientId above. |
| 2074 | | AzureConfigKey::AuthorityId |
| 2075 | | AzureConfigKey::AuthorityHost |
| 2076 | | AzureConfigKey::FederatedTokenFile |
| 2077 | // Azurite, handled separately below. |
| 2078 | | AzureConfigKey::UseEmulator |
| 2079 | ) |
| 2080 | } |
| 2081 | |
| 2082 | /// Build the Azure client configuration for `container` from the accepted |
| 2083 | /// part of `env`, and refuse every other recognized Azure setting. |
| 2084 | /// |
| 2085 | /// `object_store`'s builder accepts every source the Azure chain offers. |
| 2086 | /// celld accepts three, which mirrors the deliberate narrowness of the S3 |
| 2087 | /// path, where celld reads the `AWS_*` environment but no `~/.aws` |
| 2088 | /// profile and no SSO login. Both the fleet client and the replica store |
| 2089 | /// come through here, so they cannot narrow differently. |
| 2090 | /// |
| 2091 | /// A refused variable fails at startup with a message that names it. A |
| 2092 | /// silently ignored credential surfaces much later as a permission |
| 2093 | /// error, and it points at the container instead of the configuration. |
| 2094 | fn azure_builder_for(env: &AzureEnv, container: &str) -> anyhow::Result<MicrosoftAzureBuilder> { |
| 2095 | let mut parsed: Vec<(AzureConfigKey, &str, &str)> = Vec::new(); |
| 2096 | let mut seen: Vec<(AzureConfigKey, &str)> = Vec::new(); |
| 2097 | for (name, value) in &env.variables { |
| 2098 | // `from_env` parses each AZURE_* name into a config key and drops |
| 2099 | // the ones that do not parse, so a name this parse rejects is a |
| 2100 | // name object_store would have ignored anyway. |
| 2101 | let Ok(key) = name.to_ascii_lowercase().parse::<AzureConfigKey>() else { |
| 2102 | continue; |
| 2103 | }; |
| 2104 | if !accepts_azure_config_key(&key) { |
| 2105 | anyhow::bail!( |
| 2106 | "an az:// bucket does not accept {name}; celld authenticates with an Azure \ |
| 2107 | storage account key, a managed identity, or a workload identity on the \ |
| 2108 | public Azure cloud, and it refuses every other Azure setting" |
| 2109 | ); |
| 2110 | } |
| 2111 | let value = if key == AzureConfigKey::AuthorityHost { |
| 2112 | let public = authority_hosts::AZURE_PUBLIC_CLOUD; |
| 2113 | if value != public && value != &format!("{public}/") { |
| 2114 | anyhow::bail!( |
| 2115 | "an az:// bucket accepts {name} only for the public Azure authority \ |
| 2116 | {public}; sovereign and custom authority hosts are not supported" |
| 2117 | ); |
| 2118 | } |
| 2119 | // The webhook value has a trailing slash, but object_store |
| 2120 | // inserts its own separator. Pass one canonical spelling. |
| 2121 | public |
| 2122 | } else { |
| 2123 | value.as_str() |
| 2124 | }; |
| 2125 | if let Some((_, first)) = seen.iter().find(|(candidate, _)| *candidate == key) { |
| 2126 | anyhow::bail!( |
| 2127 | "an az:// bucket does not accept both {first} and {name}; they are aliases for \ |
| 2128 | the same Azure setting" |
| 2129 | ); |
| 2130 | } |
| 2131 | seen.push((key, name)); |
| 2132 | parsed.push((key, name.as_str(), value)); |
| 2133 | } |
| 2134 | |
| 2135 | let has = |wanted| seen.iter().any(|(key, _)| *key == wanted); |
| 2136 | let account_key = has(AzureConfigKey::AccessKey); |
| 2137 | let client_id = has(AzureConfigKey::ClientId); |
| 2138 | let workload_specific = has(AzureConfigKey::AuthorityId) |
| 2139 | || has(AzureConfigKey::AuthorityHost) |
| 2140 | || has(AzureConfigKey::FederatedTokenFile); |
| 2141 | let managed_specific = has(AzureConfigKey::ObjectId) || has(AzureConfigKey::MsiResourceId); |
| 2142 | let managed_selectors: Vec<&str> = seen |
| 2143 | .iter() |
| 2144 | .filter(|(key, _)| { |
| 2145 | matches!( |
| 2146 | key, |
| 2147 | AzureConfigKey::ClientId | AzureConfigKey::ObjectId | AzureConfigKey::MsiResourceId |
| 2148 | ) |
| 2149 | }) |
| 2150 | .map(|(_, name)| *name) |
| 2151 | .collect(); |
| 2152 | |
| 2153 | if (account_key && (client_id || workload_specific || managed_specific)) |
| 2154 | || (workload_specific && managed_specific) |
| 2155 | { |
| 2156 | anyhow::bail!( |
| 2157 | "an az:// bucket does not accept mixed Azure credential families; select exactly \ |
| 2158 | one storage account key, workload identity, or managed identity" |
| 2159 | ); |
| 2160 | } |
| 2161 | // Two selectors inside the managed-identity family are not an alias |
| 2162 | // pair, so the duplicate check above does not see them. object_store |
| 2163 | // resolves them by precedence instead — client_id, then object_id, |
| 2164 | // then msi_res_id (`azure/credential.rs`) — so the node authenticates |
| 2165 | // as an identity the operator did not choose, and the mistake |
| 2166 | // surfaces as a permission error against the container. That is the |
| 2167 | // late, misdirected failure this whole seam exists to prevent. |
| 2168 | if !workload_specific && managed_selectors.len() > 1 { |
| 2169 | anyhow::bail!( |
| 2170 | "an az:// bucket accepts one managed-identity selector, but {} name different \ |
| 2171 | identities; set exactly one of AZURE_CLIENT_ID, AZURE_OBJECT_ID, or \ |
| 2172 | AZURE_MSI_RESOURCE_ID", |
| 2173 | managed_selectors.join(" and ") |
| 2174 | ); |
| 2175 | } |
| 2176 | if workload_specific |
| 2177 | && !(client_id |
| 2178 | && has(AzureConfigKey::AuthorityId) |
| 2179 | && has(AzureConfigKey::FederatedTokenFile)) |
| 2180 | { |
| 2181 | anyhow::bail!( |
| 2182 | "an Azure workload identity requires AZURE_CLIENT_ID, AZURE_TENANT_ID, and \ |
| 2183 | AZURE_FEDERATED_TOKEN_FILE" |
| 2184 | ); |
| 2185 | } |
| 2186 | |
| 2187 | let mut builder = MicrosoftAzureBuilder::new(); |
| 2188 | let mut account = false; |
| 2189 | let mut emulator = None; |
| 2190 | for (key, name, value) in parsed { |
| 2191 | match key { |
| 2192 | // Never handed on as a string. object_store would parse it |
| 2193 | // itself, and its parse accepts y/n as well as true/false, so |
| 2194 | // a second parse here could disagree with it — and a |
| 2195 | // disagreement over this key means celld validates a |
| 2196 | // production configuration while the client talks to a local |
| 2197 | // Azurite. Two such nodes each own every cell. The name |
| 2198 | // travels with the value so the refusal below names what the |
| 2199 | // operator set. Today one AZURE_ spelling parses to this key, |
| 2200 | // so the two can not differ; carrying the name keeps that |
| 2201 | // true if object_store adds an alias. |
| 2202 | AzureConfigKey::UseEmulator => emulator = Some((name, value)), |
| 2203 | AzureConfigKey::AccountName => { |
| 2204 | account = true; |
| 2205 | builder = builder.with_config(key, value); |
| 2206 | } |
| 2207 | _ => builder = builder.with_config(key, value), |
| 2208 | } |
| 2209 | } |
| 2210 | // Azurite is the one endpoint override celld allows, and it arrives |
| 2211 | // as a parsed bool, so object_store re-parses nothing. Its |
| 2212 | // conditional-write behavior is not qualified for a production fleet. |
| 2213 | if let Some((name, value)) = emulator { |
| 2214 | let on = match value.to_ascii_lowercase().as_str() { |
| 2215 | "true" | "1" => true, |
| 2216 | "false" | "0" => false, |
| 2217 | other => anyhow::bail!("{name} accepts true or false, not {other:?}"), |
| 2218 | }; |
| 2219 | builder = builder.with_use_emulator(on); |
| 2220 | if on { |
| 2221 | return Ok(builder.with_container_name(container)); |
| 2222 | } |
| 2223 | } |
| 2224 | if !account { |
| 2225 | anyhow::bail!( |
| 2226 | "an az:// bucket names a container, so the storage account must come from \ |
| 2227 | AZURE_STORAGE_ACCOUNT_NAME" |
| 2228 | ); |
| 2229 | } |
| 2230 | Ok(builder.with_container_name(container)) |
| 2231 | } |
| 2232 | |
| 2233 | /// Was this a 401/403 — the credential itself rejected? Used by the managed |
| 2234 | /// path to report a revoked credential rather than a flaky bucket. |
| 2235 | pub fn is_unauthorized(error: &anyhow::Error) -> bool { |
| 2236 | error.chain().any(|cause| { |
| 2237 | if matches!( |
| 2238 | cause.downcast_ref::<Error>(), |
| 2239 | Some(Error::PermissionDenied { .. } | Error::Unauthenticated { .. }) |
| 2240 | ) { |
| 2241 | return true; |
| 2242 | } |
| 2243 | // The S3 list path wraps its private retry error as Generic, so the |
| 2244 | // status survives only in Display. object_store 0.11 used `status |
| 2245 | // 403`, and 0.12 uses the canonical HTTP phrase below. A revoked |
| 2246 | // managed credential must keep the same operator-visible state. |
| 2247 | let text = cause.to_string(); |
| 2248 | text.contains("status 403") |
| 2249 | || text.contains("status 401") |
| 2250 | || text.contains("status code: 403 Forbidden") |
| 2251 | || text.contains("status code: 401 Unauthorized") |
| 2252 | }) |
| 2253 | } |
| 2254 | |
| 2255 | /// homeflare: `put_large` and `get_large` against a real S3 endpoint. Run |
| 2256 | /// with `CELLD_TEST_S3_ENDPOINT` set (e.g. moto_server) and `--ignored`. |
| 2257 | #[cfg(test)] |
| 2258 | mod large_object_tests { |
| 2259 | use super::*; |
| 2260 | |
| 2261 | #[tokio::test] |
| 2262 | #[ignore] |
| 2263 | #[allow(clippy::disallowed_methods)] |
| 2264 | async fn large_object_round_trip() { |
| 2265 | let endpoint = std::env::var("CELLD_TEST_S3_ENDPOINT").expect("CELLD_TEST_S3_ENDPOINT"); |
| 2266 | let bucket = Bucket::open( |
| 2267 | "s3://celld-large/fleet", |
| 2268 | Some(&endpoint), |
| 2269 | "us-east-1", |
| 2270 | Some(StaticCredentials { |
| 2271 | access_key_id: "test".into(), |
| 2272 | secret_access_key: "test".into(), |
| 2273 | session_token: None, |
| 2274 | }), |
| 2275 | None, |
| 2276 | ) |
| 2277 | .unwrap(); |
| 2278 | // Two and a half parts, with bytes that differ by position. |
| 2279 | let size = LARGE_PART * 2 + LARGE_PART / 2; |
| 2280 | let body: Vec<u8> = (0..size).map(|i| (i % 251) as u8).collect(); |
| 2281 | let written = bucket |
| 2282 | .put_large("deploy/images/x.tar", std::io::Cursor::new(body.clone())) |
| 2283 | .await |
| 2284 | .unwrap(); |
| 2285 | assert_eq!(written, size as u64); |
| 2286 | let (stored, _) = bucket.head("deploy/images/x.tar").await.unwrap().unwrap(); |
| 2287 | assert_eq!(stored, size as u64); |
| 2288 | |
| 2289 | let temp = tempfile::NamedTempFile::new().unwrap(); |
| 2290 | let mut file = tokio::fs::File::from_std(temp.reopen().unwrap()); |
| 2291 | let read = bucket |
| 2292 | .get_large("deploy/images/x.tar", &mut file) |
| 2293 | .await |
| 2294 | .unwrap(); |
| 2295 | assert_eq!(read, Some(size as u64)); |
| 2296 | drop(file); |
| 2297 | assert!( |
| 2298 | std::fs::read(temp.path()).unwrap() == body, |
| 2299 | "downloaded bytes differ" |
| 2300 | ); |
| 2301 | assert_eq!( |
| 2302 | bucket |
| 2303 | .get_large( |
| 2304 | "deploy/images/none.tar", |
| 2305 | &mut tokio::fs::File::from_std(temp.reopen().unwrap()) |
| 2306 | ) |
| 2307 | .await |
| 2308 | .unwrap(), |
| 2309 | None |
| 2310 | ); |
| 2311 | |
| 2312 | // A reader that fails partway leaves nothing behind. |
| 2313 | struct Failing(usize); |
| 2314 | impl tokio::io::AsyncRead for Failing { |
| 2315 | fn poll_read( |
| 2316 | mut self: std::pin::Pin<&mut Self>, |
| 2317 | _: &mut std::task::Context<'_>, |
| 2318 | buf: &mut tokio::io::ReadBuf<'_>, |
| 2319 | ) -> std::task::Poll<std::io::Result<()>> { |
| 2320 | if self.0 == 0 { |
| 2321 | return std::task::Poll::Ready(Err(std::io::Error::other("save failed"))); |
| 2322 | } |
| 2323 | let n = self.0.min(buf.remaining()).min(1 << 20); |
| 2324 | buf.put_slice(&vec![7u8; n]); |
| 2325 | self.0 -= n; |
| 2326 | std::task::Poll::Ready(Ok(())) |
| 2327 | } |
| 2328 | } |
| 2329 | assert!(bucket |
| 2330 | .put_large("deploy/images/bad.tar", Failing(LARGE_PART + 5)) |
| 2331 | .await |
| 2332 | .is_err()); |
| 2333 | assert!(bucket |
| 2334 | .head("deploy/images/bad.tar") |
| 2335 | .await |
| 2336 | .unwrap() |
| 2337 | .is_none()); |
| 2338 | } |
| 2339 | } |