| 1 | //! client::object_store — S3/R2/MinIO `ReplicaClient` via the `object_store` crate. |
| 2 | //! |
| 3 | //! Ported (behavior only) from [email protected] `s3/replica_client.go`. We do |
| 4 | //! **not** use the Go AWS SDK; instead the five `ReplicaClient` operations are |
| 5 | //! mapped onto `object_store::ObjectStore` (the `s3` cargo feature wires the |
| 6 | //! `object_store::aws::AmazonS3Builder` backend). The behavioral invariants from |
| 7 | //! the upstream conformance suite are kept: |
| 8 | //! |
| 9 | //! * key/path scheme `{path}/{level:04x}/{min}-{max}.ltx` |
| 10 | //! (s3/replica_client.go:629, 677, 1040-1042); |
| 11 | //! * the 5 MiB single-PUT vs multipart threshold |
| 12 | //! (s3/replica_client.go:99 + the Go uploader default); |
| 13 | //! * list + seek-skip on `min_txid < seek`, ascending TXID order |
| 14 | //! (s3/replica_client.go:1530-1533); |
| 15 | //! * `NoSuchKey` → `os.ErrNotExist` error mapping |
| 16 | //! (s3/replica_client.go:647-649, 1662-1668); |
| 17 | //! * batch DELETE up to 1000 keys per call with per-key error surfacing |
| 18 | //! (s3/replica_client.go:1028-1101). |
| 19 | //! |
| 20 | //! The provider-defaults table (`ParseHost`, path-style flags, endpoint env |
| 21 | //! var) is a faithful port of `NewReplicaClientFromURL` |
| 22 | //! (s3/replica_client.go:133-314) so a `s3://…` URL configures the same way. |
| 23 | //! |
| 24 | //! This whole module is gated behind `#[cfg(feature = "s3")]` because it needs |
| 25 | //! `object_store`'s AWS backend. |
| 26 | |
| 27 | #![cfg(feature = "s3")] |
| 28 | |
| 29 | use std::sync::Arc; |
| 30 | |
| 31 | use chrono::{DateTime, SecondsFormat}; |
| 32 | use futures_util::stream::{StreamExt, TryStreamExt}; |
| 33 | use object_store::aws::{AmazonS3Builder, AmazonS3ConfigKey}; |
| 34 | use object_store::path::Path as ObjPath; |
| 35 | use object_store::{ |
| 36 | Attribute, AttributeValue, Attributes, ClientOptions, ObjectStore, PutMultipartOptions, |
| 37 | PutOptions, PutPayload, RetryConfig, |
| 38 | }; |
| 39 | |
| 40 | use crate::error::{Error, Result}; |
| 41 | use crate::ltx::{self, FileInfo}; |
| 42 | use crate::replica_url::{ |
| 43 | self, bool_query_value, ensure_endpoint_scheme, region_from_s3_arn, ParsedReplicaUrl, |
| 44 | }; |
| 45 | use crate::TXID; |
| 46 | |
| 47 | use super::ReplicaClient; |
| 48 | |
| 49 | /// The standard Litestream S3 metadata key for an LTX header timestamp. |
| 50 | const METADATA_KEY_TIMESTAMP: &str = "litestream-timestamp"; |
| 51 | |
| 52 | /// The retry policy every replica store uses. |
| 53 | /// |
| 54 | /// object_store defaults to 10 retries under a 180-second ceiling. That suits |
| 55 | /// a client whose caller has nowhere else to go. A replica store always has |
| 56 | /// somewhere else to go: a failed segment read is retried by the restore that |
| 57 | /// asked for it, and a failed upload is retried by the next replication turn, |
| 58 | /// so a long ladder inside one request buys nothing and delays the answer. |
| 59 | /// |
| 60 | /// The ceiling matters most on a request a person is waiting for. A read-only |
| 61 | /// cell inspection reaches this store, and a definite failure under the |
| 62 | /// default policy takes seconds of pure backoff before the caller learns |
| 63 | /// anything. Three attempts still absorb an ordinary transient error. |
| 64 | pub fn replica_retry_config() -> RetryConfig { |
| 65 | RetryConfig { |
| 66 | max_retries: 3, |
| 67 | retry_timeout: std::time::Duration::from_secs(30), |
| 68 | ..RetryConfig::default() |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | /// The same key with an underscore, for Azure Blob Storage. An Azure blob |
| 73 | /// metadata name must be a C# identifier, so it cannot hold a hyphen, and |
| 74 | /// the standard key is refused there. |
| 75 | const METADATA_KEY_TIMESTAMP_UNDERSCORE: &str = "litestream_timestamp"; |
| 76 | |
| 77 | /// Which object-metadata name carries the LTX header timestamp. |
| 78 | /// |
| 79 | /// The name is per backend, not per deployment: Azure Blob Storage |
| 80 | /// refuses a hyphen in a metadata name, and every other supported store |
| 81 | /// accepts the standard Litestream key. The value and its format do not |
| 82 | /// change. |
| 83 | /// |
| 84 | /// The key exists for external Litestream tooling, which reads |
| 85 | /// `litestream-timestamp` to do a timestamp restore without downloading |
| 86 | /// every candidate file. A renamed key therefore ends that interop on |
| 87 | /// Azure. celld itself never reads the key back. |
| 88 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 89 | pub enum TimestampMetadataKey { |
| 90 | /// `litestream-timestamp`, the standard Litestream key. |
| 91 | #[default] |
| 92 | Litestream, |
| 93 | /// `litestream_timestamp`, for a store that refuses a hyphen. |
| 94 | Underscore, |
| 95 | } |
| 96 | |
| 97 | impl TimestampMetadataKey { |
| 98 | /// The metadata name this variant writes. |
| 99 | pub fn as_str(self) -> &'static str { |
| 100 | match self { |
| 101 | Self::Litestream => METADATA_KEY_TIMESTAMP, |
| 102 | Self::Underscore => METADATA_KEY_TIMESTAMP_UNDERSCORE, |
| 103 | } |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | /// Max keys S3 operates on per batch DELETE. `MaxKeys` (s3/replica_client.go:56). |
| 108 | pub const MAX_KEYS: usize = 1000; |
| 109 | |
| 110 | /// Region used when none is specified. `DefaultRegion` (s3/replica_client.go:59). |
| 111 | pub const DEFAULT_REGION: &str = "us-east-1"; |
| 112 | |
| 113 | /// Multipart upload threshold: data at or above this size is uploaded with |
| 114 | /// `put_multipart`; below it, a single `put`. Matches the Go uploader's 5 MiB |
| 115 | /// `PartSize` default (s3/replica_client.go:99). |
| 116 | pub const MULTIPART_THRESHOLD: usize = 5 * 1024 * 1024; |
| 117 | |
| 118 | // ── Config ──────────────────────────────────────────────────────────────────── |
| 119 | |
| 120 | /// Configuration for the S3/R2/MinIO backend. |
| 121 | /// |
| 122 | /// Maps to the public fields of Go's `ReplicaClient` struct |
| 123 | /// (s3/replica_client.go:78-116). Zero/`None` values mean "use the backend |
| 124 | /// default". |
| 125 | #[derive(Debug, Clone, Default)] |
| 126 | pub struct ObjectStoreConfig { |
| 127 | /// Bucket name (required). |
| 128 | pub bucket: String, |
| 129 | /// Key prefix within the bucket. |
| 130 | pub path: String, |
| 131 | /// AWS region. |
| 132 | pub region: String, |
| 133 | /// Custom endpoint (MinIO, R2, …); empty = native AWS. |
| 134 | pub endpoint: String, |
| 135 | /// Static access key id; empty = ambient credential chain. |
| 136 | pub access_key_id: String, |
| 137 | /// Static secret access key; empty = ambient credential chain. |
| 138 | pub secret_access_key: String, |
| 139 | /// Session token for temporary/scoped credentials (STS, R2 API tokens); |
| 140 | /// empty = none. Required alongside temporary keys or signing fails. |
| 141 | pub session_token: String, |
| 142 | /// Force path-style addressing (required for MinIO/Backblaze/Supabase/Filebase). |
| 143 | pub force_path_style: bool, |
| 144 | /// Skip TLS verification (allows self-signed endpoints). |
| 145 | pub skip_verify: bool, |
| 146 | /// Multipart part size in bytes; 0 = default (5 MiB). |
| 147 | pub part_size: u64, |
| 148 | /// The metadata name for the LTX header timestamp. The default is the |
| 149 | /// standard Litestream key; a host that injects an Azure store must |
| 150 | /// select [`TimestampMetadataKey::Underscore`], because Azure refuses |
| 151 | /// a hyphen in a metadata name. |
| 152 | pub timestamp_metadata_key: TimestampMetadataKey, |
| 153 | } |
| 154 | |
| 155 | impl ObjectStoreConfig { |
| 156 | /// Construct from a parsed `s3://` URL, mirroring `NewReplicaClientFromURL` |
| 157 | /// (s3/replica_client.go:133-314): host → bucket/region/endpoint/path-style |
| 158 | /// (or ARN), query-param overrides (camelCase ↔ hyphenated aliases), the |
| 159 | /// `AWS_*`/`LITESTREAM_*` env credentials, the `LITESTREAM_S3_ENDPOINT` env |
| 160 | /// fallback, and the provider-specific path-style defaults for |
| 161 | /// MinIO/Backblaze/Filebase/Supabase. |
| 162 | pub fn from_url(parsed: &ParsedReplicaUrl) -> Result<Self> { |
| 163 | let host = &parsed.host; |
| 164 | let query = &parsed.query; |
| 165 | |
| 166 | // Host → bucket/region/endpoint/forcePathStyle (or ARN access point). |
| 167 | let (bucket, mut region, mut endpoint, mut force_path_style) = if host.starts_with("arn:") { |
| 168 | (host.clone(), region_from_s3_arn(host), String::new(), false) |
| 169 | } else { |
| 170 | parse_host(host) |
| 171 | }; |
| 172 | |
| 173 | let q = Some(query); |
| 174 | |
| 175 | // endpoint query param: ensure scheme, default to path-style for custom |
| 176 | // endpoints unless force-path-style is explicitly set to false. |
| 177 | let q_endpoint = query.get("endpoint"); |
| 178 | if !q_endpoint.is_empty() { |
| 179 | let (ep, _) = ensure_endpoint_scheme(q_endpoint); |
| 180 | endpoint = ep; |
| 181 | match bool_query_value(q, &["forcePathStyle", "force-path-style"]) { |
| 182 | Some(false) => {} |
| 183 | _ => force_path_style = true, |
| 184 | } |
| 185 | } |
| 186 | let q_region = query.get("region"); |
| 187 | if !q_region.is_empty() { |
| 188 | region = q_region.to_string(); |
| 189 | } |
| 190 | if let Some(v) = bool_query_value(q, &["forcePathStyle", "force-path-style"]) { |
| 191 | force_path_style = v; |
| 192 | } |
| 193 | let mut skip_verify = false; |
| 194 | if let Some(v) = bool_query_value(q, &["skipVerify", "skip-verify"]) { |
| 195 | skip_verify = v; |
| 196 | } |
| 197 | |
| 198 | let mut part_size: u64 = 0; |
| 199 | let v = query.get("partSize"); |
| 200 | let v2 = query.get("part-size"); |
| 201 | if !v.is_empty() { |
| 202 | if let Ok(n) = v.parse::<u64>() { |
| 203 | if n > 0 { |
| 204 | part_size = n; |
| 205 | } |
| 206 | } |
| 207 | } else if !v2.is_empty() { |
| 208 | if let Ok(n) = v2.parse::<u64>() { |
| 209 | if n > 0 { |
| 210 | part_size = n; |
| 211 | } |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | if bucket.is_empty() { |
| 216 | return Err(Error::Other("bucket required for s3 replica URL".into())); |
| 217 | } |
| 218 | |
| 219 | // Track whether forcePathStyle was explicitly set via query param |
| 220 | // (s3/replica_client.go:208) — this gates the env-var/provider defaults. |
| 221 | let force_path_style_set = |
| 222 | !query.get("forcePathStyle").is_empty() || !query.get("force-path-style").is_empty(); |
| 223 | |
| 224 | // Static credentials from env (AWS_* preferred, then LITESTREAM_*). |
| 225 | let mut access_key_id = String::new(); |
| 226 | let mut secret_access_key = String::new(); |
| 227 | if let Some(v) = nonempty_env("AWS_ACCESS_KEY_ID") { |
| 228 | access_key_id = v; |
| 229 | } else if let Some(v) = nonempty_env("LITESTREAM_ACCESS_KEY_ID") { |
| 230 | access_key_id = v; |
| 231 | } |
| 232 | if let Some(v) = nonempty_env("AWS_SECRET_ACCESS_KEY") { |
| 233 | secret_access_key = v; |
| 234 | } else if let Some(v) = nonempty_env("LITESTREAM_SECRET_ACCESS_KEY") { |
| 235 | secret_access_key = v; |
| 236 | } |
| 237 | let session_token = nonempty_env("AWS_SESSION_TOKEN") |
| 238 | .or_else(|| nonempty_env("LITESTREAM_SESSION_TOKEN")) |
| 239 | .unwrap_or_default(); |
| 240 | |
| 241 | // LITESTREAM_S3_ENDPOINT env fallback (only when no endpoint yet). |
| 242 | if endpoint.is_empty() { |
| 243 | if let Some(v) = nonempty_env("LITESTREAM_S3_ENDPOINT") { |
| 244 | let (ep, _) = ensure_endpoint_scheme(&v); |
| 245 | endpoint = ep; |
| 246 | if !force_path_style_set { |
| 247 | force_path_style = true; |
| 248 | } |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | // Provider detection for applying defaults. |
| 253 | let is_filebase = replica_url::is_filebase_endpoint(&endpoint); |
| 254 | let is_backblaze = replica_url::is_backblaze_endpoint(&endpoint); |
| 255 | let is_minio = replica_url::is_minio_endpoint(&endpoint); |
| 256 | let is_supabase = replica_url::is_supabase_endpoint(&endpoint); |
| 257 | if !force_path_style_set && (is_filebase || is_backblaze || is_minio || is_supabase) { |
| 258 | force_path_style = true; |
| 259 | } |
| 260 | |
| 261 | Ok(ObjectStoreConfig { |
| 262 | bucket, |
| 263 | path: parsed.path.clone(), |
| 264 | region, |
| 265 | endpoint, |
| 266 | access_key_id, |
| 267 | secret_access_key, |
| 268 | session_token, |
| 269 | force_path_style, |
| 270 | skip_verify, |
| 271 | part_size, |
| 272 | timestamp_metadata_key: TimestampMetadataKey::default(), |
| 273 | }) |
| 274 | } |
| 275 | |
| 276 | /// Build the backing `Arc<dyn ObjectStore>` for this config. Public so a host |
| 277 | /// can build one store for a bucket and share it across many |
| 278 | /// [`ObjectStoreClient::with_store`] clients that differ only by key prefix |
| 279 | /// — one connection pool for every cell on a node. |
| 280 | /// |
| 281 | /// An empty `access_key_id` and `secret_access_key` select the ambient AWS |
| 282 | /// credential chain, which reads web identity, ECS task credentials, EKS |
| 283 | /// Pod Identity, and instance metadata from the process environment. Set |
| 284 | /// both fields to keep a caller's own credentials authoritative. |
| 285 | pub fn build_store(&self) -> Result<Arc<dyn ObjectStore>> { |
| 286 | if self.bucket.is_empty() { |
| 287 | return Err(Error::Other("s3: bucket name is required".into())); |
| 288 | } |
| 289 | |
| 290 | let region = if self.region.is_empty() { |
| 291 | DEFAULT_REGION.to_string() |
| 292 | } else { |
| 293 | self.region.clone() |
| 294 | }; |
| 295 | |
| 296 | // Forward the credential inputs that object_store reads. A bare |
| 297 | // `new()` reads no environment, so it falls through to IMDS on EKS, |
| 298 | // and `from_env()` would also import endpoint and request settings |
| 299 | // that belong to this explicit ObjectStoreConfig. So the allowlist |
| 300 | // stops at the credential boundary, and the config below stays |
| 301 | // authoritative. |
| 302 | // |
| 303 | // object_store 0.12.5 takes AWS_WEB_IDENTITY_TOKEN_FILE and |
| 304 | // AWS_ROLE_ARN from the process environment rather than from these |
| 305 | // builder fields, so that pair changes nothing today. It stays because |
| 306 | // the session name and the STS endpoint beside it *are* read from the |
| 307 | // builder, and a release that moves the pair to the builder must not |
| 308 | // drop this client back to IMDS. |
| 309 | let mut builder = AmazonS3Builder::new(); |
| 310 | for (name, key) in [ |
| 311 | ( |
| 312 | "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI", |
| 313 | AmazonS3ConfigKey::ContainerCredentialsRelativeUri, |
| 314 | ), |
| 315 | ( |
| 316 | "AWS_CONTAINER_CREDENTIALS_FULL_URI", |
| 317 | AmazonS3ConfigKey::ContainerCredentialsFullUri, |
| 318 | ), |
| 319 | ( |
| 320 | "AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE", |
| 321 | AmazonS3ConfigKey::ContainerAuthorizationTokenFile, |
| 322 | ), |
| 323 | ( |
| 324 | "AWS_WEB_IDENTITY_TOKEN_FILE", |
| 325 | AmazonS3ConfigKey::WebIdentityTokenFile, |
| 326 | ), |
| 327 | ("AWS_ROLE_ARN", AmazonS3ConfigKey::RoleArn), |
| 328 | ("AWS_ROLE_SESSION_NAME", AmazonS3ConfigKey::RoleSessionName), |
| 329 | ("AWS_ENDPOINT_URL_STS", AmazonS3ConfigKey::StsEndpoint), |
| 330 | ("AWS_METADATA_ENDPOINT", AmazonS3ConfigKey::MetadataEndpoint), |
| 331 | ] { |
| 332 | if let Some(value) = nonempty_env(name) { |
| 333 | builder = builder.with_config(key, value); |
| 334 | } |
| 335 | } |
| 336 | let mut builder = builder |
| 337 | .with_bucket_name(&self.bucket) |
| 338 | .with_region(region) |
| 339 | .with_retry(replica_retry_config()) |
| 340 | // Path-style ⇔ NOT virtual-hosted-style (s3/replica_client.go:258-263). |
| 341 | .with_virtual_hosted_style_request(!self.force_path_style) |
| 342 | // object_store disables S3 conditional puts by default. Keep the |
| 343 | // established ETagMatch behavior, so a user of the returned store |
| 344 | // can send PutMode::Create or PutMode::Update. Ordinary replica |
| 345 | // PUTs remain unconditional. |
| 346 | .with_conditional_put(object_store::aws::S3ConditionalPut::ETagMatch); |
| 347 | |
| 348 | if !self.endpoint.is_empty() { |
| 349 | // A plaintext or local endpoint must allow HTTP. skip_verify applies |
| 350 | // only to TLS certificate validation. |
| 351 | let allow_http = self.endpoint.starts_with("http://") |
| 352 | || replica_url::is_local_endpoint(&self.endpoint); |
| 353 | let client_options = ClientOptions::new() |
| 354 | .with_allow_http(allow_http) |
| 355 | .with_allow_invalid_certificates(self.skip_verify); |
| 356 | builder = builder |
| 357 | .with_endpoint(&self.endpoint) |
| 358 | .with_client_options(client_options); |
| 359 | } |
| 360 | |
| 361 | if !self.access_key_id.is_empty() { |
| 362 | builder = builder.with_access_key_id(&self.access_key_id); |
| 363 | } |
| 364 | if !self.secret_access_key.is_empty() { |
| 365 | builder = builder.with_secret_access_key(&self.secret_access_key); |
| 366 | } |
| 367 | if !self.session_token.is_empty() { |
| 368 | builder = builder.with_token(&self.session_token); |
| 369 | } |
| 370 | |
| 371 | let store = builder |
| 372 | .build() |
| 373 | .map_err(|e| Error::Other(format!("s3: build store: {e}").into()))?; |
| 374 | Ok(Arc::new(store)) |
| 375 | } |
| 376 | |
| 377 | /// Effective multipart part size (`part_size`, or the 5 MiB default). |
| 378 | fn effective_part_size(&self) -> usize { |
| 379 | if self.part_size > 0 { |
| 380 | self.part_size as usize |
| 381 | } else { |
| 382 | MULTIPART_THRESHOLD |
| 383 | } |
| 384 | } |
| 385 | } |
| 386 | |
| 387 | /// Returns `Some(value)` for a non-empty env var, else `None`. Mirrors Go's |
| 388 | /// `if v := os.Getenv(k); v != ""` pattern (s3/replica_client.go:211-224). |
| 389 | fn nonempty_env(key: &str) -> Option<String> { |
| 390 | match std::env::var(key) { |
| 391 | Ok(v) if !v.is_empty() => Some(v), |
| 392 | _ => None, |
| 393 | } |
| 394 | } |
| 395 | |
| 396 | // ── ParseHost ───────────────────────────────────────────────────────────────── |
| 397 | |
| 398 | /// Parse an S3 host into `(bucket, region, endpoint, force_path_style)`. |
| 399 | /// |
| 400 | /// Direct port of `ParseHost` (s3/replica_client.go:1608-1652): MinIO-style |
| 401 | /// `bucket.host:port`, then the AWS / DigitalOcean / Backblaze / Filebase / |
| 402 | /// Scaleway provider patterns, falling back to "host *is* the bucket". |
| 403 | pub fn parse_host(host: &str) -> (String, String, String, bool) { |
| 404 | // MinIO-style hosts: `bucket.host:port` (a colon and not a ".com"). |
| 405 | if host.contains(':') && !host.contains(".com") { |
| 406 | // SplitN(host, ".", 2) |
| 407 | if let Some((bucket, rest)) = host.split_once('.') { |
| 408 | return ( |
| 409 | bucket.to_string(), |
| 410 | DEFAULT_REGION.to_string(), |
| 411 | format!("http://{rest}"), |
| 412 | true, |
| 413 | ); |
| 414 | } |
| 415 | // No bucket in host, just host:port. |
| 416 | return (String::new(), String::new(), format!("http://{host}"), true); |
| 417 | } |
| 418 | |
| 419 | // AWS S3: `^(.+)\.s3(?:\.([^.]+))?\.amazonaws\.com$` |
| 420 | if let Some((bucket, region)) = match_aws_s3(host) { |
| 421 | return (bucket, region, String::new(), false); |
| 422 | } |
| 423 | // DigitalOcean: `^(?:(.+)\.)?([^.]+)\.digitaloceanspaces.com$` |
| 424 | if let Some((bucket, region)) = match_two_label_suffix(host, ".digitaloceanspaces.com") { |
| 425 | return ( |
| 426 | bucket, |
| 427 | region.clone(), |
| 428 | format!("https://{region}.digitaloceanspaces.com"), |
| 429 | false, |
| 430 | ); |
| 431 | } |
| 432 | // Backblaze: `^(?:(.+)\.)?s3.([^.]+)\.backblazeb2.com$` |
| 433 | if let Some((bucket, region)) = match_s3_region_suffix(host, ".backblazeb2.com") { |
| 434 | return ( |
| 435 | bucket, |
| 436 | region.clone(), |
| 437 | format!("https://s3.{region}.backblazeb2.com"), |
| 438 | true, |
| 439 | ); |
| 440 | } |
| 441 | // Filebase: `^(?:(.+)\.)?s3.filebase.com$` |
| 442 | if let Some(bucket) = match_filebase(host) { |
| 443 | return (bucket, String::new(), "s3.filebase.com".to_string(), false); |
| 444 | } |
| 445 | // Scaleway: `^(?:(.+)\.)?s3.([^.]+)\.scw\.cloud$` |
| 446 | if let Some((bucket, region)) = match_s3_region_suffix(host, ".scw.cloud") { |
| 447 | return ( |
| 448 | bucket, |
| 449 | region.clone(), |
| 450 | format!("s3.{region}.scw.cloud"), |
| 451 | false, |
| 452 | ); |
| 453 | } |
| 454 | |
| 455 | // Standard S3: the host is the bucket name. |
| 456 | (host.to_string(), String::new(), String::new(), false) |
| 457 | } |
| 458 | |
| 459 | /// `^(.+)\.s3(?:\.([^.]+))?\.amazonaws\.com$` → (bucket, region). |
| 460 | fn match_aws_s3(host: &str) -> Option<(String, String)> { |
| 461 | let rest = host.strip_suffix(".amazonaws.com")?; |
| 462 | // rest = "<bucket>.s3" or "<bucket>.s3.<region>" |
| 463 | if let Some(bucket) = rest.strip_suffix(".s3") { |
| 464 | if bucket.is_empty() { |
| 465 | return None; |
| 466 | } |
| 467 | return Some((bucket.to_string(), String::new())); |
| 468 | } |
| 469 | // "<bucket>.s3.<region>": find the ".s3." separator; region is a single |
| 470 | // label ([^.]+) — i.e. the remainder after ".s3." must contain no dot. |
| 471 | let idx = rest.find(".s3.")?; |
| 472 | let bucket = &rest[..idx]; |
| 473 | let region = &rest[idx + 4..]; |
| 474 | if bucket.is_empty() || region.is_empty() || region.contains('.') { |
| 475 | return None; |
| 476 | } |
| 477 | Some((bucket.to_string(), region.to_string())) |
| 478 | } |
| 479 | |
| 480 | /// `^(?:(.+)\.)?([^.]+)\.<suffix>$` → (bucket, region). `suffix` starts with '.'. |
| 481 | fn match_two_label_suffix(host: &str, suffix: &str) -> Option<(String, String)> { |
| 482 | let rest = host.strip_suffix(suffix)?; |
| 483 | if rest.is_empty() { |
| 484 | return None; |
| 485 | } |
| 486 | // The last label before the suffix is the region; anything before it |
| 487 | // (optionally) is the bucket. |
| 488 | match rest.rfind('.') { |
| 489 | Some(i) => { |
| 490 | let bucket = &rest[..i]; |
| 491 | let region = &rest[i + 1..]; |
| 492 | if region.is_empty() { |
| 493 | return None; |
| 494 | } |
| 495 | Some((bucket.to_string(), region.to_string())) |
| 496 | } |
| 497 | None => Some((String::new(), rest.to_string())), |
| 498 | } |
| 499 | } |
| 500 | |
| 501 | /// `^(?:(.+)\.)?s3.([^.]+)\.<suffix>$` → (bucket, region). `suffix` starts with '.'. |
| 502 | fn match_s3_region_suffix(host: &str, suffix: &str) -> Option<(String, String)> { |
| 503 | let rest = host.strip_suffix(suffix)?; |
| 504 | // rest = "[bucket.]s3.<region>"; region is one label ([^.]+). |
| 505 | // Bucket-less form: rest == "s3.<region>". |
| 506 | if let Some(region) = rest.strip_prefix("s3.") { |
| 507 | if region.is_empty() || region.contains('.') { |
| 508 | return None; |
| 509 | } |
| 510 | return Some((String::new(), region.to_string())); |
| 511 | } |
| 512 | // Bucketed form: rest == "<bucket>.s3.<region>". |
| 513 | let sep = rest.find(".s3.")?; |
| 514 | let bucket = &rest[..sep]; |
| 515 | let region = &rest[sep + 4..]; |
| 516 | if bucket.is_empty() || region.is_empty() || region.contains('.') { |
| 517 | return None; |
| 518 | } |
| 519 | Some((bucket.to_string(), region.to_string())) |
| 520 | } |
| 521 | |
| 522 | /// `^(?:(.+)\.)?s3.filebase.com$` → bucket. |
| 523 | fn match_filebase(host: &str) -> Option<String> { |
| 524 | if host == "s3.filebase.com" { |
| 525 | return Some(String::new()); |
| 526 | } |
| 527 | let bucket = host.strip_suffix(".s3.filebase.com")?; |
| 528 | if bucket.is_empty() { |
| 529 | None |
| 530 | } else { |
| 531 | Some(bucket.to_string()) |
| 532 | } |
| 533 | } |
| 534 | |
| 535 | // ── Client ──────────────────────────────────────────────────────────────────── |
| 536 | |
| 537 | /// Concrete S3/R2/MinIO backend, wrapping a lazily-initialised |
| 538 | /// `Arc<dyn ObjectStore>`. The config-driven path builds an S3 store, but |
| 539 | /// [`Self::with_store`] accepts any prebuilt `ObjectStore` — the five |
| 540 | /// replica operations are provider-neutral, and a host can inject e.g. a |
| 541 | /// GCS or in-memory store. |
| 542 | /// |
| 543 | /// Mirrors Go `ReplicaClient` (s3/replica_client.go:78-116). The inner store is |
| 544 | /// created on the first call that needs it (`OnceCell`, mirroring `Init`, |
| 545 | /// s3/replica_client.go:322-477), so construction is infallible and race-free. |
| 546 | pub struct ObjectStoreClient { |
| 547 | store: tokio::sync::OnceCell<Arc<dyn ObjectStore>>, |
| 548 | config: ObjectStoreConfig, |
| 549 | } |
| 550 | |
| 551 | impl std::fmt::Debug for ObjectStoreClient { |
| 552 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 553 | f.debug_struct("ObjectStoreClient") |
| 554 | .field("config", &self.config) |
| 555 | .field("initialized", &self.store.initialized()) |
| 556 | .finish() |
| 557 | } |
| 558 | } |
| 559 | |
| 560 | impl ObjectStoreClient { |
| 561 | /// Create a client from config (no I/O; the store is built on first use). |
| 562 | pub fn new(config: ObjectStoreConfig) -> Self { |
| 563 | ObjectStoreClient { |
| 564 | store: tokio::sync::OnceCell::new(), |
| 565 | config, |
| 566 | } |
| 567 | } |
| 568 | |
| 569 | /// Create a client directly from an already-built `ObjectStore`, such as an |
| 570 | /// in-memory store or a pre-configured backend. |
| 571 | pub fn with_store(config: ObjectStoreConfig, store: Arc<dyn ObjectStore>) -> Self { |
| 572 | let cell = tokio::sync::OnceCell::new(); |
| 573 | cell.set(store).ok(); |
| 574 | ObjectStoreClient { |
| 575 | store: cell, |
| 576 | config, |
| 577 | } |
| 578 | } |
| 579 | |
| 580 | /// Get-or-build the inner store, once. |
| 581 | async fn store(&self) -> Result<&Arc<dyn ObjectStore>> { |
| 582 | self.store |
| 583 | .get_or_try_init(|| async { self.config.build_store() }) |
| 584 | .await |
| 585 | } |
| 586 | |
| 587 | /// Returns whether the replica epoch prefix contains an object. |
| 588 | /// |
| 589 | /// The caller needs only an existence proof, so it stops the recursive, |
| 590 | /// delimiter-less listing after the first object. An empty or non-empty |
| 591 | /// prefix therefore costs one list request instead of one request for each |
| 592 | /// compaction level. |
| 593 | pub async fn has_any_object(&self) -> Result<bool> { |
| 594 | let store = self.store().await?; |
| 595 | let prefix = ObjPath::from(self.root_prefix()); |
| 596 | store |
| 597 | .list(Some(&prefix)) |
| 598 | .next() |
| 599 | .await |
| 600 | .transpose() |
| 601 | .map(|object| object.is_some()) |
| 602 | .map_err(map_os_error) |
| 603 | } |
| 604 | |
| 605 | /// Build the S3 key for an LTX file: `{path}/{level:04x}/{min}-{max}.ltx`. |
| 606 | /// Ported from s3/replica_client.go:629, 677, 1040-1042. |
| 607 | fn ltx_key(&self, level: i32, min_txid: TXID, max_txid: TXID) -> String { |
| 608 | let filename = ltx::format_filename(min_txid, max_txid); |
| 609 | format!("{}/{:04x}/{}", self.config.path, level, filename) |
| 610 | } |
| 611 | |
| 612 | /// Prefix for listing a level: `{path}/{level:04x}/`. |
| 613 | /// Ported from s3/replica_client.go:1363. |
| 614 | fn level_prefix(&self, level: i32) -> String { |
| 615 | format!("{}/{:04x}/", self.config.path, level) |
| 616 | } |
| 617 | |
| 618 | /// Root prefix for delete-all: `{path}/`. (s3/replica_client.go:1114). |
| 619 | fn root_prefix(&self) -> String { |
| 620 | format!("{}/", self.config.path) |
| 621 | } |
| 622 | } |
| 623 | |
| 624 | /// Map an `object_store::Error` to `crate::Error`, preserving NotFound as |
| 625 | /// `io::ErrorKind::NotFound` so callers keep working with the std error kind. |
| 626 | /// Mirrors `isNotExists` → `os.ErrNotExist` (s3/replica_client.go:647-649, |
| 627 | /// 1662-1668). |
| 628 | fn map_os_error(e: object_store::Error) -> Error { |
| 629 | match e { |
| 630 | object_store::Error::NotFound { .. } => { |
| 631 | Error::Io(std::io::Error::new(std::io::ErrorKind::NotFound, e)) |
| 632 | } |
| 633 | other => Error::Other(Box::new(other)), |
| 634 | } |
| 635 | } |
| 636 | |
| 637 | #[async_trait::async_trait] |
| 638 | impl ReplicaClient for ObjectStoreClient { |
| 639 | async fn ltx_files(&self, level: i32, seek: TXID) -> Result<Vec<FileInfo>> { |
| 640 | self.ltx_files_bounded(level, seek, usize::MAX).await |
| 641 | } |
| 642 | |
| 643 | async fn ltx_files_bounded( |
| 644 | &self, |
| 645 | level: i32, |
| 646 | seek: TXID, |
| 647 | limit: usize, |
| 648 | ) -> Result<Vec<FileInfo>> { |
| 649 | if limit == 0 { |
| 650 | return Ok(Vec::new()); |
| 651 | } |
| 652 | let store = self.store().await?; |
| 653 | let prefix = ObjPath::from(self.level_prefix(level)); |
| 654 | // The offset ends immediately before every filename with this minimum |
| 655 | // TXID. S3 and GCS can push it into the listing request, so an additive |
| 656 | // compaction does not scan the complete retained L0 history. The |
| 657 | // supported production stores return each page in lexical order. The |
| 658 | // compactor validates continuity and fails closed for an unordered |
| 659 | // custom store. |
| 660 | let offset = ObjPath::from(format!("{}{:016x}", self.level_prefix(level), seek.0)); |
| 661 | let mut listed = store.list_with_offset(Some(&prefix), &offset); |
| 662 | let mut infos = Vec::with_capacity(limit.min(256)); |
| 663 | while let Some(meta) = listed.try_next().await.map_err(map_os_error)? { |
| 664 | let name = meta.location.filename().unwrap_or(""); |
| 665 | let (min_txid, max_txid) = match ltx::parse_filename(name) { |
| 666 | Ok(t) => t, |
| 667 | Err(_) => continue, // skip non-LTX keys |
| 668 | }; |
| 669 | if min_txid < seek { |
| 670 | continue; |
| 671 | } |
| 672 | infos.push(FileInfo { |
| 673 | level, |
| 674 | min_txid, |
| 675 | max_txid, |
| 676 | size: meta.size as i64, |
| 677 | created_at: Some(std::time::SystemTime::from(meta.last_modified)), |
| 678 | ..Default::default() |
| 679 | }); |
| 680 | if infos.len() == limit { |
| 681 | break; |
| 682 | } |
| 683 | } |
| 684 | |
| 685 | // Iterator contract: ascending by (level, min_txid, max_txid). |
| 686 | infos.sort_by(|a, b| { |
| 687 | (a.level, a.min_txid.0, a.max_txid.0).cmp(&(b.level, b.min_txid.0, b.max_txid.0)) |
| 688 | }); |
| 689 | Ok(infos) |
| 690 | } |
| 691 | |
| 692 | async fn open_ltx_file(&self, level: i32, min_txid: TXID, max_txid: TXID) -> Result<Vec<u8>> { |
| 693 | let store = self.store().await?; |
| 694 | let key = ObjPath::from(self.ltx_key(level, min_txid, max_txid)); |
| 695 | |
| 696 | let result = match store.get(&key).await { |
| 697 | Ok(r) => r, |
| 698 | Err(object_store::Error::NotFound { .. }) => { |
| 699 | return Err(Error::Io(std::io::Error::new( |
| 700 | std::io::ErrorKind::NotFound, |
| 701 | format!("replica: get object {key}: not found"), |
| 702 | ))); |
| 703 | } |
| 704 | Err(e) => return Err(map_os_error(e)), |
| 705 | }; |
| 706 | |
| 707 | let bytes = result.bytes().await.map_err(map_os_error)?; |
| 708 | Ok(bytes.to_vec()) |
| 709 | } |
| 710 | |
| 711 | async fn write_ltx_file( |
| 712 | &self, |
| 713 | level: i32, |
| 714 | min_txid: TXID, |
| 715 | max_txid: TXID, |
| 716 | data: &[u8], |
| 717 | ) -> Result<FileInfo> { |
| 718 | let store = self.store().await?; |
| 719 | |
| 720 | // Preserve the LTX header timestamp in the standard Litestream object |
| 721 | // metadata. This costs no extra request and lets Litestream perform an |
| 722 | // accurate timestamp restore without downloading every candidate file. |
| 723 | // The name is per backend, because Azure refuses a hyphen in it. |
| 724 | let header = ltx::Header::parse(data)?; |
| 725 | let created_at = std::time::UNIX_EPOCH |
| 726 | + std::time::Duration::from_millis(header.timestamp.max(0) as u64); |
| 727 | let mut attributes = Attributes::new(); |
| 728 | attributes.insert( |
| 729 | Attribute::Metadata(self.config.timestamp_metadata_key.as_str().into()), |
| 730 | AttributeValue::from(format_rfc3339_nano(header.timestamp)?), |
| 731 | ); |
| 732 | let key = ObjPath::from(self.ltx_key(level, min_txid, max_txid)); |
| 733 | |
| 734 | // Multipart threshold: < 5 MiB → single PUT; ≥ 5 MiB → multipart with |
| 735 | // fixed-size parts. Ported from the Go uploader's 5 MiB PartSize default |
| 736 | // (s3/replica_client.go:99, brief §5.1). |
| 737 | let part_size = self.config.effective_part_size(); |
| 738 | if data.len() < MULTIPART_THRESHOLD { |
| 739 | let payload = PutPayload::from(data.to_vec()); |
| 740 | let options = PutOptions { |
| 741 | attributes, |
| 742 | ..Default::default() |
| 743 | }; |
| 744 | store |
| 745 | .put_opts(&key, payload, options) |
| 746 | .await |
| 747 | .map_err(|e| Error::Other(format!("replica: upload to {key}: {e}").into()))?; |
| 748 | } else { |
| 749 | let options = PutMultipartOptions { |
| 750 | attributes, |
| 751 | ..Default::default() |
| 752 | }; |
| 753 | let mut upload = store |
| 754 | .put_multipart_opts(&key, options) |
| 755 | .await |
| 756 | .map_err(|e| Error::Other(format!("replica: upload to {key}: {e}").into()))?; |
| 757 | // Upload in fixed-size parts (each ≥ 5 MiB except possibly the last, |
| 758 | // matching object_store's part-size requirement). |
| 759 | for chunk in data.chunks(part_size.max(MULTIPART_THRESHOLD)) { |
| 760 | upload |
| 761 | .put_part(PutPayload::from(chunk.to_vec())) |
| 762 | .await |
| 763 | .map_err(|e| { |
| 764 | Error::Other(format!("replica: upload part to {key}: {e}").into()) |
| 765 | })?; |
| 766 | } |
| 767 | upload.complete().await.map_err(|e| { |
| 768 | Error::Other(format!("replica: complete upload to {key}: {e}").into()) |
| 769 | })?; |
| 770 | } |
| 771 | |
| 772 | Ok(FileInfo { |
| 773 | level, |
| 774 | min_txid, |
| 775 | max_txid, |
| 776 | size: data.len() as i64, |
| 777 | created_at: Some(created_at), |
| 778 | ..Default::default() |
| 779 | }) |
| 780 | } |
| 781 | |
| 782 | async fn delete_ltx_files(&self, files: &[FileInfo]) -> Result<()> { |
| 783 | if files.is_empty() { |
| 784 | return Ok(()); |
| 785 | } |
| 786 | let store = self.store().await?; |
| 787 | |
| 788 | // Build the key list, then delete in batches of MAX_KEYS via the |
| 789 | // store's delete_stream, surfacing per-key errors (brief §5.5). |
| 790 | let keys: Vec<ObjPath> = files |
| 791 | .iter() |
| 792 | .map(|info| ObjPath::from(self.ltx_key(info.level, info.min_txid, info.max_txid))) |
| 793 | .collect(); |
| 794 | |
| 795 | for batch in keys.chunks(MAX_KEYS) { |
| 796 | delete_batch(store.as_ref(), batch, /*ignore_missing=*/ true).await?; |
| 797 | } |
| 798 | Ok(()) |
| 799 | } |
| 800 | |
| 801 | async fn delete_all(&self) -> Result<()> { |
| 802 | let store = self.store().await?; |
| 803 | let prefix = ObjPath::from(self.root_prefix()); |
| 804 | |
| 805 | // List everything under the path prefix, then batch-delete. |
| 806 | // (s3/replica_client.go:1104-1148). |
| 807 | let keys: Vec<ObjPath> = store |
| 808 | .list(Some(&prefix)) |
| 809 | .map_ok(|m| m.location) |
| 810 | .map_err(map_os_error) |
| 811 | .try_collect() |
| 812 | .await?; |
| 813 | |
| 814 | for batch in keys.chunks(MAX_KEYS) { |
| 815 | delete_batch(store.as_ref(), batch, /*ignore_missing=*/ true).await?; |
| 816 | } |
| 817 | Ok(()) |
| 818 | } |
| 819 | } |
| 820 | |
| 821 | /// Delete a batch of keys via `delete_stream`, surfacing per-key errors. |
| 822 | /// |
| 823 | /// When `ignore_missing` is set, `NotFound` is tolerated (delete is idempotent — |
| 824 | /// the file client swallows ENOENT the same way), but every other per-key error |
| 825 | /// is returned (brief §5.5: do not silently swallow partial failures). |
| 826 | async fn delete_batch( |
| 827 | store: &dyn ObjectStore, |
| 828 | keys: &[ObjPath], |
| 829 | ignore_missing: bool, |
| 830 | ) -> Result<()> { |
| 831 | if keys.is_empty() { |
| 832 | return Ok(()); |
| 833 | } |
| 834 | let owned: Vec<ObjPath> = keys.to_vec(); |
| 835 | let stream = futures_util::stream::iter(owned.into_iter().map(Ok)); |
| 836 | let mut results = store.delete_stream(stream.boxed()); |
| 837 | while let Some(res) = results.next().await { |
| 838 | match res { |
| 839 | Ok(_) => {} |
| 840 | Err(object_store::Error::NotFound { .. }) if ignore_missing => {} |
| 841 | Err(e) => return Err(map_os_error(e)), |
| 842 | } |
| 843 | } |
| 844 | Ok(()) |
| 845 | } |
| 846 | |
| 847 | /// Format a Unix-millisecond timestamp like Go's `time.RFC3339Nano`. |
| 848 | fn format_rfc3339_nano(unix_millis: i64) -> Result<String> { |
| 849 | let mut timestamp = DateTime::from_timestamp_millis(unix_millis.max(0)) |
| 850 | .ok_or_else(|| Error::Other("LTX timestamp is outside the RFC3339 range".into()))? |
| 851 | .to_rfc3339_opts(SecondsFormat::AutoSi, true); |
| 852 | |
| 853 | // Chrono keeps millisecond precision as three digits. Go removes trailing |
| 854 | // zeros, so `.500Z` becomes `.5Z`. |
| 855 | if timestamp.contains('.') { |
| 856 | // The pop must stay outside debug_assert!, which vanishes in release |
| 857 | // builds and would leave the Z in place to be doubled below. |
| 858 | let suffix = timestamp.pop(); |
| 859 | debug_assert_eq!(suffix, Some('Z')); |
| 860 | while timestamp.ends_with('0') { |
| 861 | timestamp.pop(); |
| 862 | } |
| 863 | timestamp.push('Z'); |
| 864 | } |
| 865 | Ok(timestamp) |
| 866 | } |
| 867 | |
| 868 | #[doc(hidden)] |
| 869 | pub mod internal { |
| 870 | use super::*; |
| 871 | |
| 872 | pub const METADATA_KEY_TIMESTAMP: &str = super::METADATA_KEY_TIMESTAMP; |
| 873 | pub const METADATA_KEY_TIMESTAMP_UNDERSCORE: &str = super::METADATA_KEY_TIMESTAMP_UNDERSCORE; |
| 874 | |
| 875 | pub fn format_rfc3339_nano(unix_millis: i64) -> Result<String> { |
| 876 | super::format_rfc3339_nano(unix_millis) |
| 877 | } |
| 878 | |
| 879 | pub fn ltx_key(client: &ObjectStoreClient, level: i32, min: TXID, max: TXID) -> String { |
| 880 | client.ltx_key(level, min, max) |
| 881 | } |
| 882 | |
| 883 | pub fn level_prefix(client: &ObjectStoreClient, level: i32) -> String { |
| 884 | client.level_prefix(level) |
| 885 | } |
| 886 | |
| 887 | pub fn root_prefix(client: &ObjectStoreClient) -> String { |
| 888 | client.root_prefix() |
| 889 | } |
| 890 | |
| 891 | pub fn map_os_error(error: object_store::Error) -> Error { |
| 892 | super::map_os_error(error) |
| 893 | } |
| 894 | } |