Diffinery

homeflare/celldpublic

celld/crates/ltx/src/client/object_store.rs
1090 lines · 41.2 KBRaw History
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//! * `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
29use std::sync::Arc;
30
31use chrono::{DateTime, SecondsFormat};
32use futures_util::stream::{StreamExt, TryStreamExt};
33use object_store::aws::AmazonS3Builder;
34use object_store::path::Path as ObjPath;
35use object_store::{
36 Attribute, AttributeValue, Attributes, ClientOptions, ObjectStore, PutMultipartOpts,
37 PutOptions, PutPayload, RetryConfig,
38};
39
40use crate::error::{Error, Result};
41use crate::ltx::{self, FileInfo};
42use crate::replica_url::{
43 self, bool_query_value, ensure_endpoint_scheme, region_from_s3_arn, ParsedReplicaUrl,
44};
45use crate::TXID;
46
47use super::ReplicaClient;
48
49/// The standard Litestream S3 metadata key for an LTX header timestamp.
50const 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.
64pub 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.
75const 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)]
89pub 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
97impl 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).
108pub const MAX_KEYS: usize = 1000;
109
110/// Region used when none is specified. `DefaultRegion` (s3/replica_client.go:59).
111pub 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).
116pub 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)]
126pub 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
155impl 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 pub fn build_store(&self) -> Result<Arc<dyn ObjectStore>> {
281 if self.bucket.is_empty() {
282 return Err(Error::Other("s3: bucket name is required".into()));
283 }
284
285 let region = if self.region.is_empty() {
286 DEFAULT_REGION.to_string()
287 } else {
288 self.region.clone()
289 };
290
291 let mut builder = AmazonS3Builder::new()
292 .with_bucket_name(&self.bucket)
293 .with_region(region)
294 .with_retry(replica_retry_config())
295 // Path-style ⇔ NOT virtual-hosted-style (s3/replica_client.go:258-263).
296 .with_virtual_hosted_style_request(!self.force_path_style)
297 // object_store disables S3 conditional puts by default. Keep the
298 // established ETagMatch behavior, so a user of the returned store
299 // can send PutMode::Create or PutMode::Update. Ordinary replica
300 // PUTs remain unconditional.
301 .with_conditional_put(object_store::aws::S3ConditionalPut::ETagMatch);
302
303 if !self.endpoint.is_empty() {
304 // A plaintext or local endpoint must allow HTTP. skip_verify applies
305 // only to TLS certificate validation.
306 let allow_http = self.endpoint.starts_with("http://")
307 || replica_url::is_local_endpoint(&self.endpoint);
308 let client_options = ClientOptions::new()
309 .with_allow_http(allow_http)
310 .with_allow_invalid_certificates(self.skip_verify);
311 builder = builder
312 .with_endpoint(&self.endpoint)
313 .with_client_options(client_options);
314 }
315
316 if !self.access_key_id.is_empty() {
317 builder = builder.with_access_key_id(&self.access_key_id);
318 }
319 if !self.secret_access_key.is_empty() {
320 builder = builder.with_secret_access_key(&self.secret_access_key);
321 }
322 if !self.session_token.is_empty() {
323 builder = builder.with_token(&self.session_token);
324 }
325
326 let store = builder
327 .build()
328 .map_err(|e| Error::Other(format!("s3: build store: {e}").into()))?;
329 Ok(Arc::new(store))
330 }
331
332 /// Effective multipart part size (`part_size`, or the 5 MiB default).
333 fn effective_part_size(&self) -> usize {
334 if self.part_size > 0 {
335 self.part_size as usize
336 } else {
337 MULTIPART_THRESHOLD
338 }
339 }
340}
341
342/// Returns `Some(value)` for a non-empty env var, else `None`. Mirrors Go's
343/// `if v := os.Getenv(k); v != ""` pattern (s3/replica_client.go:211-224).
344fn nonempty_env(key: &str) -> Option<String> {
345 match std::env::var(key) {
346 Ok(v) if !v.is_empty() => Some(v),
347 _ => None,
348 }
349}
350
351// ── ParseHost ─────────────────────────────────────────────────────────────────
352
353/// Parse an S3 host into `(bucket, region, endpoint, force_path_style)`.
354///
355/// Direct port of `ParseHost` (s3/replica_client.go:1608-1652): MinIO-style
356/// `bucket.host:port`, then the AWS / DigitalOcean / Backblaze / Filebase /
357/// Scaleway provider patterns, falling back to "host *is* the bucket".
358pub fn parse_host(host: &str) -> (String, String, String, bool) {
359 // MinIO-style hosts: `bucket.host:port` (a colon and not a ".com").
360 if host.contains(':') && !host.contains(".com") {
361 // SplitN(host, ".", 2)
362 if let Some((bucket, rest)) = host.split_once('.') {
363 return (
364 bucket.to_string(),
365 DEFAULT_REGION.to_string(),
366 format!("http://{rest}"),
367 true,
368 );
369 }
370 // No bucket in host, just host:port.
371 return (String::new(), String::new(), format!("http://{host}"), true);
372 }
373
374 // AWS S3: `^(.+)\.s3(?:\.([^.]+))?\.amazonaws\.com$`
375 if let Some((bucket, region)) = match_aws_s3(host) {
376 return (bucket, region, String::new(), false);
377 }
378 // DigitalOcean: `^(?:(.+)\.)?([^.]+)\.digitaloceanspaces.com$`
379 if let Some((bucket, region)) = match_two_label_suffix(host, ".digitaloceanspaces.com") {
380 return (
381 bucket,
382 region.clone(),
383 format!("https://{region}.digitaloceanspaces.com"),
384 false,
385 );
386 }
387 // Backblaze: `^(?:(.+)\.)?s3.([^.]+)\.backblazeb2.com$`
388 if let Some((bucket, region)) = match_s3_region_suffix(host, ".backblazeb2.com") {
389 return (
390 bucket,
391 region.clone(),
392 format!("https://s3.{region}.backblazeb2.com"),
393 true,
394 );
395 }
396 // Filebase: `^(?:(.+)\.)?s3.filebase.com$`
397 if let Some(bucket) = match_filebase(host) {
398 return (bucket, String::new(), "s3.filebase.com".to_string(), false);
399 }
400 // Scaleway: `^(?:(.+)\.)?s3.([^.]+)\.scw\.cloud$`
401 if let Some((bucket, region)) = match_s3_region_suffix(host, ".scw.cloud") {
402 return (
403 bucket,
404 region.clone(),
405 format!("s3.{region}.scw.cloud"),
406 false,
407 );
408 }
409
410 // Standard S3: the host is the bucket name.
411 (host.to_string(), String::new(), String::new(), false)
412}
413
414/// `^(.+)\.s3(?:\.([^.]+))?\.amazonaws\.com$` → (bucket, region).
415fn match_aws_s3(host: &str) -> Option<(String, String)> {
416 let rest = host.strip_suffix(".amazonaws.com")?;
417 // rest = "<bucket>.s3" or "<bucket>.s3.<region>"
418 if let Some(bucket) = rest.strip_suffix(".s3") {
419 if bucket.is_empty() {
420 return None;
421 }
422 return Some((bucket.to_string(), String::new()));
423 }
424 // "<bucket>.s3.<region>": find the ".s3." separator; region is a single
425 // label ([^.]+) — i.e. the remainder after ".s3." must contain no dot.
426 let idx = rest.find(".s3.")?;
427 let bucket = &rest[..idx];
428 let region = &rest[idx + 4..];
429 if bucket.is_empty() || region.is_empty() || region.contains('.') {
430 return None;
431 }
432 Some((bucket.to_string(), region.to_string()))
433}
434
435/// `^(?:(.+)\.)?([^.]+)\.<suffix>$` → (bucket, region). `suffix` starts with '.'.
436fn match_two_label_suffix(host: &str, suffix: &str) -> Option<(String, String)> {
437 let rest = host.strip_suffix(suffix)?;
438 if rest.is_empty() {
439 return None;
440 }
441 // The last label before the suffix is the region; anything before it
442 // (optionally) is the bucket.
443 match rest.rfind('.') {
444 Some(i) => {
445 let bucket = &rest[..i];
446 let region = &rest[i + 1..];
447 if region.is_empty() {
448 return None;
449 }
450 Some((bucket.to_string(), region.to_string()))
451 }
452 None => Some((String::new(), rest.to_string())),
453 }
454}
455
456/// `^(?:(.+)\.)?s3.([^.]+)\.<suffix>$` → (bucket, region). `suffix` starts with '.'.
457fn match_s3_region_suffix(host: &str, suffix: &str) -> Option<(String, String)> {
458 let rest = host.strip_suffix(suffix)?;
459 // rest = "[bucket.]s3.<region>"; region is one label ([^.]+).
460 // Bucket-less form: rest == "s3.<region>".
461 if let Some(region) = rest.strip_prefix("s3.") {
462 if region.is_empty() || region.contains('.') {
463 return None;
464 }
465 return Some((String::new(), region.to_string()));
466 }
467 // Bucketed form: rest == "<bucket>.s3.<region>".
468 let sep = rest.find(".s3.")?;
469 let bucket = &rest[..sep];
470 let region = &rest[sep + 4..];
471 if bucket.is_empty() || region.is_empty() || region.contains('.') {
472 return None;
473 }
474 Some((bucket.to_string(), region.to_string()))
475}
476
477/// `^(?:(.+)\.)?s3.filebase.com$` → bucket.
478fn match_filebase(host: &str) -> Option<String> {
479 if host == "s3.filebase.com" {
480 return Some(String::new());
481 }
482 let bucket = host.strip_suffix(".s3.filebase.com")?;
483 if bucket.is_empty() {
484 None
485 } else {
486 Some(bucket.to_string())
487 }
488}
489
490// ── Client ────────────────────────────────────────────────────────────────────
491
492/// Concrete S3/R2/MinIO backend, wrapping a lazily-initialised
493/// `Arc<dyn ObjectStore>`. The config-driven path builds an S3 store, but
494/// [`Self::with_store`] accepts any prebuilt `ObjectStore` — the five
495/// replica operations are provider-neutral, and a host can inject e.g. a
496/// GCS or in-memory store.
497///
498/// Mirrors Go `ReplicaClient` (s3/replica_client.go:78-116). The inner store is
499/// created on the first call that needs it (`OnceCell`, mirroring `Init`,
500/// s3/replica_client.go:322-477), so construction is infallible and race-free.
501pub struct ObjectStoreClient {
502 store: tokio::sync::OnceCell<Arc<dyn ObjectStore>>,
503 config: ObjectStoreConfig,
504}
505
506impl std::fmt::Debug for ObjectStoreClient {
507 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
508 f.debug_struct("ObjectStoreClient")
509 .field("config", &self.config)
510 .field("initialized", &self.store.initialized())
511 .finish()
512 }
513}
514
515impl ObjectStoreClient {
516 /// Create a client from config (no I/O; the store is built on first use).
517 pub fn new(config: ObjectStoreConfig) -> Self {
518 ObjectStoreClient {
519 store: tokio::sync::OnceCell::new(),
520 config,
521 }
522 }
523
524 /// Create a client directly from an already-built `ObjectStore` (e.g. an
525 /// in-memory store for tests, or a pre-configured backend).
526 pub fn with_store(config: ObjectStoreConfig, store: Arc<dyn ObjectStore>) -> Self {
527 let cell = tokio::sync::OnceCell::new();
528 cell.set(store).ok();
529 ObjectStoreClient {
530 store: cell,
531 config,
532 }
533 }
534
535 /// Get-or-build the inner store, once.
536 async fn store(&self) -> Result<&Arc<dyn ObjectStore>> {
537 self.store
538 .get_or_try_init(|| async { self.config.build_store() })
539 .await
540 }
541
542 /// Build the S3 key for an LTX file: `{path}/{level:04x}/{min}-{max}.ltx`.
543 /// Ported from s3/replica_client.go:629, 677, 1040-1042.
544 fn ltx_key(&self, level: i32, min_txid: TXID, max_txid: TXID) -> String {
545 let filename = ltx::format_filename(min_txid, max_txid);
546 format!("{}/{:04x}/{}", self.config.path, level, filename)
547 }
548
549 /// Prefix for listing a level: `{path}/{level:04x}/`.
550 /// Ported from s3/replica_client.go:1363.
551 fn level_prefix(&self, level: i32) -> String {
552 format!("{}/{:04x}/", self.config.path, level)
553 }
554
555 /// Root prefix for delete-all: `{path}/`. (s3/replica_client.go:1114).
556 fn root_prefix(&self) -> String {
557 format!("{}/", self.config.path)
558 }
559}
560
561/// Map an `object_store::Error` to `crate::Error`, preserving NotFound as
562/// `io::ErrorKind::NotFound` so callers keep working with the std error kind.
563/// Mirrors `isNotExists` → `os.ErrNotExist` (s3/replica_client.go:647-649,
564/// 1662-1668).
565fn map_os_error(e: object_store::Error) -> Error {
566 match e {
567 object_store::Error::NotFound { .. } => {
568 Error::Io(std::io::Error::new(std::io::ErrorKind::NotFound, e))
569 }
570 other => Error::Other(Box::new(other)),
571 }
572}
573
574#[async_trait::async_trait]
575impl ReplicaClient for ObjectStoreClient {
576 async fn ltx_files(&self, level: i32, seek: TXID) -> Result<Vec<FileInfo>> {
577 self.ltx_files_bounded(level, seek, usize::MAX).await
578 }
579
580 async fn ltx_files_bounded(
581 &self,
582 level: i32,
583 seek: TXID,
584 limit: usize,
585 ) -> Result<Vec<FileInfo>> {
586 if limit == 0 {
587 return Ok(Vec::new());
588 }
589 let store = self.store().await?;
590 let prefix = ObjPath::from(self.level_prefix(level));
591 // The offset ends immediately before every filename with this minimum
592 // TXID. S3 and GCS can push it into the listing request, so an additive
593 // compaction does not scan the complete retained L0 history. The
594 // supported production stores return each page in lexical order. The
595 // compactor validates continuity and fails closed for an unordered
596 // custom store.
597 let offset = ObjPath::from(format!("{}{:016x}", self.level_prefix(level), seek.0));
598 let mut listed = store.list_with_offset(Some(&prefix), &offset);
599 let mut infos = Vec::with_capacity(limit.min(256));
600 while let Some(meta) = listed.try_next().await.map_err(map_os_error)? {
601 let name = meta.location.filename().unwrap_or("");
602 let (min_txid, max_txid) = match ltx::parse_filename(name) {
603 Ok(t) => t,
604 Err(_) => continue, // skip non-LTX keys
605 };
606 if min_txid < seek {
607 continue;
608 }
609 infos.push(FileInfo {
610 level,
611 min_txid,
612 max_txid,
613 size: meta.size as i64,
614 created_at: Some(std::time::SystemTime::from(meta.last_modified)),
615 ..Default::default()
616 });
617 if infos.len() == limit {
618 break;
619 }
620 }
621
622 // Iterator contract: ascending by (level, min_txid, max_txid).
623 infos.sort_by(|a, b| {
624 (a.level, a.min_txid.0, a.max_txid.0).cmp(&(b.level, b.min_txid.0, b.max_txid.0))
625 });
626 Ok(infos)
627 }
628
629 async fn open_ltx_file(&self, level: i32, min_txid: TXID, max_txid: TXID) -> Result<Vec<u8>> {
630 let store = self.store().await?;
631 let key = ObjPath::from(self.ltx_key(level, min_txid, max_txid));
632
633 let result = match store.get(&key).await {
634 Ok(r) => r,
635 Err(object_store::Error::NotFound { .. }) => {
636 return Err(Error::Io(std::io::Error::new(
637 std::io::ErrorKind::NotFound,
638 format!("replica: get object {key}: not found"),
639 )));
640 }
641 Err(e) => return Err(map_os_error(e)),
642 };
643
644 let bytes = result.bytes().await.map_err(map_os_error)?;
645 Ok(bytes.to_vec())
646 }
647
648 async fn write_ltx_file(
649 &self,
650 level: i32,
651 min_txid: TXID,
652 max_txid: TXID,
653 data: &[u8],
654 ) -> Result<FileInfo> {
655 let store = self.store().await?;
656
657 // Preserve the LTX header timestamp in the standard Litestream object
658 // metadata. This costs no extra request and lets Litestream perform an
659 // accurate timestamp restore without downloading every candidate file.
660 // The name is per backend, because Azure refuses a hyphen in it.
661 let header = ltx::Header::parse(data)?;
662 let created_at = std::time::UNIX_EPOCH
663 + std::time::Duration::from_millis(header.timestamp.max(0) as u64);
664 let mut attributes = Attributes::new();
665 attributes.insert(
666 Attribute::Metadata(self.config.timestamp_metadata_key.as_str().into()),
667 AttributeValue::from(format_rfc3339_nano(header.timestamp)?),
668 );
669 let key = ObjPath::from(self.ltx_key(level, min_txid, max_txid));
670
671 // Multipart threshold: < 5 MiB → single PUT; ≥ 5 MiB → multipart with
672 // fixed-size parts. Ported from the Go uploader's 5 MiB PartSize default
673 // (s3/replica_client.go:99, brief §5.1).
674 let part_size = self.config.effective_part_size();
675 if data.len() < MULTIPART_THRESHOLD {
676 let payload = PutPayload::from(data.to_vec());
677 let options = PutOptions {
678 attributes,
679 ..Default::default()
680 };
681 store
682 .put_opts(&key, payload, options)
683 .await
684 .map_err(|e| Error::Other(format!("replica: upload to {key}: {e}").into()))?;
685 } else {
686 let options = PutMultipartOpts {
687 attributes,
688 ..Default::default()
689 };
690 let mut upload = store
691 .put_multipart_opts(&key, options)
692 .await
693 .map_err(|e| Error::Other(format!("replica: upload to {key}: {e}").into()))?;
694 // Upload in fixed-size parts (each ≥ 5 MiB except possibly the last,
695 // matching object_store's part-size requirement).
696 for chunk in data.chunks(part_size.max(MULTIPART_THRESHOLD)) {
697 upload
698 .put_part(PutPayload::from(chunk.to_vec()))
699 .await
700 .map_err(|e| {
701 Error::Other(format!("replica: upload part to {key}: {e}").into())
702 })?;
703 }
704 upload.complete().await.map_err(|e| {
705 Error::Other(format!("replica: complete upload to {key}: {e}").into())
706 })?;
707 }
708
709 Ok(FileInfo {
710 level,
711 min_txid,
712 max_txid,
713 size: data.len() as i64,
714 created_at: Some(created_at),
715 ..Default::default()
716 })
717 }
718
719 async fn delete_ltx_files(&self, files: &[FileInfo]) -> Result<()> {
720 if files.is_empty() {
721 return Ok(());
722 }
723 let store = self.store().await?;
724
725 // Build the key list, then delete in batches of MAX_KEYS via the
726 // store's delete_stream, surfacing per-key errors (brief §5.5).
727 let keys: Vec<ObjPath> = files
728 .iter()
729 .map(|info| ObjPath::from(self.ltx_key(info.level, info.min_txid, info.max_txid)))
730 .collect();
731
732 for batch in keys.chunks(MAX_KEYS) {
733 delete_batch(store.as_ref(), batch, /*ignore_missing=*/ true).await?;
734 }
735 Ok(())
736 }
737
738 async fn delete_all(&self) -> Result<()> {
739 let store = self.store().await?;
740 let prefix = ObjPath::from(self.root_prefix());
741
742 // List everything under the path prefix, then batch-delete.
743 // (s3/replica_client.go:1104-1148).
744 let keys: Vec<ObjPath> = store
745 .list(Some(&prefix))
746 .map_ok(|m| m.location)
747 .map_err(map_os_error)
748 .try_collect()
749 .await?;
750
751 for batch in keys.chunks(MAX_KEYS) {
752 delete_batch(store.as_ref(), batch, /*ignore_missing=*/ true).await?;
753 }
754 Ok(())
755 }
756}
757
758/// Delete a batch of keys via `delete_stream`, surfacing per-key errors.
759///
760/// When `ignore_missing` is set, `NotFound` is tolerated (delete is idempotent —
761/// the file client swallows ENOENT the same way), but every other per-key error
762/// is returned (brief §5.5: do not silently swallow partial failures).
763async fn delete_batch(
764 store: &dyn ObjectStore,
765 keys: &[ObjPath],
766 ignore_missing: bool,
767) -> Result<()> {
768 if keys.is_empty() {
769 return Ok(());
770 }
771 let owned: Vec<ObjPath> = keys.to_vec();
772 let stream = futures_util::stream::iter(owned.into_iter().map(Ok));
773 let mut results = store.delete_stream(stream.boxed());
774 while let Some(res) = results.next().await {
775 match res {
776 Ok(_) => {}
777 Err(object_store::Error::NotFound { .. }) if ignore_missing => {}
778 Err(e) => return Err(map_os_error(e)),
779 }
780 }
781 Ok(())
782}
783
784/// Format a Unix-millisecond timestamp like Go's `time.RFC3339Nano`.
785fn format_rfc3339_nano(unix_millis: i64) -> Result<String> {
786 let mut timestamp = DateTime::from_timestamp_millis(unix_millis.max(0))
787 .ok_or_else(|| Error::Other("LTX timestamp is outside the RFC3339 range".into()))?
788 .to_rfc3339_opts(SecondsFormat::AutoSi, true);
789
790 // Chrono keeps millisecond precision as three digits. Go removes trailing
791 // zeros, so `.500Z` becomes `.5Z`.
792 if timestamp.contains('.') {
793 // The pop must stay outside debug_assert!, which vanishes in release
794 // builds and would leave the Z in place to be doubled below.
795 let suffix = timestamp.pop();
796 debug_assert_eq!(suffix, Some('Z'));
797 while timestamp.ends_with('0') {
798 timestamp.pop();
799 }
800 timestamp.push('Z');
801 }
802 Ok(timestamp)
803}
804
805#[cfg(test)]
806mod tests {
807 use super::*;
808 use crate::replica_url::parse_replica_url_with_query;
809
810 #[test]
811 fn timestamp_metadata_matches_go_rfc3339_nano() {
812 assert_eq!(
813 format_rfc3339_nano(1_609_459_200_000).unwrap(),
814 "2021-01-01T00:00:00Z"
815 );
816 assert_eq!(
817 format_rfc3339_nano(1_609_459_200_500).unwrap(),
818 "2021-01-01T00:00:00.5Z"
819 );
820 assert_eq!(
821 format_rfc3339_nano(1_609_459_200_123).unwrap(),
822 "2021-01-01T00:00:00.123Z"
823 );
824 assert!(format_rfc3339_nano(i64::MAX).is_err());
825 }
826
827 /// Write one LTX object under `key` and answer the object's metadata.
828 async fn write_ltx_and_read_metadata(key: TimestampMetadataKey) -> Attributes {
829 let store = Arc::new(object_store::memory::InMemory::new());
830 let client = ObjectStoreClient::with_store(
831 ObjectStoreConfig {
832 bucket: "bucket".into(),
833 path: "replica".into(),
834 timestamp_metadata_key: key,
835 ..Default::default()
836 },
837 store.clone(),
838 );
839 let data = ltx::Header {
840 version: ltx::VERSION,
841 flags: ltx::HEADER_FLAG_NO_CHECKSUM,
842 page_size: 512,
843 commit: 1,
844 min_txid: TXID(1),
845 max_txid: TXID(1),
846 timestamp: 1_609_459_200_123,
847 pre_apply_checksum: 0,
848 wal_offset: 0,
849 wal_size: 0,
850 wal_salt1: 0,
851 wal_salt2: 0,
852 node_id: 0,
853 }
854 .marshal();
855
856 client
857 .write_ltx_file(0, TXID(1), TXID(1), &data)
858 .await
859 .expect("write LTX object");
860
861 let result = store
862 .get_opts(
863 &ObjPath::from("replica/0000/0000000000000001-0000000000000001.ltx"),
864 object_store::GetOptions {
865 head: true,
866 ..Default::default()
867 },
868 )
869 .await
870 .expect("read object metadata");
871 result.attributes
872 }
873
874 #[tokio::test]
875 async fn write_preserves_the_litestream_timestamp_metadata() {
876 let attributes = write_ltx_and_read_metadata(TimestampMetadataKey::Litestream).await;
877 let value = attributes
878 .get(&Attribute::Metadata(METADATA_KEY_TIMESTAMP.into()))
879 .expect("litestream timestamp metadata");
880 assert_eq!(value.as_ref(), "2021-01-01T00:00:00.123Z");
881 }
882
883 // Azure Blob Storage refuses a hyphen in a metadata name, so an az://
884 // replica writes the same value under an underscored key. The hyphen
885 // key must then be absent — a reader that finds both cannot tell which
886 // write produced the object.
887 #[tokio::test]
888 async fn an_underscored_key_replaces_the_hyphenated_one() {
889 let attributes = write_ltx_and_read_metadata(TimestampMetadataKey::Underscore).await;
890 let value = attributes
891 .get(&Attribute::Metadata(
892 METADATA_KEY_TIMESTAMP_UNDERSCORE.into(),
893 ))
894 .expect("underscored timestamp metadata");
895 assert_eq!(value.as_ref(), "2021-01-01T00:00:00.123Z");
896 assert!(
897 attributes
898 .get(&Attribute::Metadata(METADATA_KEY_TIMESTAMP.into()))
899 .is_none(),
900 "the hyphenated key must not also be written"
901 );
902 }
903
904 // ── ParseHost (port of TestParseHost, s3/replica_client_test.go:1071) ──────
905 #[test]
906 fn parse_host_table() {
907 let cases: &[(&str, &str, &str, &str, bool)] = &[
908 (
909 "my-space.sgp1.digitaloceanspaces.com",
910 "my-space",
911 "sgp1",
912 "https://sgp1.digitaloceanspaces.com",
913 false,
914 ),
915 (
916 "test-bucket.nyc3.digitaloceanspaces.com",
917 "test-bucket",
918 "nyc3",
919 "https://nyc3.digitaloceanspaces.com",
920 false,
921 ),
922 (
923 "mybucket.s3.us-east-1.amazonaws.com",
924 "mybucket",
925 "us-east-1",
926 "",
927 false,
928 ),
929 ("mybucket.s3.amazonaws.com", "mybucket", "", "", false),
930 (
931 "mybucket.s3.us-west-004.backblazeb2.com",
932 "mybucket",
933 "us-west-004",
934 "https://s3.us-west-004.backblazeb2.com",
935 true,
936 ),
937 (
938 "mybucket.localhost:9000",
939 "mybucket",
940 "us-east-1",
941 "http://localhost:9000",
942 true,
943 ),
944 ];
945 for (host, b, r, e, fps) in cases {
946 let (bucket, region, endpoint, force) = parse_host(host);
947 assert_eq!(&bucket, b, "bucket for {host}");
948 assert_eq!(&region, r, "region for {host}");
949 assert_eq!(&endpoint, e, "endpoint for {host}");
950 assert_eq!(force, *fps, "force_path_style for {host}");
951 }
952 }
953
954 #[test]
955 fn parse_host_standard_s3_is_bucket() {
956 let (bucket, region, endpoint, force) = parse_host("mybucket");
957 assert_eq!(bucket, "mybucket");
958 assert_eq!(region, "");
959 assert_eq!(endpoint, "");
960 assert!(!force);
961 }
962
963 fn cfg_from_url(url: &str) -> ObjectStoreConfig {
964 let parsed = parse_replica_url_with_query(url).unwrap();
965 ObjectStoreConfig::from_url(&parsed).unwrap()
966 }
967
968 // ── URL query param aliases (port of
969 // TestNewReplicaClientFromURL_QueryParamAliases, test:1940) ───────────────
970 #[test]
971 fn query_param_aliases() {
972 let c = cfg_from_url("s3://mybucket/path?forcePathStyle=true");
973 assert!(c.force_path_style);
974
975 let c = cfg_from_url("s3://mybucket/path?force-path-style=true");
976 assert!(c.force_path_style);
977
978 let c = cfg_from_url(
979 "s3://mybucket/path?endpoint=http://localhost:9000&force-path-style=false",
980 );
981 assert!(!c.force_path_style, "explicit force-path-style=false wins");
982
983 let c = cfg_from_url("s3://mybucket/path?skipVerify=true");
984 assert!(c.skip_verify);
985 let c = cfg_from_url("s3://mybucket/path?skip-verify=true");
986 assert!(c.skip_verify);
987
988 let c = cfg_from_url("s3://mybucket/path?part-size=10485760");
989 assert_eq!(c.part_size, 10_485_760);
990 let c = cfg_from_url("s3://mybucket/path?partSize=10485760");
991 assert_eq!(c.part_size, 10_485_760);
992
993 let c = cfg_from_url(
994 "s3://mybucket/path?force-path-style=true&skip-verify=true&part-size=8388608",
995 );
996 assert!(c.force_path_style);
997 assert!(c.skip_verify);
998 assert_eq!(c.part_size, 8_388_608);
999 }
1000
1001 // ── Endpoint env var (port of TestNewReplicaClientFromURL_EndpointEnvVar,
1002 // test:2023). These mutate a process-global env var, so they run
1003 // sequentially under one #[test] with save/restore to avoid cross-test
1004 // interference. ───────────────────────────────────────────────────────────
1005 #[test]
1006 fn endpoint_env_var() {
1007 let saved = std::env::var("LITESTREAM_S3_ENDPOINT").ok();
1008
1009 let set = |v: &str| {
1010 if v.is_empty() {
1011 std::env::remove_var("LITESTREAM_S3_ENDPOINT");
1012 } else {
1013 std::env::set_var("LITESTREAM_S3_ENDPOINT", v);
1014 }
1015 };
1016
1017 set("http://localhost:9000");
1018 let c = cfg_from_url("s3://mybucket/path");
1019 assert_eq!(c.endpoint, "http://localhost:9000");
1020 assert!(c.force_path_style, "env endpoint forces path-style");
1021
1022 set("s3.example.com");
1023 let c = cfg_from_url("s3://mybucket/path");
1024 assert_eq!(
1025 c.endpoint, "https://s3.example.com",
1026 "env endpoint gets https"
1027 );
1028 assert!(c.force_path_style);
1029
1030 set("http://localhost:9000");
1031 let c = cfg_from_url("s3://mybucket/path?endpoint=http://other:9000");
1032 assert_eq!(
1033 c.endpoint, "http://other:9000",
1034 "query endpoint overrides env"
1035 );
1036 assert!(c.force_path_style);
1037
1038 set("http://localhost:9000");
1039 let c = cfg_from_url("s3://mybucket/path?force-path-style=false");
1040 assert_eq!(c.endpoint, "http://localhost:9000");
1041 assert!(
1042 !c.force_path_style,
1043 "explicit force-path-style=false respected with env endpoint"
1044 );
1045
1046 set("");
1047 let c = cfg_from_url("s3://mybucket/path");
1048 assert_eq!(c.endpoint, "");
1049 assert!(!c.force_path_style);
1050
1051 // Restore.
1052 match saved {
1053 Some(v) => std::env::set_var("LITESTREAM_S3_ENDPOINT", v),
1054 None => std::env::remove_var("LITESTREAM_S3_ENDPOINT"),
1055 }
1056 }
1057
1058 // ── Key construction (wire-compat requirement D-1, test:629/677/1040) ─────
1059 #[test]
1060 fn ltx_key_scheme() {
1061 let client = ObjectStoreClient::new(ObjectStoreConfig {
1062 bucket: "b".into(),
1063 path: "replica".into(),
1064 ..Default::default()
1065 });
1066 assert_eq!(
1067 client.ltx_key(0, TXID(1), TXID(1)),
1068 "replica/0000/0000000000000001-0000000000000001.ltx"
1069 );
1070 assert_eq!(
1071 client.ltx_key(0, TXID(1), TXID(6)),
1072 "replica/0000/0000000000000001-0000000000000006.ltx"
1073 );
1074 assert_eq!(client.level_prefix(0), "replica/0000/");
1075 assert_eq!(client.root_prefix(), "replica/");
1076 }
1077
1078 // ── isNotExists mapping (port of TestIsNotExists, test:53) ────────────────
1079 #[test]
1080 fn not_found_maps_to_io_not_found() {
1081 let e = map_os_error(object_store::Error::NotFound {
1082 path: "k".into(),
1083 source: "missing".into(),
1084 });
1085 match e {
1086 Error::Io(io) => assert_eq!(io.kind(), std::io::ErrorKind::NotFound),
1087 other => panic!("expected Io(NotFound), got {other:?}"),
1088 }
1089 }
1090}