Diffinery

homeflare/celldpublic

celld/crates/ltx/src/client/object_store.rs
1001 lines · 37.3 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,
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/// Max keys S3 operates on per batch DELETE. `MaxKeys` (s3/replica_client.go:56).
53pub const MAX_KEYS: usize = 1000;
54
55/// Region used when none is specified. `DefaultRegion` (s3/replica_client.go:59).
56pub const DEFAULT_REGION: &str = "us-east-1";
57
58/// Multipart upload threshold: data at or above this size is uploaded with
59/// `put_multipart`; below it, a single `put`. Matches the Go uploader's 5 MiB
60/// `PartSize` default (s3/replica_client.go:99).
61pub const MULTIPART_THRESHOLD: usize = 5 * 1024 * 1024;
62
63// ── Config ────────────────────────────────────────────────────────────────────
64
65/// Configuration for the S3/R2/MinIO backend.
66///
67/// Maps to the public fields of Go's `ReplicaClient` struct
68/// (s3/replica_client.go:78-116). Zero/`None` values mean "use the backend
69/// default".
70#[derive(Debug, Clone, Default)]
71pub struct ObjectStoreConfig {
72 /// Bucket name (required).
73 pub bucket: String,
74 /// Key prefix within the bucket.
75 pub path: String,
76 /// AWS region.
77 pub region: String,
78 /// Custom endpoint (MinIO, R2, …); empty = native AWS.
79 pub endpoint: String,
80 /// Static access key id; empty = ambient credential chain.
81 pub access_key_id: String,
82 /// Static secret access key; empty = ambient credential chain.
83 pub secret_access_key: String,
84 /// Session token for temporary/scoped credentials (STS, R2 API tokens);
85 /// empty = none. Required alongside temporary keys or signing fails.
86 pub session_token: String,
87 /// Force path-style addressing (required for MinIO/Backblaze/Supabase/Filebase).
88 pub force_path_style: bool,
89 /// Skip TLS verification (allows self-signed endpoints).
90 pub skip_verify: bool,
91 /// Multipart part size in bytes; 0 = default (5 MiB).
92 pub part_size: u64,
93}
94
95impl ObjectStoreConfig {
96 /// Construct from a parsed `s3://` URL, mirroring `NewReplicaClientFromURL`
97 /// (s3/replica_client.go:133-314): host → bucket/region/endpoint/path-style
98 /// (or ARN), query-param overrides (camelCase ↔ hyphenated aliases), the
99 /// `AWS_*`/`LITESTREAM_*` env credentials, the `LITESTREAM_S3_ENDPOINT` env
100 /// fallback, and the provider-specific path-style defaults for
101 /// MinIO/Backblaze/Filebase/Supabase.
102 pub fn from_url(parsed: &ParsedReplicaUrl) -> Result<Self> {
103 let host = &parsed.host;
104 let query = &parsed.query;
105
106 // Host → bucket/region/endpoint/forcePathStyle (or ARN access point).
107 let (bucket, mut region, mut endpoint, mut force_path_style) = if host.starts_with("arn:") {
108 (host.clone(), region_from_s3_arn(host), String::new(), false)
109 } else {
110 parse_host(host)
111 };
112
113 let q = Some(query);
114
115 // endpoint query param: ensure scheme, default to path-style for custom
116 // endpoints unless force-path-style is explicitly set to false.
117 let q_endpoint = query.get("endpoint");
118 if !q_endpoint.is_empty() {
119 let (ep, _) = ensure_endpoint_scheme(q_endpoint);
120 endpoint = ep;
121 match bool_query_value(q, &["forcePathStyle", "force-path-style"]) {
122 Some(false) => {}
123 _ => force_path_style = true,
124 }
125 }
126 let q_region = query.get("region");
127 if !q_region.is_empty() {
128 region = q_region.to_string();
129 }
130 if let Some(v) = bool_query_value(q, &["forcePathStyle", "force-path-style"]) {
131 force_path_style = v;
132 }
133 let mut skip_verify = false;
134 if let Some(v) = bool_query_value(q, &["skipVerify", "skip-verify"]) {
135 skip_verify = v;
136 }
137
138 let mut part_size: u64 = 0;
139 let v = query.get("partSize");
140 let v2 = query.get("part-size");
141 if !v.is_empty() {
142 if let Ok(n) = v.parse::<u64>() {
143 if n > 0 {
144 part_size = n;
145 }
146 }
147 } else if !v2.is_empty() {
148 if let Ok(n) = v2.parse::<u64>() {
149 if n > 0 {
150 part_size = n;
151 }
152 }
153 }
154
155 if bucket.is_empty() {
156 return Err(Error::Other("bucket required for s3 replica URL".into()));
157 }
158
159 // Track whether forcePathStyle was explicitly set via query param
160 // (s3/replica_client.go:208) — this gates the env-var/provider defaults.
161 let force_path_style_set =
162 !query.get("forcePathStyle").is_empty() || !query.get("force-path-style").is_empty();
163
164 // Static credentials from env (AWS_* preferred, then LITESTREAM_*).
165 let mut access_key_id = String::new();
166 let mut secret_access_key = String::new();
167 if let Some(v) = nonempty_env("AWS_ACCESS_KEY_ID") {
168 access_key_id = v;
169 } else if let Some(v) = nonempty_env("LITESTREAM_ACCESS_KEY_ID") {
170 access_key_id = v;
171 }
172 if let Some(v) = nonempty_env("AWS_SECRET_ACCESS_KEY") {
173 secret_access_key = v;
174 } else if let Some(v) = nonempty_env("LITESTREAM_SECRET_ACCESS_KEY") {
175 secret_access_key = v;
176 }
177 let session_token = nonempty_env("AWS_SESSION_TOKEN")
178 .or_else(|| nonempty_env("LITESTREAM_SESSION_TOKEN"))
179 .unwrap_or_default();
180
181 // LITESTREAM_S3_ENDPOINT env fallback (only when no endpoint yet).
182 if endpoint.is_empty() {
183 if let Some(v) = nonempty_env("LITESTREAM_S3_ENDPOINT") {
184 let (ep, _) = ensure_endpoint_scheme(&v);
185 endpoint = ep;
186 if !force_path_style_set {
187 force_path_style = true;
188 }
189 }
190 }
191
192 // Provider detection for applying defaults.
193 let is_filebase = replica_url::is_filebase_endpoint(&endpoint);
194 let is_backblaze = replica_url::is_backblaze_endpoint(&endpoint);
195 let is_minio = replica_url::is_minio_endpoint(&endpoint);
196 let is_supabase = replica_url::is_supabase_endpoint(&endpoint);
197 if !force_path_style_set && (is_filebase || is_backblaze || is_minio || is_supabase) {
198 force_path_style = true;
199 }
200
201 Ok(ObjectStoreConfig {
202 bucket,
203 path: parsed.path.clone(),
204 region,
205 endpoint,
206 access_key_id,
207 secret_access_key,
208 session_token,
209 force_path_style,
210 skip_verify,
211 part_size,
212 })
213 }
214
215 /// Build the backing `Arc<dyn ObjectStore>` for this config. Public so a host
216 /// can build one store for a bucket and share it across many
217 /// [`ObjectStoreClient::with_store`] clients that differ only by key prefix
218 /// — one connection pool for every cell on a node.
219 pub fn build_store(&self) -> Result<Arc<dyn ObjectStore>> {
220 if self.bucket.is_empty() {
221 return Err(Error::Other("s3: bucket name is required".into()));
222 }
223
224 let region = if self.region.is_empty() {
225 DEFAULT_REGION.to_string()
226 } else {
227 self.region.clone()
228 };
229
230 let mut builder = AmazonS3Builder::new()
231 .with_bucket_name(&self.bucket)
232 .with_region(region)
233 // Path-style ⇔ NOT virtual-hosted-style (s3/replica_client.go:258-263).
234 .with_virtual_hosted_style_request(!self.force_path_style)
235 // object_store ships with conditional puts DISABLED for S3 and
236 // answers PutMode::Create with NotImplemented. The epoch seal is a
237 // conditional create (first restorer wins), and every provider on
238 // the support matrix speaks the If-None-Match/If-Match headers
239 // this enables.
240 .with_conditional_put(object_store::aws::S3ConditionalPut::ETagMatch);
241
242 if !self.endpoint.is_empty() {
243 // A plaintext or local endpoint must allow HTTP. skip_verify applies
244 // only to TLS certificate validation.
245 let allow_http = self.endpoint.starts_with("http://")
246 || replica_url::is_local_endpoint(&self.endpoint);
247 let client_options = ClientOptions::new()
248 .with_allow_http(allow_http)
249 .with_allow_invalid_certificates(self.skip_verify);
250 builder = builder
251 .with_endpoint(&self.endpoint)
252 .with_client_options(client_options);
253 }
254
255 if !self.access_key_id.is_empty() {
256 builder = builder.with_access_key_id(&self.access_key_id);
257 }
258 if !self.secret_access_key.is_empty() {
259 builder = builder.with_secret_access_key(&self.secret_access_key);
260 }
261 if !self.session_token.is_empty() {
262 builder = builder.with_token(&self.session_token);
263 }
264
265 let store = builder
266 .build()
267 .map_err(|e| Error::Other(format!("s3: build store: {e}").into()))?;
268 Ok(Arc::new(store))
269 }
270
271 /// Effective multipart part size (`part_size`, or the 5 MiB default).
272 fn effective_part_size(&self) -> usize {
273 if self.part_size > 0 {
274 self.part_size as usize
275 } else {
276 MULTIPART_THRESHOLD
277 }
278 }
279}
280
281/// Returns `Some(value)` for a non-empty env var, else `None`. Mirrors Go's
282/// `if v := os.Getenv(k); v != ""` pattern (s3/replica_client.go:211-224).
283fn nonempty_env(key: &str) -> Option<String> {
284 match std::env::var(key) {
285 Ok(v) if !v.is_empty() => Some(v),
286 _ => None,
287 }
288}
289
290// ── ParseHost ─────────────────────────────────────────────────────────────────
291
292/// Parse an S3 host into `(bucket, region, endpoint, force_path_style)`.
293///
294/// Direct port of `ParseHost` (s3/replica_client.go:1608-1652): MinIO-style
295/// `bucket.host:port`, then the AWS / DigitalOcean / Backblaze / Filebase /
296/// Scaleway provider patterns, falling back to "host *is* the bucket".
297pub fn parse_host(host: &str) -> (String, String, String, bool) {
298 // MinIO-style hosts: `bucket.host:port` (a colon and not a ".com").
299 if host.contains(':') && !host.contains(".com") {
300 // SplitN(host, ".", 2)
301 if let Some((bucket, rest)) = host.split_once('.') {
302 return (
303 bucket.to_string(),
304 DEFAULT_REGION.to_string(),
305 format!("http://{rest}"),
306 true,
307 );
308 }
309 // No bucket in host, just host:port.
310 return (String::new(), String::new(), format!("http://{host}"), true);
311 }
312
313 // AWS S3: `^(.+)\.s3(?:\.([^.]+))?\.amazonaws\.com$`
314 if let Some((bucket, region)) = match_aws_s3(host) {
315 return (bucket, region, String::new(), false);
316 }
317 // DigitalOcean: `^(?:(.+)\.)?([^.]+)\.digitaloceanspaces.com$`
318 if let Some((bucket, region)) = match_two_label_suffix(host, ".digitaloceanspaces.com") {
319 return (
320 bucket,
321 region.clone(),
322 format!("https://{region}.digitaloceanspaces.com"),
323 false,
324 );
325 }
326 // Backblaze: `^(?:(.+)\.)?s3.([^.]+)\.backblazeb2.com$`
327 if let Some((bucket, region)) = match_s3_region_suffix(host, ".backblazeb2.com") {
328 return (
329 bucket,
330 region.clone(),
331 format!("https://s3.{region}.backblazeb2.com"),
332 true,
333 );
334 }
335 // Filebase: `^(?:(.+)\.)?s3.filebase.com$`
336 if let Some(bucket) = match_filebase(host) {
337 return (bucket, String::new(), "s3.filebase.com".to_string(), false);
338 }
339 // Scaleway: `^(?:(.+)\.)?s3.([^.]+)\.scw\.cloud$`
340 if let Some((bucket, region)) = match_s3_region_suffix(host, ".scw.cloud") {
341 return (
342 bucket,
343 region.clone(),
344 format!("s3.{region}.scw.cloud"),
345 false,
346 );
347 }
348
349 // Standard S3: the host is the bucket name.
350 (host.to_string(), String::new(), String::new(), false)
351}
352
353/// `^(.+)\.s3(?:\.([^.]+))?\.amazonaws\.com$` → (bucket, region).
354fn match_aws_s3(host: &str) -> Option<(String, String)> {
355 let rest = host.strip_suffix(".amazonaws.com")?;
356 // rest = "<bucket>.s3" or "<bucket>.s3.<region>"
357 if let Some(bucket) = rest.strip_suffix(".s3") {
358 if bucket.is_empty() {
359 return None;
360 }
361 return Some((bucket.to_string(), String::new()));
362 }
363 // "<bucket>.s3.<region>": find the ".s3." separator; region is a single
364 // label ([^.]+) — i.e. the remainder after ".s3." must contain no dot.
365 let idx = rest.find(".s3.")?;
366 let bucket = &rest[..idx];
367 let region = &rest[idx + 4..];
368 if bucket.is_empty() || region.is_empty() || region.contains('.') {
369 return None;
370 }
371 Some((bucket.to_string(), region.to_string()))
372}
373
374/// `^(?:(.+)\.)?([^.]+)\.<suffix>$` → (bucket, region). `suffix` starts with '.'.
375fn match_two_label_suffix(host: &str, suffix: &str) -> Option<(String, String)> {
376 let rest = host.strip_suffix(suffix)?;
377 if rest.is_empty() {
378 return None;
379 }
380 // The last label before the suffix is the region; anything before it
381 // (optionally) is the bucket.
382 match rest.rfind('.') {
383 Some(i) => {
384 let bucket = &rest[..i];
385 let region = &rest[i + 1..];
386 if region.is_empty() {
387 return None;
388 }
389 Some((bucket.to_string(), region.to_string()))
390 }
391 None => Some((String::new(), rest.to_string())),
392 }
393}
394
395/// `^(?:(.+)\.)?s3.([^.]+)\.<suffix>$` → (bucket, region). `suffix` starts with '.'.
396fn match_s3_region_suffix(host: &str, suffix: &str) -> Option<(String, String)> {
397 let rest = host.strip_suffix(suffix)?;
398 // rest = "[bucket.]s3.<region>"; region is one label ([^.]+).
399 // Bucket-less form: rest == "s3.<region>".
400 if let Some(region) = rest.strip_prefix("s3.") {
401 if region.is_empty() || region.contains('.') {
402 return None;
403 }
404 return Some((String::new(), region.to_string()));
405 }
406 // Bucketed form: rest == "<bucket>.s3.<region>".
407 let sep = rest.find(".s3.")?;
408 let bucket = &rest[..sep];
409 let region = &rest[sep + 4..];
410 if bucket.is_empty() || region.is_empty() || region.contains('.') {
411 return None;
412 }
413 Some((bucket.to_string(), region.to_string()))
414}
415
416/// `^(?:(.+)\.)?s3.filebase.com$` → bucket.
417fn match_filebase(host: &str) -> Option<String> {
418 if host == "s3.filebase.com" {
419 return Some(String::new());
420 }
421 let bucket = host.strip_suffix(".s3.filebase.com")?;
422 if bucket.is_empty() {
423 None
424 } else {
425 Some(bucket.to_string())
426 }
427}
428
429// ── Client ────────────────────────────────────────────────────────────────────
430
431/// Concrete S3/R2/MinIO backend, wrapping a lazily-initialised
432/// `Arc<dyn ObjectStore>`. The config-driven path builds an S3 store, but
433/// [`Self::with_store`] accepts any prebuilt `ObjectStore` — the five
434/// replica operations are provider-neutral, and a host can inject e.g. a
435/// GCS or in-memory store.
436///
437/// Mirrors Go `ReplicaClient` (s3/replica_client.go:78-116). The inner store is
438/// created on the first call that needs it (`OnceCell`, mirroring `Init`,
439/// s3/replica_client.go:322-477), so construction is infallible and race-free.
440pub struct ObjectStoreClient {
441 store: tokio::sync::OnceCell<Arc<dyn ObjectStore>>,
442 config: ObjectStoreConfig,
443}
444
445impl std::fmt::Debug for ObjectStoreClient {
446 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
447 f.debug_struct("ObjectStoreClient")
448 .field("config", &self.config)
449 .field("initialized", &self.store.initialized())
450 .finish()
451 }
452}
453
454impl ObjectStoreClient {
455 /// Create a client from config (no I/O; the store is built on first use).
456 pub fn new(config: ObjectStoreConfig) -> Self {
457 ObjectStoreClient {
458 store: tokio::sync::OnceCell::new(),
459 config,
460 }
461 }
462
463 /// Create a client directly from an already-built `ObjectStore` (e.g. an
464 /// in-memory store for tests, or a pre-configured backend).
465 pub fn with_store(config: ObjectStoreConfig, store: Arc<dyn ObjectStore>) -> Self {
466 let cell = tokio::sync::OnceCell::new();
467 cell.set(store).ok();
468 ObjectStoreClient {
469 store: cell,
470 config,
471 }
472 }
473
474 /// Get-or-build the inner store, once.
475 async fn store(&self) -> Result<&Arc<dyn ObjectStore>> {
476 self.store
477 .get_or_try_init(|| async { self.config.build_store() })
478 .await
479 }
480
481 /// Build the S3 key for an LTX file: `{path}/{level:04x}/{min}-{max}.ltx`.
482 /// Ported from s3/replica_client.go:629, 677, 1040-1042.
483 fn ltx_key(&self, level: i32, min_txid: TXID, max_txid: TXID) -> String {
484 let filename = ltx::format_filename(min_txid, max_txid);
485 format!("{}/{:04x}/{}", self.config.path, level, filename)
486 }
487
488 /// Prefix for listing a level: `{path}/{level:04x}/`.
489 /// Ported from s3/replica_client.go:1363.
490 fn level_prefix(&self, level: i32) -> String {
491 format!("{}/{:04x}/", self.config.path, level)
492 }
493
494 /// Root prefix for delete-all: `{path}/`. (s3/replica_client.go:1114).
495 fn root_prefix(&self) -> String {
496 format!("{}/", self.config.path)
497 }
498}
499
500/// Map an `object_store::Error` to `crate::Error`, preserving NotFound as
501/// `io::ErrorKind::NotFound` so callers keep working with the std error kind.
502/// Mirrors `isNotExists` → `os.ErrNotExist` (s3/replica_client.go:647-649,
503/// 1662-1668).
504fn map_os_error(e: object_store::Error) -> Error {
505 match e {
506 object_store::Error::NotFound { .. } => {
507 Error::Io(std::io::Error::new(std::io::ErrorKind::NotFound, e))
508 }
509 other => Error::Other(Box::new(other)),
510 }
511}
512
513#[async_trait::async_trait]
514impl ReplicaClient for ObjectStoreClient {
515 async fn ltx_files(&self, level: i32, seek: TXID) -> Result<Vec<FileInfo>> {
516 self.ltx_files_bounded(level, seek, usize::MAX).await
517 }
518
519 async fn ltx_files_bounded(
520 &self,
521 level: i32,
522 seek: TXID,
523 limit: usize,
524 ) -> Result<Vec<FileInfo>> {
525 if limit == 0 {
526 return Ok(Vec::new());
527 }
528 let store = self.store().await?;
529 let prefix = ObjPath::from(self.level_prefix(level));
530 // The offset ends immediately before every filename with this minimum
531 // TXID. S3 and GCS can push it into the listing request, so an additive
532 // compaction does not scan the complete retained L0 history. The
533 // supported production stores return each page in lexical order. The
534 // compactor validates continuity and fails closed for an unordered
535 // custom store.
536 let offset = ObjPath::from(format!("{}{:016x}", self.level_prefix(level), seek.0));
537 let mut listed = store.list_with_offset(Some(&prefix), &offset);
538 let mut infos = Vec::with_capacity(limit.min(256));
539 while let Some(meta) = listed.try_next().await.map_err(map_os_error)? {
540 let name = meta.location.filename().unwrap_or("");
541 let (min_txid, max_txid) = match ltx::parse_filename(name) {
542 Ok(t) => t,
543 Err(_) => continue, // skip non-LTX keys
544 };
545 if min_txid < seek {
546 continue;
547 }
548 infos.push(FileInfo {
549 level,
550 min_txid,
551 max_txid,
552 size: meta.size as i64,
553 created_at: Some(std::time::SystemTime::from(meta.last_modified)),
554 ..Default::default()
555 });
556 if infos.len() == limit {
557 break;
558 }
559 }
560
561 // Iterator contract: ascending by (level, min_txid, max_txid).
562 infos.sort_by(|a, b| {
563 (a.level, a.min_txid.0, a.max_txid.0).cmp(&(b.level, b.min_txid.0, b.max_txid.0))
564 });
565 Ok(infos)
566 }
567
568 async fn open_ltx_file(&self, level: i32, min_txid: TXID, max_txid: TXID) -> Result<Vec<u8>> {
569 let store = self.store().await?;
570 let key = ObjPath::from(self.ltx_key(level, min_txid, max_txid));
571
572 let result = match store.get(&key).await {
573 Ok(r) => r,
574 Err(object_store::Error::NotFound { .. }) => {
575 return Err(Error::Io(std::io::Error::new(
576 std::io::ErrorKind::NotFound,
577 format!("replica: get object {key}: not found"),
578 )));
579 }
580 Err(e) => return Err(map_os_error(e)),
581 };
582
583 let bytes = result.bytes().await.map_err(map_os_error)?;
584 Ok(bytes.to_vec())
585 }
586
587 async fn write_ltx_file(
588 &self,
589 level: i32,
590 min_txid: TXID,
591 max_txid: TXID,
592 data: &[u8],
593 ) -> Result<FileInfo> {
594 let store = self.store().await?;
595
596 // Preserve the LTX header timestamp in the standard Litestream object
597 // metadata. This costs no extra request and lets Litestream perform an
598 // accurate timestamp restore without downloading every candidate file.
599 let header = ltx::Header::parse(data)?;
600 let created_at = std::time::UNIX_EPOCH
601 + std::time::Duration::from_millis(header.timestamp.max(0) as u64);
602 let mut attributes = Attributes::new();
603 attributes.insert(
604 Attribute::Metadata(METADATA_KEY_TIMESTAMP.into()),
605 AttributeValue::from(format_rfc3339_nano(header.timestamp)?),
606 );
607 let key = ObjPath::from(self.ltx_key(level, min_txid, max_txid));
608
609 // Multipart threshold: < 5 MiB → single PUT; ≥ 5 MiB → multipart with
610 // fixed-size parts. Ported from the Go uploader's 5 MiB PartSize default
611 // (s3/replica_client.go:99, brief §5.1).
612 let part_size = self.config.effective_part_size();
613 if data.len() < MULTIPART_THRESHOLD {
614 let payload = PutPayload::from(data.to_vec());
615 let options = PutOptions {
616 attributes,
617 ..Default::default()
618 };
619 store
620 .put_opts(&key, payload, options)
621 .await
622 .map_err(|e| Error::Other(format!("replica: upload to {key}: {e}").into()))?;
623 } else {
624 let options = PutMultipartOpts {
625 attributes,
626 ..Default::default()
627 };
628 let mut upload = store
629 .put_multipart_opts(&key, options)
630 .await
631 .map_err(|e| Error::Other(format!("replica: upload to {key}: {e}").into()))?;
632 // Upload in fixed-size parts (each ≥ 5 MiB except possibly the last,
633 // matching object_store's part-size requirement).
634 for chunk in data.chunks(part_size.max(MULTIPART_THRESHOLD)) {
635 upload
636 .put_part(PutPayload::from(chunk.to_vec()))
637 .await
638 .map_err(|e| {
639 Error::Other(format!("replica: upload part to {key}: {e}").into())
640 })?;
641 }
642 upload.complete().await.map_err(|e| {
643 Error::Other(format!("replica: complete upload to {key}: {e}").into())
644 })?;
645 }
646
647 Ok(FileInfo {
648 level,
649 min_txid,
650 max_txid,
651 size: data.len() as i64,
652 created_at: Some(created_at),
653 ..Default::default()
654 })
655 }
656
657 async fn delete_ltx_files(&self, files: &[FileInfo]) -> Result<()> {
658 if files.is_empty() {
659 return Ok(());
660 }
661 let store = self.store().await?;
662
663 // Build the key list, then delete in batches of MAX_KEYS via the
664 // store's delete_stream, surfacing per-key errors (brief §5.5).
665 let keys: Vec<ObjPath> = files
666 .iter()
667 .map(|info| ObjPath::from(self.ltx_key(info.level, info.min_txid, info.max_txid)))
668 .collect();
669
670 for batch in keys.chunks(MAX_KEYS) {
671 delete_batch(store.as_ref(), batch, /*ignore_missing=*/ true).await?;
672 }
673 Ok(())
674 }
675
676 async fn delete_all(&self) -> Result<()> {
677 let store = self.store().await?;
678 let prefix = ObjPath::from(self.root_prefix());
679
680 // List everything under the path prefix, then batch-delete.
681 // (s3/replica_client.go:1104-1148).
682 let keys: Vec<ObjPath> = store
683 .list(Some(&prefix))
684 .map_ok(|m| m.location)
685 .map_err(map_os_error)
686 .try_collect()
687 .await?;
688
689 for batch in keys.chunks(MAX_KEYS) {
690 delete_batch(store.as_ref(), batch, /*ignore_missing=*/ true).await?;
691 }
692 Ok(())
693 }
694}
695
696/// Delete a batch of keys via `delete_stream`, surfacing per-key errors.
697///
698/// When `ignore_missing` is set, `NotFound` is tolerated (delete is idempotent —
699/// the file client swallows ENOENT the same way), but every other per-key error
700/// is returned (brief §5.5: do not silently swallow partial failures).
701async fn delete_batch(
702 store: &dyn ObjectStore,
703 keys: &[ObjPath],
704 ignore_missing: bool,
705) -> Result<()> {
706 if keys.is_empty() {
707 return Ok(());
708 }
709 let owned: Vec<ObjPath> = keys.to_vec();
710 let stream = futures_util::stream::iter(owned.into_iter().map(Ok));
711 let mut results = store.delete_stream(stream.boxed());
712 while let Some(res) = results.next().await {
713 match res {
714 Ok(_) => {}
715 Err(object_store::Error::NotFound { .. }) if ignore_missing => {}
716 Err(e) => return Err(map_os_error(e)),
717 }
718 }
719 Ok(())
720}
721
722/// Format a Unix-millisecond timestamp like Go's `time.RFC3339Nano`.
723fn format_rfc3339_nano(unix_millis: i64) -> Result<String> {
724 let mut timestamp = DateTime::from_timestamp_millis(unix_millis.max(0))
725 .ok_or_else(|| Error::Other("LTX timestamp is outside the RFC3339 range".into()))?
726 .to_rfc3339_opts(SecondsFormat::AutoSi, true);
727
728 // Chrono keeps millisecond precision as three digits. Go removes trailing
729 // zeros, so `.500Z` becomes `.5Z`.
730 if timestamp.contains('.') {
731 // The pop must stay outside debug_assert!, which vanishes in release
732 // builds and would leave the Z in place to be doubled below.
733 let suffix = timestamp.pop();
734 debug_assert_eq!(suffix, Some('Z'));
735 while timestamp.ends_with('0') {
736 timestamp.pop();
737 }
738 timestamp.push('Z');
739 }
740 Ok(timestamp)
741}
742
743#[cfg(test)]
744mod tests {
745 use super::*;
746 use crate::replica_url::parse_replica_url_with_query;
747
748 #[test]
749 fn timestamp_metadata_matches_go_rfc3339_nano() {
750 assert_eq!(
751 format_rfc3339_nano(1_609_459_200_000).unwrap(),
752 "2021-01-01T00:00:00Z"
753 );
754 assert_eq!(
755 format_rfc3339_nano(1_609_459_200_500).unwrap(),
756 "2021-01-01T00:00:00.5Z"
757 );
758 assert_eq!(
759 format_rfc3339_nano(1_609_459_200_123).unwrap(),
760 "2021-01-01T00:00:00.123Z"
761 );
762 assert!(format_rfc3339_nano(i64::MAX).is_err());
763 }
764
765 #[tokio::test]
766 async fn write_preserves_the_litestream_timestamp_metadata() {
767 let store = Arc::new(object_store::memory::InMemory::new());
768 let client = ObjectStoreClient::with_store(
769 ObjectStoreConfig {
770 bucket: "bucket".into(),
771 path: "replica".into(),
772 ..Default::default()
773 },
774 store.clone(),
775 );
776 let data = ltx::Header {
777 version: ltx::VERSION,
778 flags: ltx::HEADER_FLAG_NO_CHECKSUM,
779 page_size: 512,
780 commit: 1,
781 min_txid: TXID(1),
782 max_txid: TXID(1),
783 timestamp: 1_609_459_200_123,
784 pre_apply_checksum: 0,
785 wal_offset: 0,
786 wal_size: 0,
787 wal_salt1: 0,
788 wal_salt2: 0,
789 node_id: 0,
790 }
791 .marshal();
792
793 client
794 .write_ltx_file(0, TXID(1), TXID(1), &data)
795 .await
796 .expect("write LTX object");
797
798 let result = store
799 .get_opts(
800 &ObjPath::from("replica/0000/0000000000000001-0000000000000001.ltx"),
801 object_store::GetOptions {
802 head: true,
803 ..Default::default()
804 },
805 )
806 .await
807 .expect("read object metadata");
808 let value = result
809 .attributes
810 .get(&Attribute::Metadata(METADATA_KEY_TIMESTAMP.into()))
811 .expect("litestream timestamp metadata");
812 assert_eq!(value.as_ref(), "2021-01-01T00:00:00.123Z");
813 }
814
815 // ── ParseHost (port of TestParseHost, s3/replica_client_test.go:1071) ──────
816 #[test]
817 fn parse_host_table() {
818 let cases: &[(&str, &str, &str, &str, bool)] = &[
819 (
820 "my-space.sgp1.digitaloceanspaces.com",
821 "my-space",
822 "sgp1",
823 "https://sgp1.digitaloceanspaces.com",
824 false,
825 ),
826 (
827 "test-bucket.nyc3.digitaloceanspaces.com",
828 "test-bucket",
829 "nyc3",
830 "https://nyc3.digitaloceanspaces.com",
831 false,
832 ),
833 (
834 "mybucket.s3.us-east-1.amazonaws.com",
835 "mybucket",
836 "us-east-1",
837 "",
838 false,
839 ),
840 ("mybucket.s3.amazonaws.com", "mybucket", "", "", false),
841 (
842 "mybucket.s3.us-west-004.backblazeb2.com",
843 "mybucket",
844 "us-west-004",
845 "https://s3.us-west-004.backblazeb2.com",
846 true,
847 ),
848 (
849 "mybucket.localhost:9000",
850 "mybucket",
851 "us-east-1",
852 "http://localhost:9000",
853 true,
854 ),
855 ];
856 for (host, b, r, e, fps) in cases {
857 let (bucket, region, endpoint, force) = parse_host(host);
858 assert_eq!(&bucket, b, "bucket for {host}");
859 assert_eq!(&region, r, "region for {host}");
860 assert_eq!(&endpoint, e, "endpoint for {host}");
861 assert_eq!(force, *fps, "force_path_style for {host}");
862 }
863 }
864
865 #[test]
866 fn parse_host_standard_s3_is_bucket() {
867 let (bucket, region, endpoint, force) = parse_host("mybucket");
868 assert_eq!(bucket, "mybucket");
869 assert_eq!(region, "");
870 assert_eq!(endpoint, "");
871 assert!(!force);
872 }
873
874 fn cfg_from_url(url: &str) -> ObjectStoreConfig {
875 let parsed = parse_replica_url_with_query(url).unwrap();
876 ObjectStoreConfig::from_url(&parsed).unwrap()
877 }
878
879 // ── URL query param aliases (port of
880 // TestNewReplicaClientFromURL_QueryParamAliases, test:1940) ───────────────
881 #[test]
882 fn query_param_aliases() {
883 let c = cfg_from_url("s3://mybucket/path?forcePathStyle=true");
884 assert!(c.force_path_style);
885
886 let c = cfg_from_url("s3://mybucket/path?force-path-style=true");
887 assert!(c.force_path_style);
888
889 let c = cfg_from_url(
890 "s3://mybucket/path?endpoint=http://localhost:9000&force-path-style=false",
891 );
892 assert!(!c.force_path_style, "explicit force-path-style=false wins");
893
894 let c = cfg_from_url("s3://mybucket/path?skipVerify=true");
895 assert!(c.skip_verify);
896 let c = cfg_from_url("s3://mybucket/path?skip-verify=true");
897 assert!(c.skip_verify);
898
899 let c = cfg_from_url("s3://mybucket/path?part-size=10485760");
900 assert_eq!(c.part_size, 10_485_760);
901 let c = cfg_from_url("s3://mybucket/path?partSize=10485760");
902 assert_eq!(c.part_size, 10_485_760);
903
904 let c = cfg_from_url(
905 "s3://mybucket/path?force-path-style=true&skip-verify=true&part-size=8388608",
906 );
907 assert!(c.force_path_style);
908 assert!(c.skip_verify);
909 assert_eq!(c.part_size, 8_388_608);
910 }
911
912 // ── Endpoint env var (port of TestNewReplicaClientFromURL_EndpointEnvVar,
913 // test:2023). These mutate a process-global env var, so they run
914 // sequentially under one #[test] with save/restore to avoid cross-test
915 // interference. ───────────────────────────────────────────────────────────
916 #[test]
917 fn endpoint_env_var() {
918 let saved = std::env::var("LITESTREAM_S3_ENDPOINT").ok();
919
920 let set = |v: &str| {
921 if v.is_empty() {
922 std::env::remove_var("LITESTREAM_S3_ENDPOINT");
923 } else {
924 std::env::set_var("LITESTREAM_S3_ENDPOINT", v);
925 }
926 };
927
928 set("http://localhost:9000");
929 let c = cfg_from_url("s3://mybucket/path");
930 assert_eq!(c.endpoint, "http://localhost:9000");
931 assert!(c.force_path_style, "env endpoint forces path-style");
932
933 set("s3.example.com");
934 let c = cfg_from_url("s3://mybucket/path");
935 assert_eq!(
936 c.endpoint, "https://s3.example.com",
937 "env endpoint gets https"
938 );
939 assert!(c.force_path_style);
940
941 set("http://localhost:9000");
942 let c = cfg_from_url("s3://mybucket/path?endpoint=http://other:9000");
943 assert_eq!(
944 c.endpoint, "http://other:9000",
945 "query endpoint overrides env"
946 );
947 assert!(c.force_path_style);
948
949 set("http://localhost:9000");
950 let c = cfg_from_url("s3://mybucket/path?force-path-style=false");
951 assert_eq!(c.endpoint, "http://localhost:9000");
952 assert!(
953 !c.force_path_style,
954 "explicit force-path-style=false respected with env endpoint"
955 );
956
957 set("");
958 let c = cfg_from_url("s3://mybucket/path");
959 assert_eq!(c.endpoint, "");
960 assert!(!c.force_path_style);
961
962 // Restore.
963 match saved {
964 Some(v) => std::env::set_var("LITESTREAM_S3_ENDPOINT", v),
965 None => std::env::remove_var("LITESTREAM_S3_ENDPOINT"),
966 }
967 }
968
969 // ── Key construction (wire-compat requirement D-1, test:629/677/1040) ─────
970 #[test]
971 fn ltx_key_scheme() {
972 let client = ObjectStoreClient::new(ObjectStoreConfig {
973 bucket: "b".into(),
974 path: "replica".into(),
975 ..Default::default()
976 });
977 assert_eq!(
978 client.ltx_key(0, TXID(1), TXID(1)),
979 "replica/0000/0000000000000001-0000000000000001.ltx"
980 );
981 assert_eq!(
982 client.ltx_key(0, TXID(1), TXID(6)),
983 "replica/0000/0000000000000001-0000000000000006.ltx"
984 );
985 assert_eq!(client.level_prefix(0), "replica/0000/");
986 assert_eq!(client.root_prefix(), "replica/");
987 }
988
989 // ── isNotExists mapping (port of TestIsNotExists, test:53) ────────────────
990 #[test]
991 fn not_found_maps_to_io_not_found() {
992 let e = map_os_error(object_store::Error::NotFound {
993 path: "k".into(),
994 source: "missing".into(),
995 });
996 match e {
997 Error::Io(io) => assert_eq!(io.kind(), std::io::ErrorKind::NotFound),
998 other => panic!("expected Io(NotFound), got {other:?}"),
999 }
1000 }
1001}