| 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 that |
| 7 | //! let this client pass the T5 conformance suite against a real MinIO 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 | //! * the `litestream-timestamp` header-timestamp metadata, written on every |
| 16 | //! PUT and (on `use_metadata=true`) read back via a parallel `head` fan-out |
| 17 | //! (s3/replica_client.go:53, 679-683, 1384-1455); |
| 18 | //! * `NoSuchKey` → `os.ErrNotExist` error mapping |
| 19 | //! (s3/replica_client.go:647-649, 1662-1668); |
| 20 | //! * batch DELETE up to 1000 keys per call with per-key error surfacing |
| 21 | //! (s3/replica_client.go:1028-1101). |
| 22 | //! |
| 23 | //! The provider-defaults table (`ParseHost`, R2 concurrency, path-style flags, |
| 24 | //! endpoint env var) is a faithful port of `NewReplicaClientFromURL` |
| 25 | //! (s3/replica_client.go:133-314) so a `s3://…` URL configures the same way. |
| 26 | //! |
| 27 | //! This whole module is gated behind `#[cfg(feature = "s3")]` because it needs |
| 28 | //! `object_store`'s AWS backend. |
| 29 | |
| 30 | #![cfg(feature = "s3")] |
| 31 | |
| 32 | use std::sync::Arc; |
| 33 | |
| 34 | use futures::stream::{FuturesUnordered, StreamExt, TryStreamExt}; |
| 35 | use object_store::aws::AmazonS3Builder; |
| 36 | use object_store::path::Path as ObjPath; |
| 37 | use object_store::{ |
| 38 | Attribute, AttributeValue, Attributes, GetOptions, GetRange, ObjectStore, PutMultipartOpts, |
| 39 | PutOptions, PutPayload, |
| 40 | }; |
| 41 | |
| 42 | use crate::error::{Error, Result}; |
| 43 | use crate::ltx::{self, FileInfo}; |
| 44 | use crate::replica_url::{ |
| 45 | self, bool_query_value, ensure_endpoint_scheme, region_from_s3_arn, ParsedReplicaUrl, |
| 46 | }; |
| 47 | use crate::TXID; |
| 48 | |
| 49 | use super::ReplicaClient; |
| 50 | |
| 51 | /// The replica backend type string, matching `ReplicaClientType` ("s3"). |
| 52 | pub const REPLICA_CLIENT_TYPE: &str = "s3"; |
| 53 | |
| 54 | /// S3 metadata key carrying the LTX-header timestamp (RFC3339Nano), so accurate |
| 55 | /// timestamps survive across restores. Ported from `MetadataKeyTimestamp` |
| 56 | /// (s3/replica_client.go:53). |
| 57 | pub const METADATA_KEY_TIMESTAMP: &str = "litestream-timestamp"; |
| 58 | |
| 59 | /// Max keys S3 operates on per batch DELETE. `MaxKeys` (s3/replica_client.go:56). |
| 60 | pub const MAX_KEYS: usize = 1000; |
| 61 | |
| 62 | /// Region used when none is specified. `DefaultRegion` (s3/replica_client.go:59). |
| 63 | pub const DEFAULT_REGION: &str = "us-east-1"; |
| 64 | |
| 65 | /// Default parallel `head` calls for timestamp-based restore. |
| 66 | /// `DefaultMetadataConcurrency` (s3/replica_client.go:64). |
| 67 | pub const DEFAULT_METADATA_CONCURRENCY: usize = 50; |
| 68 | |
| 69 | /// Default concurrent multipart parts for Cloudflare R2 (strict limits). |
| 70 | /// `DefaultR2Concurrency` (s3/replica_client.go:68). |
| 71 | pub const DEFAULT_R2_CONCURRENCY: usize = 2; |
| 72 | |
| 73 | /// Multipart upload threshold: data at or above this size is uploaded with |
| 74 | /// `put_multipart`; below it, a single `put`. Matches the Go uploader's 5 MiB |
| 75 | /// `PartSize` default (s3/replica_client.go:99). |
| 76 | pub const MULTIPART_THRESHOLD: usize = 5 * 1024 * 1024; |
| 77 | |
| 78 | // ── Config ──────────────────────────────────────────────────────────────────── |
| 79 | |
| 80 | /// Configuration for the S3/R2/MinIO backend. |
| 81 | /// |
| 82 | /// Maps to the public fields of Go's `ReplicaClient` struct |
| 83 | /// (s3/replica_client.go:78-116). Zero/`None` values mean "use the backend |
| 84 | /// default". |
| 85 | #[derive(Debug, Clone, Default)] |
| 86 | pub struct ObjectStoreConfig { |
| 87 | /// Bucket name (required). |
| 88 | pub bucket: String, |
| 89 | /// Key prefix within the bucket. |
| 90 | pub path: String, |
| 91 | /// AWS region. |
| 92 | pub region: String, |
| 93 | /// Custom endpoint (MinIO, R2, …); empty = native AWS. |
| 94 | pub endpoint: String, |
| 95 | /// Static access key id; empty = ambient credential chain. |
| 96 | pub access_key_id: String, |
| 97 | /// Static secret access key; empty = ambient credential chain. |
| 98 | pub secret_access_key: String, |
| 99 | /// Session token for temporary/scoped credentials (STS, R2 API tokens); |
| 100 | /// empty = none. Required alongside temporary keys or signing fails. |
| 101 | pub session_token: String, |
| 102 | /// Force path-style addressing (required for MinIO/Backblaze/Supabase/Filebase). |
| 103 | pub force_path_style: bool, |
| 104 | /// Skip TLS verification (allows self-signed endpoints). |
| 105 | pub skip_verify: bool, |
| 106 | /// Multipart part size in bytes; 0 = default (5 MiB). |
| 107 | pub part_size: u64, |
| 108 | /// Concurrent multipart parts; 0 = default. R2 endpoints default to 2. |
| 109 | pub concurrency: usize, |
| 110 | } |
| 111 | |
| 112 | impl ObjectStoreConfig { |
| 113 | /// Construct from a parsed `s3://` URL, mirroring `NewReplicaClientFromURL` |
| 114 | /// (s3/replica_client.go:133-314): host → bucket/region/endpoint/path-style |
| 115 | /// (or ARN), query-param overrides (camelCase ↔ hyphenated aliases), the |
| 116 | /// `AWS_*`/`LITESTREAM_*` env credentials, the `LITESTREAM_S3_ENDPOINT` env |
| 117 | /// fallback, and the provider-specific defaults (R2 concurrency; path-style |
| 118 | /// for MinIO/Backblaze/Filebase/Supabase). |
| 119 | pub fn from_url(parsed: &ParsedReplicaUrl) -> Result<Self> { |
| 120 | let host = &parsed.host; |
| 121 | let query = &parsed.query; |
| 122 | |
| 123 | // Host → bucket/region/endpoint/forcePathStyle (or ARN access point). |
| 124 | let (bucket, mut region, mut endpoint, mut force_path_style) = if host.starts_with("arn:") { |
| 125 | (host.clone(), region_from_s3_arn(host), String::new(), false) |
| 126 | } else { |
| 127 | parse_host(host) |
| 128 | }; |
| 129 | |
| 130 | let q = Some(query); |
| 131 | |
| 132 | // endpoint query param: ensure scheme, default to path-style for custom |
| 133 | // endpoints unless force-path-style is explicitly set to false. |
| 134 | let q_endpoint = query.get("endpoint"); |
| 135 | if !q_endpoint.is_empty() { |
| 136 | let (ep, _) = ensure_endpoint_scheme(q_endpoint); |
| 137 | endpoint = ep; |
| 138 | match bool_query_value(q, &["forcePathStyle", "force-path-style"]) { |
| 139 | Some(false) => {} |
| 140 | _ => force_path_style = true, |
| 141 | } |
| 142 | } |
| 143 | let q_region = query.get("region"); |
| 144 | if !q_region.is_empty() { |
| 145 | region = q_region.to_string(); |
| 146 | } |
| 147 | if let Some(v) = bool_query_value(q, &["forcePathStyle", "force-path-style"]) { |
| 148 | force_path_style = v; |
| 149 | } |
| 150 | let mut skip_verify = false; |
| 151 | if let Some(v) = bool_query_value(q, &["skipVerify", "skip-verify"]) { |
| 152 | skip_verify = v; |
| 153 | } |
| 154 | |
| 155 | let mut concurrency: usize = 0; |
| 156 | let v = query.get("concurrency"); |
| 157 | if !v.is_empty() { |
| 158 | if let Ok(n) = v.parse::<usize>() { |
| 159 | if n > 0 { |
| 160 | concurrency = n; |
| 161 | } |
| 162 | } |
| 163 | } |
| 164 | let mut part_size: u64 = 0; |
| 165 | let v = query.get("partSize"); |
| 166 | let v2 = query.get("part-size"); |
| 167 | if !v.is_empty() { |
| 168 | if let Ok(n) = v.parse::<u64>() { |
| 169 | if n > 0 { |
| 170 | part_size = n; |
| 171 | } |
| 172 | } |
| 173 | } else if !v2.is_empty() { |
| 174 | if let Ok(n) = v2.parse::<u64>() { |
| 175 | if n > 0 { |
| 176 | part_size = n; |
| 177 | } |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | if bucket.is_empty() { |
| 182 | return Err(Error::Other("bucket required for s3 replica URL".into())); |
| 183 | } |
| 184 | |
| 185 | // Track whether forcePathStyle was explicitly set via query param |
| 186 | // (s3/replica_client.go:208) — this gates the env-var/provider defaults. |
| 187 | let force_path_style_set = |
| 188 | !query.get("forcePathStyle").is_empty() || !query.get("force-path-style").is_empty(); |
| 189 | |
| 190 | // Static credentials from env (AWS_* preferred, then LITESTREAM_*). |
| 191 | let mut access_key_id = String::new(); |
| 192 | let mut secret_access_key = String::new(); |
| 193 | if let Some(v) = nonempty_env("AWS_ACCESS_KEY_ID") { |
| 194 | access_key_id = v; |
| 195 | } else if let Some(v) = nonempty_env("LITESTREAM_ACCESS_KEY_ID") { |
| 196 | access_key_id = v; |
| 197 | } |
| 198 | if let Some(v) = nonempty_env("AWS_SECRET_ACCESS_KEY") { |
| 199 | secret_access_key = v; |
| 200 | } else if let Some(v) = nonempty_env("LITESTREAM_SECRET_ACCESS_KEY") { |
| 201 | secret_access_key = v; |
| 202 | } |
| 203 | let session_token = nonempty_env("AWS_SESSION_TOKEN") |
| 204 | .or_else(|| nonempty_env("LITESTREAM_SESSION_TOKEN")) |
| 205 | .unwrap_or_default(); |
| 206 | |
| 207 | // LITESTREAM_S3_ENDPOINT env fallback (only when no endpoint yet). |
| 208 | if endpoint.is_empty() { |
| 209 | if let Some(v) = nonempty_env("LITESTREAM_S3_ENDPOINT") { |
| 210 | let (ep, _) = ensure_endpoint_scheme(&v); |
| 211 | endpoint = ep; |
| 212 | if !force_path_style_set { |
| 213 | force_path_style = true; |
| 214 | } |
| 215 | } |
| 216 | } |
| 217 | |
| 218 | // Provider detection for applying defaults. |
| 219 | let is_filebase = replica_url::is_filebase_endpoint(&endpoint); |
| 220 | let is_backblaze = replica_url::is_backblaze_endpoint(&endpoint); |
| 221 | let is_minio = replica_url::is_minio_endpoint(&endpoint); |
| 222 | let is_supabase = replica_url::is_supabase_endpoint(&endpoint); |
| 223 | let is_r2 = replica_url::is_cloudflare_r2_endpoint(&endpoint); |
| 224 | |
| 225 | if !force_path_style_set && (is_filebase || is_backblaze || is_minio || is_supabase) { |
| 226 | force_path_style = true; |
| 227 | } |
| 228 | if is_r2 { |
| 229 | // R2 has strict per-bucket multipart concurrency limits. |
| 230 | concurrency = DEFAULT_R2_CONCURRENCY; |
| 231 | } |
| 232 | |
| 233 | Ok(ObjectStoreConfig { |
| 234 | bucket, |
| 235 | path: parsed.path.clone(), |
| 236 | region, |
| 237 | endpoint, |
| 238 | access_key_id, |
| 239 | secret_access_key, |
| 240 | session_token, |
| 241 | force_path_style, |
| 242 | skip_verify, |
| 243 | part_size, |
| 244 | concurrency, |
| 245 | }) |
| 246 | } |
| 247 | |
| 248 | /// Build the configured `AmazonS3` store. Ported from the relevant subset of |
| 249 | /// `Init` (s3/replica_client.go:322-477): bucket validation, region default, |
| 250 | /// custom endpoint, path-style toggle, static credentials, and `allow_http` |
| 251 | /// for plaintext/local endpoints. |
| 252 | /// Build the backing `Arc<dyn ObjectStore>` for this config. Public so a host |
| 253 | /// can build one store for a bucket and share it across many |
| 254 | /// [`ObjectStoreClient::with_store`] clients that differ only by key prefix |
| 255 | /// — one connection pool for every cell on a node. |
| 256 | pub fn build_store(&self) -> Result<Arc<dyn ObjectStore>> { |
| 257 | if self.bucket.is_empty() { |
| 258 | return Err(Error::Other("s3: bucket name is required".into())); |
| 259 | } |
| 260 | |
| 261 | let region = if self.region.is_empty() { |
| 262 | DEFAULT_REGION.to_string() |
| 263 | } else { |
| 264 | self.region.clone() |
| 265 | }; |
| 266 | |
| 267 | let mut builder = AmazonS3Builder::new() |
| 268 | .with_bucket_name(&self.bucket) |
| 269 | .with_region(region) |
| 270 | // Path-style ⇔ NOT virtual-hosted-style (s3/replica_client.go:258-263). |
| 271 | .with_virtual_hosted_style_request(!self.force_path_style); |
| 272 | |
| 273 | if !self.endpoint.is_empty() { |
| 274 | // A plaintext (http://) or local endpoint must allow non-TLS, and |
| 275 | // skip_verify likewise permits http (object_store gates http behind |
| 276 | // allow_http rather than a TLS-verify toggle). |
| 277 | let allow_http = self.endpoint.starts_with("http://") |
| 278 | || self.skip_verify |
| 279 | || replica_url::is_local_endpoint(&self.endpoint); |
| 280 | builder = builder |
| 281 | .with_endpoint(&self.endpoint) |
| 282 | .with_allow_http(allow_http); |
| 283 | } |
| 284 | |
| 285 | if !self.access_key_id.is_empty() { |
| 286 | builder = builder.with_access_key_id(&self.access_key_id); |
| 287 | } |
| 288 | if !self.secret_access_key.is_empty() { |
| 289 | builder = builder.with_secret_access_key(&self.secret_access_key); |
| 290 | } |
| 291 | if !self.session_token.is_empty() { |
| 292 | builder = builder.with_token(&self.session_token); |
| 293 | } |
| 294 | |
| 295 | let store = builder |
| 296 | .build() |
| 297 | .map_err(|e| Error::Other(format!("s3: build store: {e}").into()))?; |
| 298 | Ok(Arc::new(store)) |
| 299 | } |
| 300 | |
| 301 | /// Effective multipart part size (`part_size`, or the 5 MiB default). |
| 302 | fn effective_part_size(&self) -> usize { |
| 303 | if self.part_size > 0 { |
| 304 | self.part_size as usize |
| 305 | } else { |
| 306 | MULTIPART_THRESHOLD |
| 307 | } |
| 308 | } |
| 309 | } |
| 310 | |
| 311 | /// Returns `Some(value)` for a non-empty env var, else `None`. Mirrors Go's |
| 312 | /// `if v := os.Getenv(k); v != ""` pattern (s3/replica_client.go:211-224). |
| 313 | fn nonempty_env(key: &str) -> Option<String> { |
| 314 | match std::env::var(key) { |
| 315 | Ok(v) if !v.is_empty() => Some(v), |
| 316 | _ => None, |
| 317 | } |
| 318 | } |
| 319 | |
| 320 | // ── ParseHost ───────────────────────────────────────────────────────────────── |
| 321 | |
| 322 | /// Parse an S3 host into `(bucket, region, endpoint, force_path_style)`. |
| 323 | /// |
| 324 | /// Direct port of `ParseHost` (s3/replica_client.go:1608-1652): MinIO-style |
| 325 | /// `bucket.host:port`, then the AWS / DigitalOcean / Backblaze / Filebase / |
| 326 | /// Scaleway provider patterns, falling back to "host *is* the bucket". |
| 327 | pub fn parse_host(host: &str) -> (String, String, String, bool) { |
| 328 | // MinIO-style hosts: `bucket.host:port` (a colon and not a ".com"). |
| 329 | if host.contains(':') && !host.contains(".com") { |
| 330 | // SplitN(host, ".", 2) |
| 331 | if let Some((bucket, rest)) = host.split_once('.') { |
| 332 | return ( |
| 333 | bucket.to_string(), |
| 334 | DEFAULT_REGION.to_string(), |
| 335 | format!("http://{rest}"), |
| 336 | true, |
| 337 | ); |
| 338 | } |
| 339 | // No bucket in host, just host:port. |
| 340 | return (String::new(), String::new(), format!("http://{host}"), true); |
| 341 | } |
| 342 | |
| 343 | // AWS S3: `^(.+)\.s3(?:\.([^.]+))?\.amazonaws\.com$` |
| 344 | if let Some((bucket, region)) = match_aws_s3(host) { |
| 345 | return (bucket, region, String::new(), false); |
| 346 | } |
| 347 | // DigitalOcean: `^(?:(.+)\.)?([^.]+)\.digitaloceanspaces.com$` |
| 348 | if let Some((bucket, region)) = match_two_label_suffix(host, ".digitaloceanspaces.com") { |
| 349 | return ( |
| 350 | bucket, |
| 351 | region.clone(), |
| 352 | format!("https://{region}.digitaloceanspaces.com"), |
| 353 | false, |
| 354 | ); |
| 355 | } |
| 356 | // Backblaze: `^(?:(.+)\.)?s3.([^.]+)\.backblazeb2.com$` |
| 357 | if let Some((bucket, region)) = match_s3_region_suffix(host, ".backblazeb2.com") { |
| 358 | return ( |
| 359 | bucket, |
| 360 | region.clone(), |
| 361 | format!("https://s3.{region}.backblazeb2.com"), |
| 362 | true, |
| 363 | ); |
| 364 | } |
| 365 | // Filebase: `^(?:(.+)\.)?s3.filebase.com$` |
| 366 | if let Some(bucket) = match_filebase(host) { |
| 367 | return (bucket, String::new(), "s3.filebase.com".to_string(), false); |
| 368 | } |
| 369 | // Scaleway: `^(?:(.+)\.)?s3.([^.]+)\.scw\.cloud$` |
| 370 | if let Some((bucket, region)) = match_s3_region_suffix(host, ".scw.cloud") { |
| 371 | return ( |
| 372 | bucket, |
| 373 | region.clone(), |
| 374 | format!("s3.{region}.scw.cloud"), |
| 375 | false, |
| 376 | ); |
| 377 | } |
| 378 | |
| 379 | // Standard S3: the host is the bucket name. |
| 380 | (host.to_string(), String::new(), String::new(), false) |
| 381 | } |
| 382 | |
| 383 | /// `^(.+)\.s3(?:\.([^.]+))?\.amazonaws\.com$` → (bucket, region). |
| 384 | fn match_aws_s3(host: &str) -> Option<(String, String)> { |
| 385 | let rest = host.strip_suffix(".amazonaws.com")?; |
| 386 | // rest = "<bucket>.s3" or "<bucket>.s3.<region>" |
| 387 | if let Some(bucket) = rest.strip_suffix(".s3") { |
| 388 | if bucket.is_empty() { |
| 389 | return None; |
| 390 | } |
| 391 | return Some((bucket.to_string(), String::new())); |
| 392 | } |
| 393 | // "<bucket>.s3.<region>": find the ".s3." separator; region is a single |
| 394 | // label ([^.]+) — i.e. the remainder after ".s3." must contain no dot. |
| 395 | let idx = rest.find(".s3.")?; |
| 396 | let bucket = &rest[..idx]; |
| 397 | let region = &rest[idx + 4..]; |
| 398 | if bucket.is_empty() || region.is_empty() || region.contains('.') { |
| 399 | return None; |
| 400 | } |
| 401 | Some((bucket.to_string(), region.to_string())) |
| 402 | } |
| 403 | |
| 404 | /// `^(?:(.+)\.)?([^.]+)\.<suffix>$` → (bucket, region). `suffix` starts with '.'. |
| 405 | fn match_two_label_suffix(host: &str, suffix: &str) -> Option<(String, String)> { |
| 406 | let rest = host.strip_suffix(suffix)?; |
| 407 | if rest.is_empty() { |
| 408 | return None; |
| 409 | } |
| 410 | // The last label before the suffix is the region; anything before it |
| 411 | // (optionally) is the bucket. |
| 412 | match rest.rfind('.') { |
| 413 | Some(i) => { |
| 414 | let bucket = &rest[..i]; |
| 415 | let region = &rest[i + 1..]; |
| 416 | if region.is_empty() { |
| 417 | return None; |
| 418 | } |
| 419 | Some((bucket.to_string(), region.to_string())) |
| 420 | } |
| 421 | None => Some((String::new(), rest.to_string())), |
| 422 | } |
| 423 | } |
| 424 | |
| 425 | /// `^(?:(.+)\.)?s3.([^.]+)\.<suffix>$` → (bucket, region). `suffix` starts with '.'. |
| 426 | fn match_s3_region_suffix(host: &str, suffix: &str) -> Option<(String, String)> { |
| 427 | let rest = host.strip_suffix(suffix)?; |
| 428 | // rest = "[bucket.]s3.<region>"; region is one label ([^.]+). |
| 429 | // Bucket-less form: rest == "s3.<region>". |
| 430 | if let Some(region) = rest.strip_prefix("s3.") { |
| 431 | if region.is_empty() || region.contains('.') { |
| 432 | return None; |
| 433 | } |
| 434 | return Some((String::new(), region.to_string())); |
| 435 | } |
| 436 | // Bucketed form: rest == "<bucket>.s3.<region>". |
| 437 | let sep = rest.find(".s3.")?; |
| 438 | let bucket = &rest[..sep]; |
| 439 | let region = &rest[sep + 4..]; |
| 440 | if bucket.is_empty() || region.is_empty() || region.contains('.') { |
| 441 | return None; |
| 442 | } |
| 443 | Some((bucket.to_string(), region.to_string())) |
| 444 | } |
| 445 | |
| 446 | /// `^(?:(.+)\.)?s3.filebase.com$` → bucket. |
| 447 | fn match_filebase(host: &str) -> Option<String> { |
| 448 | if host == "s3.filebase.com" { |
| 449 | return Some(String::new()); |
| 450 | } |
| 451 | let bucket = host.strip_suffix(".s3.filebase.com")?; |
| 452 | if bucket.is_empty() { |
| 453 | None |
| 454 | } else { |
| 455 | Some(bucket.to_string()) |
| 456 | } |
| 457 | } |
| 458 | |
| 459 | // ── Client ──────────────────────────────────────────────────────────────────── |
| 460 | |
| 461 | /// Concrete S3/R2/MinIO backend, wrapping a lazily-initialised |
| 462 | /// `Arc<dyn ObjectStore>`. |
| 463 | /// |
| 464 | /// Mirrors Go `ReplicaClient` (s3/replica_client.go:78-116). The inner store is |
| 465 | /// created on the first call that needs it (`OnceCell`, mirroring `Init`, |
| 466 | /// s3/replica_client.go:322-477), so construction is infallible and race-free. |
| 467 | pub struct ObjectStoreClient { |
| 468 | store: tokio::sync::OnceCell<Arc<dyn ObjectStore>>, |
| 469 | config: ObjectStoreConfig, |
| 470 | } |
| 471 | |
| 472 | impl std::fmt::Debug for ObjectStoreClient { |
| 473 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 474 | f.debug_struct("ObjectStoreClient") |
| 475 | .field("config", &self.config) |
| 476 | .field("initialized", &self.store.initialized()) |
| 477 | .finish() |
| 478 | } |
| 479 | } |
| 480 | |
| 481 | impl ObjectStoreClient { |
| 482 | /// Create a client from config (no I/O; the store is built on first use). |
| 483 | pub fn new(config: ObjectStoreConfig) -> Self { |
| 484 | ObjectStoreClient { |
| 485 | store: tokio::sync::OnceCell::new(), |
| 486 | config, |
| 487 | } |
| 488 | } |
| 489 | |
| 490 | /// Create a client directly from an already-built `ObjectStore` (e.g. an |
| 491 | /// in-memory store for tests, or a pre-configured backend). |
| 492 | pub fn with_store(config: ObjectStoreConfig, store: Arc<dyn ObjectStore>) -> Self { |
| 493 | let cell = tokio::sync::OnceCell::new(); |
| 494 | cell.set(store).ok(); |
| 495 | ObjectStoreClient { |
| 496 | store: cell, |
| 497 | config, |
| 498 | } |
| 499 | } |
| 500 | |
| 501 | /// The configuration this client was built with. |
| 502 | pub fn config(&self) -> &ObjectStoreConfig { |
| 503 | &self.config |
| 504 | } |
| 505 | |
| 506 | /// Force early initialisation; idempotent (mirrors `Init`, |
| 507 | /// s3/replica_client.go:322-477). |
| 508 | pub async fn init(&self) -> Result<()> { |
| 509 | self.store().await.map(|_| ()) |
| 510 | } |
| 511 | |
| 512 | /// Get-or-build the inner store, once. |
| 513 | async fn store(&self) -> Result<&Arc<dyn ObjectStore>> { |
| 514 | self.store |
| 515 | .get_or_try_init(|| async { self.config.build_store() }) |
| 516 | .await |
| 517 | } |
| 518 | |
| 519 | /// Build the S3 key for an LTX file: `{path}/{level:04x}/{min}-{max}.ltx`. |
| 520 | /// Ported from s3/replica_client.go:629, 677, 1040-1042. |
| 521 | fn ltx_key(&self, level: i32, min_txid: TXID, max_txid: TXID) -> String { |
| 522 | let filename = ltx::format_filename(min_txid, max_txid); |
| 523 | format!("{}/{:04x}/{}", self.config.path, level, filename) |
| 524 | } |
| 525 | |
| 526 | /// Prefix for listing a level: `{path}/{level:04x}/`. |
| 527 | /// Ported from s3/replica_client.go:1363. |
| 528 | fn level_prefix(&self, level: i32) -> String { |
| 529 | format!("{}/{:04x}/", self.config.path, level) |
| 530 | } |
| 531 | |
| 532 | /// Root prefix for delete-all: `{path}/`. (s3/replica_client.go:1114). |
| 533 | fn root_prefix(&self) -> String { |
| 534 | format!("{}/", self.config.path) |
| 535 | } |
| 536 | } |
| 537 | |
| 538 | /// Map an `object_store::Error` to `crate::Error`, preserving NotFound as |
| 539 | /// `io::ErrorKind::NotFound` so callers keep working with the std error kind. |
| 540 | /// Mirrors `isNotExists` → `os.ErrNotExist` (s3/replica_client.go:647-649, |
| 541 | /// 1662-1668). |
| 542 | fn map_os_error(e: object_store::Error) -> Error { |
| 543 | match e { |
| 544 | object_store::Error::NotFound { .. } => { |
| 545 | Error::Io(std::io::Error::new(std::io::ErrorKind::NotFound, e)) |
| 546 | } |
| 547 | other => Error::Other(Box::new(other)), |
| 548 | } |
| 549 | } |
| 550 | |
| 551 | #[async_trait::async_trait] |
| 552 | impl ReplicaClient for ObjectStoreClient { |
| 553 | fn type_name(&self) -> &str { |
| 554 | REPLICA_CLIENT_TYPE |
| 555 | } |
| 556 | |
| 557 | async fn init(&self) -> Result<()> { |
| 558 | ObjectStoreClient::init(self).await |
| 559 | } |
| 560 | |
| 561 | async fn ltx_files(&self, level: i32, seek: TXID, use_metadata: bool) -> Result<Vec<FileInfo>> { |
| 562 | let store = self.store().await?; |
| 563 | let prefix = ObjPath::from(self.level_prefix(level)); |
| 564 | |
| 565 | // List everything under the level prefix. object_store yields keys in |
| 566 | // lexicographic order; since TXID hex is zero-padded to 16 digits, |
| 567 | // lexicographic == numeric ascending (brief §5.10). We still sort |
| 568 | // defensively after collecting, because the listing of an L0 level is |
| 569 | // bounded and small. |
| 570 | let metas: Vec<object_store::ObjectMeta> = store |
| 571 | .list(Some(&prefix)) |
| 572 | .map_err(map_os_error) |
| 573 | .try_collect() |
| 574 | .await?; |
| 575 | |
| 576 | // Parse filenames, applying the seek-skip filter (min_txid < seek). |
| 577 | // Done as a post-parse filter, NOT via a list prefix, because S3 prefix |
| 578 | // listing is lexicographic on the full key (brief §5.4). |
| 579 | let mut entries: Vec<(object_store::ObjectMeta, TXID, TXID)> = |
| 580 | Vec::with_capacity(metas.len()); |
| 581 | for meta in metas { |
| 582 | let name = meta.location.filename().unwrap_or(""); |
| 583 | let (min_txid, max_txid) = match ltx::parse_filename(name) { |
| 584 | Ok(t) => t, |
| 585 | Err(_) => continue, // skip non-LTX keys |
| 586 | }; |
| 587 | if min_txid < seek { |
| 588 | continue; |
| 589 | } |
| 590 | entries.push((meta, min_txid, max_txid)); |
| 591 | } |
| 592 | |
| 593 | // Timestamp source: when use_metadata is requested, read the |
| 594 | // litestream-timestamp attribute back via a parallel `head` fan-out |
| 595 | // (concurrency DEFAULT_METADATA_CONCURRENCY); otherwise fall back to the |
| 596 | // listing's last_modified. Ported from s3/replica_client.go:1384-1455, |
| 597 | // 1543-1553. |
| 598 | let mut header_ts: std::collections::HashMap<String, std::time::SystemTime> = |
| 599 | std::collections::HashMap::new(); |
| 600 | if use_metadata && !entries.is_empty() { |
| 601 | let keys: Vec<String> = entries |
| 602 | .iter() |
| 603 | .map(|(m, _, _)| m.location.to_string()) |
| 604 | .collect(); |
| 605 | header_ts = fetch_timestamp_metadata(store.as_ref(), &keys).await; |
| 606 | } |
| 607 | |
| 608 | let mut infos: Vec<FileInfo> = entries |
| 609 | .into_iter() |
| 610 | .map(|(meta, min_txid, max_txid)| { |
| 611 | let key = meta.location.to_string(); |
| 612 | let created_at = if use_metadata { |
| 613 | header_ts |
| 614 | .get(&key) |
| 615 | .copied() |
| 616 | .or_else(|| Some(std::time::SystemTime::from(meta.last_modified))) |
| 617 | } else { |
| 618 | Some(std::time::SystemTime::from(meta.last_modified)) |
| 619 | }; |
| 620 | FileInfo { |
| 621 | level, |
| 622 | min_txid, |
| 623 | max_txid, |
| 624 | size: meta.size as i64, |
| 625 | created_at, |
| 626 | ..Default::default() |
| 627 | } |
| 628 | }) |
| 629 | .collect(); |
| 630 | |
| 631 | // Iterator contract: ascending by (level, min_txid, max_txid). |
| 632 | infos.sort_by(|a, b| { |
| 633 | (a.level, a.min_txid.0, a.max_txid.0).cmp(&(b.level, b.min_txid.0, b.max_txid.0)) |
| 634 | }); |
| 635 | Ok(infos) |
| 636 | } |
| 637 | |
| 638 | async fn open_ltx_file( |
| 639 | &self, |
| 640 | level: i32, |
| 641 | min_txid: TXID, |
| 642 | max_txid: TXID, |
| 643 | offset: i64, |
| 644 | size: i64, |
| 645 | ) -> Result<Vec<u8>> { |
| 646 | let store = self.store().await?; |
| 647 | let key = ObjPath::from(self.ltx_key(level, min_txid, max_txid)); |
| 648 | |
| 649 | // Range: bytes=offset-(offset+size-1) when size>0, else bytes=offset- |
| 650 | // (s3/replica_client.go:620-625). |
| 651 | let off = offset.max(0) as usize; |
| 652 | let range = if size > 0 { |
| 653 | GetRange::Bounded(off..(off + size as usize)) |
| 654 | } else { |
| 655 | GetRange::Offset(off) |
| 656 | }; |
| 657 | |
| 658 | let opts = GetOptions { |
| 659 | range: Some(range), |
| 660 | ..Default::default() |
| 661 | }; |
| 662 | |
| 663 | let result = match store.get_opts(&key, opts).await { |
| 664 | Ok(r) => r, |
| 665 | Err(object_store::Error::NotFound { .. }) => { |
| 666 | return Err(Error::Io(std::io::Error::new( |
| 667 | std::io::ErrorKind::NotFound, |
| 668 | format!("s3: get object {key}: not found"), |
| 669 | ))); |
| 670 | } |
| 671 | // DECISION: an `offset >= object_size` range yields HTTP 416 from |
| 672 | // S3/MinIO (object_store surfaces it as a Generic "Range Not |
| 673 | // Satisfiable" error). The Go client would propagate that 416 as an |
| 674 | // error; our file client (T6) instead returns an empty slice when |
| 675 | // `offset >= len`. We mirror the *file client* here so both backends |
| 676 | // are interchangeable under `run_client_suite` (the T7 DoD). No real |
| 677 | // read path requests a past-EOF offset (restore reads the in-bounds |
| 678 | // page-index tail), so this only affects the degenerate case, and a |
| 679 | // genuine read error (anything not 416) still propagates below. |
| 680 | // Logged in OPEN_QUESTIONS.md. |
| 681 | Err(e) if is_range_not_satisfiable(&e) => return Ok(Vec::new()), |
| 682 | Err(e) => return Err(map_os_error(e)), |
| 683 | }; |
| 684 | |
| 685 | let bytes = result.bytes().await.map_err(map_os_error)?; |
| 686 | Ok(bytes.to_vec()) |
| 687 | } |
| 688 | |
| 689 | async fn write_ltx_file( |
| 690 | &self, |
| 691 | level: i32, |
| 692 | min_txid: TXID, |
| 693 | max_txid: TXID, |
| 694 | data: &[u8], |
| 695 | ) -> Result<FileInfo> { |
| 696 | let store = self.store().await?; |
| 697 | |
| 698 | // Peek the LTX header timestamp (preserved as litestream-timestamp). |
| 699 | // Ported from s3/replica_client.go:662-683. |
| 700 | let header = ltx::Header::parse(data)?; |
| 701 | let created_at = std::time::UNIX_EPOCH |
| 702 | + std::time::Duration::from_millis(header.timestamp.max(0) as u64); |
| 703 | let ts_rfc3339 = format_rfc3339_nano(header.timestamp); |
| 704 | |
| 705 | let mut attributes = Attributes::new(); |
| 706 | attributes.insert( |
| 707 | Attribute::Metadata(METADATA_KEY_TIMESTAMP.into()), |
| 708 | AttributeValue::from(ts_rfc3339), |
| 709 | ); |
| 710 | |
| 711 | let key = ObjPath::from(self.ltx_key(level, min_txid, max_txid)); |
| 712 | |
| 713 | // Multipart threshold: < 5 MiB → single PUT; ≥ 5 MiB → multipart with |
| 714 | // fixed-size parts. Ported from the Go uploader's 5 MiB PartSize default |
| 715 | // (s3/replica_client.go:99, brief §5.1). |
| 716 | let part_size = self.config.effective_part_size(); |
| 717 | if data.len() < MULTIPART_THRESHOLD { |
| 718 | let payload = PutPayload::from(data.to_vec()); |
| 719 | let opts = PutOptions { |
| 720 | attributes, |
| 721 | ..Default::default() |
| 722 | }; |
| 723 | store |
| 724 | .put_opts(&key, payload, opts) |
| 725 | .await |
| 726 | .map_err(|e| Error::Other(format!("s3: upload to {key}: {e}").into()))?; |
| 727 | } else { |
| 728 | let opts = PutMultipartOpts { |
| 729 | attributes, |
| 730 | ..Default::default() |
| 731 | }; |
| 732 | let mut upload = store |
| 733 | .put_multipart_opts(&key, opts) |
| 734 | .await |
| 735 | .map_err(|e| Error::Other(format!("s3: upload to {key}: {e}").into()))?; |
| 736 | // Upload in fixed-size parts (each ≥ 5 MiB except possibly the last, |
| 737 | // matching object_store's part-size requirement). |
| 738 | for chunk in data.chunks(part_size.max(MULTIPART_THRESHOLD)) { |
| 739 | upload |
| 740 | .put_part(PutPayload::from(chunk.to_vec())) |
| 741 | .await |
| 742 | .map_err(|e| Error::Other(format!("s3: upload part to {key}: {e}").into()))?; |
| 743 | } |
| 744 | upload |
| 745 | .complete() |
| 746 | .await |
| 747 | .map_err(|e| Error::Other(format!("s3: complete upload to {key}: {e}").into()))?; |
| 748 | } |
| 749 | |
| 750 | Ok(FileInfo { |
| 751 | level, |
| 752 | min_txid, |
| 753 | max_txid, |
| 754 | size: data.len() as i64, |
| 755 | created_at: Some(created_at), |
| 756 | ..Default::default() |
| 757 | }) |
| 758 | } |
| 759 | |
| 760 | async fn delete_ltx_files(&self, files: &[FileInfo]) -> Result<()> { |
| 761 | if files.is_empty() { |
| 762 | return Ok(()); |
| 763 | } |
| 764 | let store = self.store().await?; |
| 765 | |
| 766 | // Build the key list, then delete in batches of MAX_KEYS via the |
| 767 | // store's delete_stream, surfacing per-key errors (brief §5.5). |
| 768 | let keys: Vec<ObjPath> = files |
| 769 | .iter() |
| 770 | .map(|info| ObjPath::from(self.ltx_key(info.level, info.min_txid, info.max_txid))) |
| 771 | .collect(); |
| 772 | |
| 773 | for batch in keys.chunks(MAX_KEYS) { |
| 774 | delete_batch(store.as_ref(), batch, /*ignore_missing=*/ true).await?; |
| 775 | } |
| 776 | Ok(()) |
| 777 | } |
| 778 | |
| 779 | async fn delete_all(&self) -> Result<()> { |
| 780 | let store = self.store().await?; |
| 781 | let prefix = ObjPath::from(self.root_prefix()); |
| 782 | |
| 783 | // List everything under the path prefix, then batch-delete. |
| 784 | // (s3/replica_client.go:1104-1148). |
| 785 | let keys: Vec<ObjPath> = store |
| 786 | .list(Some(&prefix)) |
| 787 | .map_ok(|m| m.location) |
| 788 | .map_err(map_os_error) |
| 789 | .try_collect() |
| 790 | .await?; |
| 791 | |
| 792 | for batch in keys.chunks(MAX_KEYS) { |
| 793 | delete_batch(store.as_ref(), batch, /*ignore_missing=*/ true).await?; |
| 794 | } |
| 795 | Ok(()) |
| 796 | } |
| 797 | } |
| 798 | |
| 799 | /// Returns `true` if the error is S3's "range not satisfiable" (HTTP 416), |
| 800 | /// which object_store surfaces as a `Generic`/`NotModified`-shaped error when a |
| 801 | /// requested range begins at or after the object's end. |
| 802 | fn is_range_not_satisfiable(e: &object_store::Error) -> bool { |
| 803 | // object_store does not expose a dedicated variant; match on the rendered |
| 804 | // message, which includes the upstream status. This only affects the |
| 805 | // offset-past-EOF parity case; a real read error still propagates. |
| 806 | let msg = e.to_string(); |
| 807 | msg.contains("Range Not Satisfiable") || msg.contains("416") |
| 808 | } |
| 809 | |
| 810 | /// Delete a batch of keys via `delete_stream`, surfacing per-key errors. |
| 811 | /// |
| 812 | /// When `ignore_missing` is set, `NotFound` is tolerated (delete is idempotent — |
| 813 | /// the file client swallows ENOENT the same way), but every other per-key error |
| 814 | /// is returned (brief §5.5: do not silently swallow partial failures). |
| 815 | async fn delete_batch( |
| 816 | store: &dyn ObjectStore, |
| 817 | keys: &[ObjPath], |
| 818 | ignore_missing: bool, |
| 819 | ) -> Result<()> { |
| 820 | if keys.is_empty() { |
| 821 | return Ok(()); |
| 822 | } |
| 823 | let owned: Vec<ObjPath> = keys.to_vec(); |
| 824 | let stream = futures::stream::iter(owned.into_iter().map(Ok)); |
| 825 | let mut results = store.delete_stream(stream.boxed()); |
| 826 | while let Some(res) = results.next().await { |
| 827 | match res { |
| 828 | Ok(_) => {} |
| 829 | Err(object_store::Error::NotFound { .. }) if ignore_missing => {} |
| 830 | Err(e) => return Err(map_os_error(e)), |
| 831 | } |
| 832 | } |
| 833 | Ok(()) |
| 834 | } |
| 835 | |
| 836 | /// Fetch the `litestream-timestamp` header timestamp for each key via a parallel |
| 837 | /// `head` fan-out, bounded to `DEFAULT_METADATA_CONCURRENCY` in-flight requests. |
| 838 | /// |
| 839 | /// A missing/unparseable attribute or a failed `head` is non-fatal (the key is |
| 840 | /// simply absent from the map, and the caller falls back to `last_modified`), |
| 841 | /// matching the Go behavior (s3/replica_client.go:1427-1442). |
| 842 | async fn fetch_timestamp_metadata( |
| 843 | store: &dyn ObjectStore, |
| 844 | keys: &[String], |
| 845 | ) -> std::collections::HashMap<String, std::time::SystemTime> { |
| 846 | use std::collections::HashMap; |
| 847 | let mut out: HashMap<String, std::time::SystemTime> = HashMap::new(); |
| 848 | let mut in_flight = FuturesUnordered::new(); |
| 849 | let mut iter = keys.iter(); |
| 850 | |
| 851 | // Prime the pump up to the concurrency limit. |
| 852 | for _ in 0..DEFAULT_METADATA_CONCURRENCY { |
| 853 | match iter.next() { |
| 854 | Some(k) => in_flight.push(head_timestamp(store, k.clone())), |
| 855 | None => break, |
| 856 | } |
| 857 | } |
| 858 | |
| 859 | while let Some((key, ts)) = in_flight.next().await { |
| 860 | if let Some(ts) = ts { |
| 861 | out.insert(key, ts); |
| 862 | } |
| 863 | if let Some(k) = iter.next() { |
| 864 | in_flight.push(head_timestamp(store, k.clone())); |
| 865 | } |
| 866 | } |
| 867 | out |
| 868 | } |
| 869 | |
| 870 | /// `head` one key and parse its `litestream-timestamp` attribute, if present. |
| 871 | async fn head_timestamp( |
| 872 | store: &dyn ObjectStore, |
| 873 | key: String, |
| 874 | ) -> (String, Option<std::time::SystemTime>) { |
| 875 | let path = ObjPath::from(key.clone()); |
| 876 | let opts = GetOptions { |
| 877 | head: true, |
| 878 | ..Default::default() |
| 879 | }; |
| 880 | match store.get_opts(&path, opts).await { |
| 881 | Ok(result) => { |
| 882 | let attr = result |
| 883 | .attributes |
| 884 | .get(&Attribute::Metadata(METADATA_KEY_TIMESTAMP.into())) |
| 885 | .map(|v| v.as_ref().to_string()); |
| 886 | let ts = attr.as_deref().and_then(parse_rfc3339_nano); |
| 887 | (key, ts) |
| 888 | } |
| 889 | // Non-fatal: fall back to LastModified for this key. |
| 890 | Err(_) => (key, None), |
| 891 | } |
| 892 | } |
| 893 | |
| 894 | // ── RFC3339Nano timestamp (de)serialisation ────────────────────────────────── |
| 895 | // |
| 896 | // Go stores `time.UnixMilli(hdr.Timestamp).UTC().Format(time.RFC3339Nano)` in |
| 897 | // the metadata (s3/replica_client.go:671-681) and parses it back with |
| 898 | // `time.Parse(time.RFC3339Nano, ts)` (s3/replica_client.go:1435). We don't pull |
| 899 | // in a date crate (AGENTS.md rule 7); these two helpers round-trip the exact |
| 900 | // shape we write — `YYYY-MM-DDTHH:MM:SS[.fffffffff]Z` — which is all the |
| 901 | // `use_metadata` restore path needs, since it only ever reads timestamps that |
| 902 | // this same client wrote. |
| 903 | |
| 904 | /// Format `unix_millis` as an RFC3339Nano UTC string (`…Z`, fractional seconds |
| 905 | /// trimmed of trailing zeros, matching Go's `time.RFC3339Nano`). |
| 906 | fn format_rfc3339_nano(unix_millis: i64) -> String { |
| 907 | // Decompose into whole seconds + millisecond remainder (>= 0). |
| 908 | let millis = unix_millis.max(0); |
| 909 | let secs = millis / 1000; |
| 910 | let ms = (millis % 1000) as u32; |
| 911 | |
| 912 | let (year, month, day, hour, min, sec) = civil_from_unix_secs(secs); |
| 913 | if ms == 0 { |
| 914 | format!("{year:04}-{month:02}-{day:02}T{hour:02}:{min:02}:{sec:02}Z") |
| 915 | } else { |
| 916 | // RFC3339Nano trims trailing zeros; milliseconds → up to 3 digits. |
| 917 | let mut frac = format!("{ms:03}"); |
| 918 | while frac.ends_with('0') { |
| 919 | frac.pop(); |
| 920 | } |
| 921 | format!("{year:04}-{month:02}-{day:02}T{hour:02}:{min:02}:{sec:02}.{frac}Z") |
| 922 | } |
| 923 | } |
| 924 | |
| 925 | /// Parse an RFC3339Nano UTC string (as produced by [`format_rfc3339_nano`]) |
| 926 | /// back into a `SystemTime`. Returns `None` on any shape we don't recognise. |
| 927 | fn parse_rfc3339_nano(s: &str) -> Option<std::time::SystemTime> { |
| 928 | // Expect: YYYY-MM-DDTHH:MM:SS[.fraction]Z |
| 929 | let s = s.strip_suffix('Z')?; |
| 930 | let (date, time) = s.split_once('T')?; |
| 931 | let mut dparts = date.split('-'); |
| 932 | let year: i64 = dparts.next()?.parse().ok()?; |
| 933 | let month: u32 = dparts.next()?.parse().ok()?; |
| 934 | let day: u32 = dparts.next()?.parse().ok()?; |
| 935 | if dparts.next().is_some() { |
| 936 | return None; |
| 937 | } |
| 938 | |
| 939 | let (hms, frac) = match time.split_once('.') { |
| 940 | Some((hms, frac)) => (hms, Some(frac)), |
| 941 | None => (time, None), |
| 942 | }; |
| 943 | let mut tparts = hms.split(':'); |
| 944 | let hour: u32 = tparts.next()?.parse().ok()?; |
| 945 | let min: u32 = tparts.next()?.parse().ok()?; |
| 946 | let sec: u32 = tparts.next()?.parse().ok()?; |
| 947 | if tparts.next().is_some() { |
| 948 | return None; |
| 949 | } |
| 950 | |
| 951 | let secs = unix_secs_from_civil(year, month, day, hour, min, sec)?; |
| 952 | let nanos: u32 = match frac { |
| 953 | Some(frac) => { |
| 954 | if frac.is_empty() || frac.len() > 9 || !frac.bytes().all(|b| b.is_ascii_digit()) { |
| 955 | return None; |
| 956 | } |
| 957 | let mut padded = frac.to_string(); |
| 958 | while padded.len() < 9 { |
| 959 | padded.push('0'); |
| 960 | } |
| 961 | padded.parse().ok()? |
| 962 | } |
| 963 | None => 0, |
| 964 | }; |
| 965 | |
| 966 | if secs < 0 { |
| 967 | return None; |
| 968 | } |
| 969 | Some(std::time::UNIX_EPOCH + std::time::Duration::new(secs as u64, nanos)) |
| 970 | } |
| 971 | |
| 972 | /// Convert a Unix timestamp (whole seconds, >= 0) to a civil |
| 973 | /// `(year, month, day, hour, min, sec)` in UTC. Uses Howard Hinnant's |
| 974 | /// days-from-civil inverse (public-domain algorithm), exact for all dates. |
| 975 | fn civil_from_unix_secs(secs: i64) -> (i64, u32, u32, u32, u32, u32) { |
| 976 | let days = secs.div_euclid(86_400); |
| 977 | let rem = secs.rem_euclid(86_400); |
| 978 | let hour = (rem / 3600) as u32; |
| 979 | let min = ((rem % 3600) / 60) as u32; |
| 980 | let sec = (rem % 60) as u32; |
| 981 | |
| 982 | // civil_from_days (days since 1970-01-01). |
| 983 | let z = days + 719_468; |
| 984 | let era = if z >= 0 { z } else { z - 146_096 } / 146_097; |
| 985 | let doe = z - era * 146_097; // [0, 146096] |
| 986 | let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; // [0, 399] |
| 987 | let y = yoe + era * 400; |
| 988 | let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // [0, 365] |
| 989 | let mp = (5 * doy + 2) / 153; // [0, 11] |
| 990 | let d = (doy - (153 * mp + 2) / 5 + 1) as u32; // [1, 31] |
| 991 | let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32; // [1, 12] |
| 992 | let year = if m <= 2 { y + 1 } else { y }; |
| 993 | (year, m, d, hour, min, sec) |
| 994 | } |
| 995 | |
| 996 | /// Inverse of [`civil_from_unix_secs`]: civil UTC → Unix seconds. Returns `None` |
| 997 | /// for an out-of-range month/day. Uses Howard Hinnant's days_from_civil. |
| 998 | fn unix_secs_from_civil( |
| 999 | year: i64, |
| 1000 | month: u32, |
| 1001 | day: u32, |
| 1002 | hour: u32, |
| 1003 | min: u32, |
| 1004 | sec: u32, |
| 1005 | ) -> Option<i64> { |
| 1006 | if !(1..=12).contains(&month) || !(1..=31).contains(&day) || hour > 23 || min > 59 || sec > 60 { |
| 1007 | return None; |
| 1008 | } |
| 1009 | let y = if month <= 2 { year - 1 } else { year }; |
| 1010 | let era = if y >= 0 { y } else { y - 399 } / 400; |
| 1011 | let yoe = y - era * 400; // [0, 399] |
| 1012 | let m = month as i64; |
| 1013 | let d = day as i64; |
| 1014 | let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d - 1; // [0, 365] |
| 1015 | let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; // [0, 146096] |
| 1016 | let days = era * 146_097 + doe - 719_468; |
| 1017 | Some(days * 86_400 + hour as i64 * 3600 + min as i64 * 60 + sec as i64) |
| 1018 | } |
| 1019 | |
| 1020 | #[cfg(test)] |
| 1021 | mod tests { |
| 1022 | use super::*; |
| 1023 | use crate::replica_url::parse_replica_url_with_query; |
| 1024 | |
| 1025 | // ── ParseHost (port of TestParseHost, s3/replica_client_test.go:1071) ────── |
| 1026 | #[test] |
| 1027 | fn parse_host_table() { |
| 1028 | let cases: &[(&str, &str, &str, &str, bool)] = &[ |
| 1029 | ( |
| 1030 | "my-space.sgp1.digitaloceanspaces.com", |
| 1031 | "my-space", |
| 1032 | "sgp1", |
| 1033 | "https://sgp1.digitaloceanspaces.com", |
| 1034 | false, |
| 1035 | ), |
| 1036 | ( |
| 1037 | "test-bucket.nyc3.digitaloceanspaces.com", |
| 1038 | "test-bucket", |
| 1039 | "nyc3", |
| 1040 | "https://nyc3.digitaloceanspaces.com", |
| 1041 | false, |
| 1042 | ), |
| 1043 | ( |
| 1044 | "mybucket.s3.us-east-1.amazonaws.com", |
| 1045 | "mybucket", |
| 1046 | "us-east-1", |
| 1047 | "", |
| 1048 | false, |
| 1049 | ), |
| 1050 | ("mybucket.s3.amazonaws.com", "mybucket", "", "", false), |
| 1051 | ( |
| 1052 | "mybucket.s3.us-west-004.backblazeb2.com", |
| 1053 | "mybucket", |
| 1054 | "us-west-004", |
| 1055 | "https://s3.us-west-004.backblazeb2.com", |
| 1056 | true, |
| 1057 | ), |
| 1058 | ( |
| 1059 | "mybucket.localhost:9000", |
| 1060 | "mybucket", |
| 1061 | "us-east-1", |
| 1062 | "http://localhost:9000", |
| 1063 | true, |
| 1064 | ), |
| 1065 | ]; |
| 1066 | for (host, b, r, e, fps) in cases { |
| 1067 | let (bucket, region, endpoint, force) = parse_host(host); |
| 1068 | assert_eq!(&bucket, b, "bucket for {host}"); |
| 1069 | assert_eq!(®ion, r, "region for {host}"); |
| 1070 | assert_eq!(&endpoint, e, "endpoint for {host}"); |
| 1071 | assert_eq!(force, *fps, "force_path_style for {host}"); |
| 1072 | } |
| 1073 | } |
| 1074 | |
| 1075 | #[test] |
| 1076 | fn parse_host_standard_s3_is_bucket() { |
| 1077 | let (bucket, region, endpoint, force) = parse_host("mybucket"); |
| 1078 | assert_eq!(bucket, "mybucket"); |
| 1079 | assert_eq!(region, ""); |
| 1080 | assert_eq!(endpoint, ""); |
| 1081 | assert!(!force); |
| 1082 | } |
| 1083 | |
| 1084 | fn cfg_from_url(url: &str) -> ObjectStoreConfig { |
| 1085 | let parsed = parse_replica_url_with_query(url).unwrap(); |
| 1086 | ObjectStoreConfig::from_url(&parsed).unwrap() |
| 1087 | } |
| 1088 | |
| 1089 | // ── R2 concurrency default (port of TestReplicaClient_R2ConcurrencyDefault, |
| 1090 | // s3/replica_client_test.go:1795) ───────────────────────────────────────── |
| 1091 | #[test] |
| 1092 | fn r2_concurrency_default() { |
| 1093 | assert_eq!( |
| 1094 | cfg_from_url("s3://mybucket/path?endpoint=https://account123.r2.cloudflarestorage.com") |
| 1095 | .concurrency, |
| 1096 | 2, |
| 1097 | "R2 endpoint defaults concurrency to 2" |
| 1098 | ); |
| 1099 | assert_eq!( |
| 1100 | cfg_from_url("s3://mybucket/path").concurrency, |
| 1101 | 0, |
| 1102 | "AWS: no concurrency override" |
| 1103 | ); |
| 1104 | assert_eq!( |
| 1105 | cfg_from_url("s3://mybucket/path?endpoint=http://localhost:9000").concurrency, |
| 1106 | 0, |
| 1107 | "MinIO: no concurrency override" |
| 1108 | ); |
| 1109 | } |
| 1110 | |
| 1111 | // ── URL query param aliases (port of |
| 1112 | // TestNewReplicaClientFromURL_QueryParamAliases, test:1940) ─────────────── |
| 1113 | #[test] |
| 1114 | fn query_param_aliases() { |
| 1115 | let c = cfg_from_url("s3://mybucket/path?forcePathStyle=true"); |
| 1116 | assert!(c.force_path_style); |
| 1117 | |
| 1118 | let c = cfg_from_url("s3://mybucket/path?force-path-style=true"); |
| 1119 | assert!(c.force_path_style); |
| 1120 | |
| 1121 | let c = cfg_from_url( |
| 1122 | "s3://mybucket/path?endpoint=http://localhost:9000&force-path-style=false", |
| 1123 | ); |
| 1124 | assert!(!c.force_path_style, "explicit force-path-style=false wins"); |
| 1125 | |
| 1126 | let c = cfg_from_url("s3://mybucket/path?skipVerify=true"); |
| 1127 | assert!(c.skip_verify); |
| 1128 | let c = cfg_from_url("s3://mybucket/path?skip-verify=true"); |
| 1129 | assert!(c.skip_verify); |
| 1130 | |
| 1131 | let c = cfg_from_url("s3://mybucket/path?concurrency=3"); |
| 1132 | assert_eq!(c.concurrency, 3); |
| 1133 | |
| 1134 | let c = cfg_from_url("s3://mybucket/path?part-size=10485760"); |
| 1135 | assert_eq!(c.part_size, 10_485_760); |
| 1136 | let c = cfg_from_url("s3://mybucket/path?partSize=10485760"); |
| 1137 | assert_eq!(c.part_size, 10_485_760); |
| 1138 | |
| 1139 | let c = cfg_from_url( |
| 1140 | "s3://mybucket/path?force-path-style=true&skip-verify=true&concurrency=4&part-size=8388608", |
| 1141 | ); |
| 1142 | assert!(c.force_path_style); |
| 1143 | assert!(c.skip_verify); |
| 1144 | assert_eq!(c.concurrency, 4); |
| 1145 | assert_eq!(c.part_size, 8_388_608); |
| 1146 | } |
| 1147 | |
| 1148 | // ── Endpoint env var (port of TestNewReplicaClientFromURL_EndpointEnvVar, |
| 1149 | // test:2023). These mutate a process-global env var, so they run |
| 1150 | // sequentially under one #[test] with save/restore to avoid cross-test |
| 1151 | // interference. ─────────────────────────────────────────────────────────── |
| 1152 | #[test] |
| 1153 | fn endpoint_env_var() { |
| 1154 | let saved = std::env::var("LITESTREAM_S3_ENDPOINT").ok(); |
| 1155 | |
| 1156 | let set = |v: &str| { |
| 1157 | if v.is_empty() { |
| 1158 | std::env::remove_var("LITESTREAM_S3_ENDPOINT"); |
| 1159 | } else { |
| 1160 | std::env::set_var("LITESTREAM_S3_ENDPOINT", v); |
| 1161 | } |
| 1162 | }; |
| 1163 | |
| 1164 | set("http://localhost:9000"); |
| 1165 | let c = cfg_from_url("s3://mybucket/path"); |
| 1166 | assert_eq!(c.endpoint, "http://localhost:9000"); |
| 1167 | assert!(c.force_path_style, "env endpoint forces path-style"); |
| 1168 | |
| 1169 | set("s3.example.com"); |
| 1170 | let c = cfg_from_url("s3://mybucket/path"); |
| 1171 | assert_eq!( |
| 1172 | c.endpoint, "https://s3.example.com", |
| 1173 | "env endpoint gets https" |
| 1174 | ); |
| 1175 | assert!(c.force_path_style); |
| 1176 | |
| 1177 | set("http://localhost:9000"); |
| 1178 | let c = cfg_from_url("s3://mybucket/path?endpoint=http://other:9000"); |
| 1179 | assert_eq!( |
| 1180 | c.endpoint, "http://other:9000", |
| 1181 | "query endpoint overrides env" |
| 1182 | ); |
| 1183 | assert!(c.force_path_style); |
| 1184 | |
| 1185 | set("http://localhost:9000"); |
| 1186 | let c = cfg_from_url("s3://mybucket/path?force-path-style=false"); |
| 1187 | assert_eq!(c.endpoint, "http://localhost:9000"); |
| 1188 | assert!( |
| 1189 | !c.force_path_style, |
| 1190 | "explicit force-path-style=false respected with env endpoint" |
| 1191 | ); |
| 1192 | |
| 1193 | set(""); |
| 1194 | let c = cfg_from_url("s3://mybucket/path"); |
| 1195 | assert_eq!(c.endpoint, ""); |
| 1196 | assert!(!c.force_path_style); |
| 1197 | |
| 1198 | // Restore. |
| 1199 | match saved { |
| 1200 | Some(v) => std::env::set_var("LITESTREAM_S3_ENDPOINT", v), |
| 1201 | None => std::env::remove_var("LITESTREAM_S3_ENDPOINT"), |
| 1202 | } |
| 1203 | } |
| 1204 | |
| 1205 | // ── Bucket validation (port of TestReplicaClient_Init_BucketValidation, |
| 1206 | // test:468). Empty bucket → build error. ──────────────────────────────── |
| 1207 | #[tokio::test] |
| 1208 | async fn empty_bucket_errors_on_init() { |
| 1209 | let client = ObjectStoreClient::new(ObjectStoreConfig::default()); |
| 1210 | assert!(client.init().await.is_err(), "empty bucket must error"); |
| 1211 | } |
| 1212 | |
| 1213 | // ── Key construction (wire-compat requirement D-1, test:629/677/1040) ───── |
| 1214 | #[test] |
| 1215 | fn ltx_key_scheme() { |
| 1216 | let client = ObjectStoreClient::new(ObjectStoreConfig { |
| 1217 | bucket: "b".into(), |
| 1218 | path: "replica".into(), |
| 1219 | ..Default::default() |
| 1220 | }); |
| 1221 | assert_eq!( |
| 1222 | client.ltx_key(0, TXID(1), TXID(1)), |
| 1223 | "replica/0000/0000000000000001-0000000000000001.ltx" |
| 1224 | ); |
| 1225 | assert_eq!( |
| 1226 | client.ltx_key(0, TXID(1), TXID(6)), |
| 1227 | "replica/0000/0000000000000001-0000000000000006.ltx" |
| 1228 | ); |
| 1229 | assert_eq!(client.level_prefix(0), "replica/0000/"); |
| 1230 | assert_eq!(client.root_prefix(), "replica/"); |
| 1231 | } |
| 1232 | |
| 1233 | // ── isNotExists mapping (port of TestIsNotExists, test:53) ──────────────── |
| 1234 | #[test] |
| 1235 | fn not_found_maps_to_io_not_found() { |
| 1236 | let e = map_os_error(object_store::Error::NotFound { |
| 1237 | path: "k".into(), |
| 1238 | source: "missing".into(), |
| 1239 | }); |
| 1240 | match e { |
| 1241 | Error::Io(io) => assert_eq!(io.kind(), std::io::ErrorKind::NotFound), |
| 1242 | other => panic!("expected Io(NotFound), got {other:?}"), |
| 1243 | } |
| 1244 | } |
| 1245 | |
| 1246 | // ── RFC3339Nano round-trip (the timestamp metadata path, test:671/1435) ─── |
| 1247 | #[test] |
| 1248 | fn rfc3339_nano_round_trip() { |
| 1249 | // 2021-01-01T00:00:00Z = 1609459200000 ms. |
| 1250 | assert_eq!( |
| 1251 | format_rfc3339_nano(1_609_459_200_000), |
| 1252 | "2021-01-01T00:00:00Z" |
| 1253 | ); |
| 1254 | // With a millisecond fraction (trailing zeros trimmed). |
| 1255 | assert_eq!( |
| 1256 | format_rfc3339_nano(1_609_459_200_500), |
| 1257 | "2021-01-01T00:00:00.5Z" |
| 1258 | ); |
| 1259 | assert_eq!(format_rfc3339_nano(0), "1970-01-01T00:00:00Z"); |
| 1260 | |
| 1261 | for ms in [ |
| 1262 | 0i64, |
| 1263 | 1_000, |
| 1264 | 1_609_459_200_000, |
| 1265 | 1_609_459_200_123, |
| 1266 | 1_700_000_000_777, |
| 1267 | ] { |
| 1268 | let s = format_rfc3339_nano(ms); |
| 1269 | let back = parse_rfc3339_nano(&s).expect("parse our own format"); |
| 1270 | let got = back |
| 1271 | .duration_since(std::time::UNIX_EPOCH) |
| 1272 | .unwrap() |
| 1273 | .as_millis() as i64; |
| 1274 | assert_eq!(got, ms, "round trip for {ms} via {s:?}"); |
| 1275 | } |
| 1276 | |
| 1277 | // Reject malformed inputs. |
| 1278 | assert!(parse_rfc3339_nano("not-a-date").is_none()); |
| 1279 | assert!(parse_rfc3339_nano("2021-01-01T00:00:00").is_none()); // missing Z |
| 1280 | assert!(parse_rfc3339_nano("2021-13-01T00:00:00Z").is_none()); // bad month |
| 1281 | } |
| 1282 | |
| 1283 | #[test] |
| 1284 | fn type_name_is_s3() { |
| 1285 | let client = ObjectStoreClient::new(ObjectStoreConfig { |
| 1286 | bucket: "b".into(), |
| 1287 | ..Default::default() |
| 1288 | }); |
| 1289 | assert_eq!(client.type_name(), "s3"); |
| 1290 | } |
| 1291 | } |