Diffinery

homeflare/celldpublic

celld/crates/ltx/src/client/object_store.rs
1284 lines · 50.7 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 from
7//! the upstream conformance suite are kept:
8//!
9//! * key/path scheme `{path}/{level:04x}/{min}-{max}.ltx`
10//! (s3/replica_client.go:629, 677, 1040-1042);
11//! * the 5 MiB single-PUT vs multipart threshold
12//! (s3/replica_client.go:99 + the Go uploader default);
13//! * list + seek-skip on `min_txid < seek`, ascending TXID order
14//! (s3/replica_client.go:1530-1533);
15//! * `NoSuchKey` → `os.ErrNotExist` error mapping
16//! (s3/replica_client.go:647-649, 1662-1668);
17//! * batch DELETE up to 1000 keys per call with per-key error surfacing
18//! (s3/replica_client.go:1028-1101).
19//!
20//! The provider-defaults table (`ParseHost`, path-style flags, endpoint env
21//! var) is a faithful port of `NewReplicaClientFromURL`
22//! (s3/replica_client.go:133-314) so a `s3://…` URL configures the same way.
23//!
24//! This whole module is gated behind `#[cfg(feature = "s3")]` because it needs
25//! `object_store`'s AWS backend.
26
27#![cfg(feature = "s3")]
28
29use std::sync::Arc;
30
31use chrono::{DateTime, SecondsFormat};
32use futures_util::stream::{StreamExt, TryStreamExt};
33use object_store::aws::{
34 AmazonS3, AmazonS3Builder, AmazonS3ConfigKey, AwsAuthorizer, AwsCredential,
35};
36use object_store::client::HttpRequestBody;
37use object_store::path::Path as ObjPath;
38use object_store::{
39 Attribute, AttributeValue, Attributes, ClientOptions, GetOptions, GetRange, ObjectStore,
40 PutMultipartOptions, PutOptions, PutPayload, RetryConfig,
41};
42
43use crate::paged::RangeReader;
44
45use crate::error::{Error, Result};
46use crate::ltx::{self, FileInfo};
47use crate::replica_url::{
48 self, bool_query_value, ensure_endpoint_scheme, region_from_s3_arn, ParsedReplicaUrl,
49};
50use crate::TXID;
51
52use super::ReplicaClient;
53
54/// The standard Litestream S3 metadata key for an LTX header timestamp.
55const METADATA_KEY_TIMESTAMP: &str = "litestream-timestamp";
56
57/// The retry policy every replica store uses.
58///
59/// object_store defaults to 10 retries under a 180-second ceiling. That suits
60/// a client whose caller has nowhere else to go. A replica store always has
61/// somewhere else to go: a failed segment read is retried by the restore that
62/// asked for it, and a failed upload is retried by the next replication turn,
63/// so a long ladder inside one request buys nothing and delays the answer.
64///
65/// The ceiling matters most on a request a person is waiting for. A read-only
66/// cell inspection reaches this store, and a definite failure under the
67/// default policy takes seconds of pure backoff before the caller learns
68/// anything. Three attempts still absorb an ordinary transient error.
69pub fn replica_retry_config() -> RetryConfig {
70 RetryConfig {
71 max_retries: 3,
72 retry_timeout: std::time::Duration::from_secs(30),
73 ..RetryConfig::default()
74 }
75}
76
77/// The same key with an underscore, for Azure Blob Storage. An Azure blob
78/// metadata name must be a C# identifier, so it cannot hold a hyphen, and
79/// the standard key is refused there.
80const METADATA_KEY_TIMESTAMP_UNDERSCORE: &str = "litestream_timestamp";
81
82/// Which object-metadata name carries the LTX header timestamp.
83///
84/// The name is per backend, not per deployment: Azure Blob Storage
85/// refuses a hyphen in a metadata name, and every other supported store
86/// accepts the standard Litestream key. The value and its format do not
87/// change.
88///
89/// The key exists for external Litestream tooling, which reads
90/// `litestream-timestamp` to do a timestamp restore without downloading
91/// every candidate file. A renamed key therefore ends that interop on
92/// Azure. celld itself never reads the key back.
93#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
94pub enum TimestampMetadataKey {
95 /// `litestream-timestamp`, the standard Litestream key.
96 #[default]
97 Litestream,
98 /// `litestream_timestamp`, for a store that refuses a hyphen.
99 Underscore,
100}
101
102impl TimestampMetadataKey {
103 /// The metadata name this variant writes.
104 pub fn as_str(self) -> &'static str {
105 match self {
106 Self::Litestream => METADATA_KEY_TIMESTAMP,
107 Self::Underscore => METADATA_KEY_TIMESTAMP_UNDERSCORE,
108 }
109 }
110}
111
112/// Max keys S3 operates on per batch DELETE. `MaxKeys` (s3/replica_client.go:56).
113pub const MAX_KEYS: usize = 1000;
114
115/// Region used when none is specified. `DefaultRegion` (s3/replica_client.go:59).
116pub const DEFAULT_REGION: &str = "us-east-1";
117
118/// Multipart upload threshold: data at or above this size is uploaded with
119/// `put_multipart`; below it, a single `put`. Matches the Go uploader's 5 MiB
120/// `PartSize` default (s3/replica_client.go:99).
121pub const MULTIPART_THRESHOLD: usize = 5 * 1024 * 1024;
122
123// ── Config ────────────────────────────────────────────────────────────────────
124
125/// Configuration for the S3/R2/MinIO backend.
126///
127/// Maps to the public fields of Go's `ReplicaClient` struct
128/// (s3/replica_client.go:78-116). Zero/`None` values mean "use the backend
129/// default".
130#[derive(Debug, Clone, Default)]
131pub struct ObjectStoreConfig {
132 /// Bucket name (required).
133 pub bucket: String,
134 /// Key prefix within the bucket.
135 pub path: String,
136 /// AWS region.
137 pub region: String,
138 /// Custom endpoint (MinIO, R2, …); empty = native AWS.
139 pub endpoint: String,
140 /// Static access key id; empty = ambient credential chain.
141 pub access_key_id: String,
142 /// Static secret access key; empty = ambient credential chain.
143 pub secret_access_key: String,
144 /// Session token for temporary/scoped credentials (STS, R2 API tokens);
145 /// empty = none. Required alongside temporary keys or signing fails.
146 pub session_token: String,
147 /// Force path-style addressing (required for MinIO/Backblaze/Supabase/Filebase).
148 pub force_path_style: bool,
149 /// Skip TLS verification (allows self-signed endpoints).
150 pub skip_verify: bool,
151 /// Multipart part size in bytes; 0 = default (5 MiB).
152 pub part_size: u64,
153 /// The metadata name for the LTX header timestamp. The default is the
154 /// standard Litestream key; a host that injects an Azure store must
155 /// select [`TimestampMetadataKey::Underscore`], because Azure refuses
156 /// a hyphen in a metadata name.
157 pub timestamp_metadata_key: TimestampMetadataKey,
158}
159
160impl ObjectStoreConfig {
161 /// Construct from a parsed `s3://` URL, mirroring `NewReplicaClientFromURL`
162 /// (s3/replica_client.go:133-314): host → bucket/region/endpoint/path-style
163 /// (or ARN), query-param overrides (camelCase ↔ hyphenated aliases), the
164 /// `AWS_*`/`LITESTREAM_*` env credentials, the `LITESTREAM_S3_ENDPOINT` env
165 /// fallback, and the provider-specific path-style defaults for
166 /// MinIO/Backblaze/Filebase/Supabase.
167 pub fn from_url(parsed: &ParsedReplicaUrl) -> Result<Self> {
168 let host = &parsed.host;
169 let query = &parsed.query;
170
171 // Host → bucket/region/endpoint/forcePathStyle (or ARN access point).
172 let (bucket, mut region, mut endpoint, mut force_path_style) = if host.starts_with("arn:") {
173 (host.clone(), region_from_s3_arn(host), String::new(), false)
174 } else {
175 parse_host(host)
176 };
177
178 let q = Some(query);
179
180 // endpoint query param: ensure scheme, default to path-style for custom
181 // endpoints unless force-path-style is explicitly set to false.
182 let q_endpoint = query.get("endpoint");
183 if !q_endpoint.is_empty() {
184 let (ep, _) = ensure_endpoint_scheme(q_endpoint);
185 endpoint = ep;
186 match bool_query_value(q, &["forcePathStyle", "force-path-style"]) {
187 Some(false) => {}
188 _ => force_path_style = true,
189 }
190 }
191 let q_region = query.get("region");
192 if !q_region.is_empty() {
193 region = q_region.to_string();
194 }
195 if let Some(v) = bool_query_value(q, &["forcePathStyle", "force-path-style"]) {
196 force_path_style = v;
197 }
198 let mut skip_verify = false;
199 if let Some(v) = bool_query_value(q, &["skipVerify", "skip-verify"]) {
200 skip_verify = v;
201 }
202
203 let mut part_size: u64 = 0;
204 let v = query.get("partSize");
205 let v2 = query.get("part-size");
206 if !v.is_empty() {
207 if let Ok(n) = v.parse::<u64>() {
208 if n > 0 {
209 part_size = n;
210 }
211 }
212 } else if !v2.is_empty() {
213 if let Ok(n) = v2.parse::<u64>() {
214 if n > 0 {
215 part_size = n;
216 }
217 }
218 }
219
220 if bucket.is_empty() {
221 return Err(Error::Other("bucket required for s3 replica URL".into()));
222 }
223
224 // Track whether forcePathStyle was explicitly set via query param
225 // (s3/replica_client.go:208) — this gates the env-var/provider defaults.
226 let force_path_style_set =
227 !query.get("forcePathStyle").is_empty() || !query.get("force-path-style").is_empty();
228
229 // Static credentials from env (AWS_* preferred, then LITESTREAM_*).
230 let mut access_key_id = String::new();
231 let mut secret_access_key = String::new();
232 if let Some(v) = nonempty_env("AWS_ACCESS_KEY_ID") {
233 access_key_id = v;
234 } else if let Some(v) = nonempty_env("LITESTREAM_ACCESS_KEY_ID") {
235 access_key_id = v;
236 }
237 if let Some(v) = nonempty_env("AWS_SECRET_ACCESS_KEY") {
238 secret_access_key = v;
239 } else if let Some(v) = nonempty_env("LITESTREAM_SECRET_ACCESS_KEY") {
240 secret_access_key = v;
241 }
242 let session_token = nonempty_env("AWS_SESSION_TOKEN")
243 .or_else(|| nonempty_env("LITESTREAM_SESSION_TOKEN"))
244 .unwrap_or_default();
245
246 // LITESTREAM_S3_ENDPOINT env fallback (only when no endpoint yet).
247 if endpoint.is_empty() {
248 if let Some(v) = nonempty_env("LITESTREAM_S3_ENDPOINT") {
249 let (ep, _) = ensure_endpoint_scheme(&v);
250 endpoint = ep;
251 if !force_path_style_set {
252 force_path_style = true;
253 }
254 }
255 }
256
257 // Provider detection for applying defaults.
258 let is_filebase = replica_url::is_filebase_endpoint(&endpoint);
259 let is_backblaze = replica_url::is_backblaze_endpoint(&endpoint);
260 let is_minio = replica_url::is_minio_endpoint(&endpoint);
261 let is_supabase = replica_url::is_supabase_endpoint(&endpoint);
262 if !force_path_style_set && (is_filebase || is_backblaze || is_minio || is_supabase) {
263 force_path_style = true;
264 }
265
266 Ok(ObjectStoreConfig {
267 bucket,
268 path: parsed.path.clone(),
269 region,
270 endpoint,
271 access_key_id,
272 secret_access_key,
273 session_token,
274 force_path_style,
275 skip_verify,
276 part_size,
277 timestamp_metadata_key: TimestampMetadataKey::default(),
278 })
279 }
280
281 /// Build the backing `Arc<dyn ObjectStore>` for this config. Public so a host
282 /// can build one store for a bucket and share it across many
283 /// [`ObjectStoreClient::with_store`] clients that differ only by key prefix
284 /// — one connection pool for every cell on a node.
285 ///
286 /// An empty `access_key_id` and `secret_access_key` select the ambient AWS
287 /// credential chain, which reads web identity, ECS task credentials, EKS
288 /// Pod Identity, and instance metadata from the process environment. Set
289 /// both fields to keep a caller's own credentials authoritative.
290 pub fn build_store(&self) -> Result<Arc<dyn ObjectStore>> {
291 Ok(self.build_s3()?)
292 }
293
294 /// The concrete S3 store, kept beside the erased one so the paged fault
295 /// path can borrow its credential.
296 fn build_s3(&self) -> Result<Arc<AmazonS3>> {
297 if self.bucket.is_empty() {
298 return Err(Error::Other("s3: bucket name is required".into()));
299 }
300
301 let region = if self.region.is_empty() {
302 DEFAULT_REGION.to_string()
303 } else {
304 self.region.clone()
305 };
306
307 // Forward the credential inputs that object_store reads. A bare
308 // `new()` reads no environment, so it falls through to IMDS on EKS,
309 // and `from_env()` would also import endpoint and request settings
310 // that belong to this explicit ObjectStoreConfig. So the allowlist
311 // stops at the credential boundary, and the config below stays
312 // authoritative.
313 //
314 // object_store 0.12.5 takes AWS_WEB_IDENTITY_TOKEN_FILE and
315 // AWS_ROLE_ARN from the process environment rather than from these
316 // builder fields, so that pair changes nothing today. It stays because
317 // the session name and the STS endpoint beside it *are* read from the
318 // builder, and a release that moves the pair to the builder must not
319 // drop this client back to IMDS.
320 let mut builder = AmazonS3Builder::new();
321 for (name, key) in [
322 (
323 "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI",
324 AmazonS3ConfigKey::ContainerCredentialsRelativeUri,
325 ),
326 (
327 "AWS_CONTAINER_CREDENTIALS_FULL_URI",
328 AmazonS3ConfigKey::ContainerCredentialsFullUri,
329 ),
330 (
331 "AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE",
332 AmazonS3ConfigKey::ContainerAuthorizationTokenFile,
333 ),
334 (
335 "AWS_WEB_IDENTITY_TOKEN_FILE",
336 AmazonS3ConfigKey::WebIdentityTokenFile,
337 ),
338 ("AWS_ROLE_ARN", AmazonS3ConfigKey::RoleArn),
339 ("AWS_ROLE_SESSION_NAME", AmazonS3ConfigKey::RoleSessionName),
340 ("AWS_ENDPOINT_URL_STS", AmazonS3ConfigKey::StsEndpoint),
341 ("AWS_METADATA_ENDPOINT", AmazonS3ConfigKey::MetadataEndpoint),
342 ] {
343 if let Some(value) = nonempty_env(name) {
344 builder = builder.with_config(key, value);
345 }
346 }
347 let mut builder = builder
348 .with_bucket_name(&self.bucket)
349 .with_region(region)
350 .with_retry(replica_retry_config())
351 // Path-style ⇔ NOT virtual-hosted-style (s3/replica_client.go:258-263).
352 .with_virtual_hosted_style_request(!self.force_path_style)
353 // object_store disables S3 conditional puts by default. Keep the
354 // established ETagMatch behavior, so a user of the returned store
355 // can send PutMode::Create or PutMode::Update. Ordinary replica
356 // PUTs remain unconditional.
357 .with_conditional_put(object_store::aws::S3ConditionalPut::ETagMatch);
358
359 if !self.endpoint.is_empty() {
360 // A plaintext or local endpoint must allow HTTP. skip_verify applies
361 // only to TLS certificate validation.
362 let allow_http = self.endpoint.starts_with("http://")
363 || replica_url::is_local_endpoint(&self.endpoint);
364 let client_options = ClientOptions::new()
365 .with_allow_http(allow_http)
366 .with_allow_invalid_certificates(self.skip_verify);
367 builder = builder
368 .with_endpoint(&self.endpoint)
369 .with_client_options(client_options);
370 }
371
372 if !self.access_key_id.is_empty() {
373 builder = builder.with_access_key_id(&self.access_key_id);
374 }
375 if !self.secret_access_key.is_empty() {
376 builder = builder.with_secret_access_key(&self.secret_access_key);
377 }
378 if !self.session_token.is_empty() {
379 builder = builder.with_token(&self.session_token);
380 }
381
382 let store = builder
383 .build()
384 .map_err(|e| Error::Other(format!("s3: build store: {e}").into()))?;
385 Ok(Arc::new(store))
386 }
387
388 /// Effective multipart part size (`part_size`, or the 5 MiB default).
389 fn effective_part_size(&self) -> usize {
390 if self.part_size > 0 {
391 self.part_size as usize
392 } else {
393 MULTIPART_THRESHOLD
394 }
395 }
396}
397
398/// Returns `Some(value)` for a non-empty env var, else `None`. Mirrors Go's
399/// `if v := os.Getenv(k); v != ""` pattern (s3/replica_client.go:211-224).
400fn nonempty_env(key: &str) -> Option<String> {
401 match std::env::var(key) {
402 Ok(v) if !v.is_empty() => Some(v),
403 _ => None,
404 }
405}
406
407// ── ParseHost ─────────────────────────────────────────────────────────────────
408
409/// Parse an S3 host into `(bucket, region, endpoint, force_path_style)`.
410///
411/// Direct port of `ParseHost` (s3/replica_client.go:1608-1652): MinIO-style
412/// `bucket.host:port`, then the AWS / DigitalOcean / Backblaze / Filebase /
413/// Scaleway provider patterns, falling back to "host *is* the bucket".
414pub fn parse_host(host: &str) -> (String, String, String, bool) {
415 // MinIO-style hosts: `bucket.host:port` (a colon and not a ".com").
416 if host.contains(':') && !host.contains(".com") {
417 // SplitN(host, ".", 2)
418 if let Some((bucket, rest)) = host.split_once('.') {
419 return (
420 bucket.to_string(),
421 DEFAULT_REGION.to_string(),
422 format!("http://{rest}"),
423 true,
424 );
425 }
426 // No bucket in host, just host:port.
427 return (String::new(), String::new(), format!("http://{host}"), true);
428 }
429
430 // AWS S3: `^(.+)\.s3(?:\.([^.]+))?\.amazonaws\.com$`
431 if let Some((bucket, region)) = match_aws_s3(host) {
432 return (bucket, region, String::new(), false);
433 }
434 // DigitalOcean: `^(?:(.+)\.)?([^.]+)\.digitaloceanspaces.com$`
435 if let Some((bucket, region)) = match_two_label_suffix(host, ".digitaloceanspaces.com") {
436 return (
437 bucket,
438 region.clone(),
439 format!("https://{region}.digitaloceanspaces.com"),
440 false,
441 );
442 }
443 // Backblaze: `^(?:(.+)\.)?s3.([^.]+)\.backblazeb2.com$`
444 if let Some((bucket, region)) = match_s3_region_suffix(host, ".backblazeb2.com") {
445 return (
446 bucket,
447 region.clone(),
448 format!("https://s3.{region}.backblazeb2.com"),
449 true,
450 );
451 }
452 // Filebase: `^(?:(.+)\.)?s3.filebase.com$`
453 if let Some(bucket) = match_filebase(host) {
454 return (bucket, String::new(), "s3.filebase.com".to_string(), false);
455 }
456 // Scaleway: `^(?:(.+)\.)?s3.([^.]+)\.scw\.cloud$`
457 if let Some((bucket, region)) = match_s3_region_suffix(host, ".scw.cloud") {
458 return (
459 bucket,
460 region.clone(),
461 format!("s3.{region}.scw.cloud"),
462 false,
463 );
464 }
465
466 // Standard S3: the host is the bucket name.
467 (host.to_string(), String::new(), String::new(), false)
468}
469
470/// `^(.+)\.s3(?:\.([^.]+))?\.amazonaws\.com$` → (bucket, region).
471fn match_aws_s3(host: &str) -> Option<(String, String)> {
472 let rest = host.strip_suffix(".amazonaws.com")?;
473 // rest = "<bucket>.s3" or "<bucket>.s3.<region>"
474 if let Some(bucket) = rest.strip_suffix(".s3") {
475 if bucket.is_empty() {
476 return None;
477 }
478 return Some((bucket.to_string(), String::new()));
479 }
480 // "<bucket>.s3.<region>": find the ".s3." separator; region is a single
481 // label ([^.]+) — i.e. the remainder after ".s3." must contain no dot.
482 let idx = rest.find(".s3.")?;
483 let bucket = &rest[..idx];
484 let region = &rest[idx + 4..];
485 if bucket.is_empty() || region.is_empty() || region.contains('.') {
486 return None;
487 }
488 Some((bucket.to_string(), region.to_string()))
489}
490
491/// `^(?:(.+)\.)?([^.]+)\.<suffix>$` → (bucket, region). `suffix` starts with '.'.
492fn match_two_label_suffix(host: &str, suffix: &str) -> Option<(String, String)> {
493 let rest = host.strip_suffix(suffix)?;
494 if rest.is_empty() {
495 return None;
496 }
497 // The last label before the suffix is the region; anything before it
498 // (optionally) is the bucket.
499 match rest.rfind('.') {
500 Some(i) => {
501 let bucket = &rest[..i];
502 let region = &rest[i + 1..];
503 if region.is_empty() {
504 return None;
505 }
506 Some((bucket.to_string(), region.to_string()))
507 }
508 None => Some((String::new(), rest.to_string())),
509 }
510}
511
512/// `^(?:(.+)\.)?s3.([^.]+)\.<suffix>$` → (bucket, region). `suffix` starts with '.'.
513fn match_s3_region_suffix(host: &str, suffix: &str) -> Option<(String, String)> {
514 let rest = host.strip_suffix(suffix)?;
515 // rest = "[bucket.]s3.<region>"; region is one label ([^.]+).
516 // Bucket-less form: rest == "s3.<region>".
517 if let Some(region) = rest.strip_prefix("s3.") {
518 if region.is_empty() || region.contains('.') {
519 return None;
520 }
521 return Some((String::new(), region.to_string()));
522 }
523 // Bucketed form: rest == "<bucket>.s3.<region>".
524 let sep = rest.find(".s3.")?;
525 let bucket = &rest[..sep];
526 let region = &rest[sep + 4..];
527 if bucket.is_empty() || region.is_empty() || region.contains('.') {
528 return None;
529 }
530 Some((bucket.to_string(), region.to_string()))
531}
532
533/// `^(?:(.+)\.)?s3.filebase.com$` → bucket.
534fn match_filebase(host: &str) -> Option<String> {
535 if host == "s3.filebase.com" {
536 return Some(String::new());
537 }
538 let bucket = host.strip_suffix(".s3.filebase.com")?;
539 if bucket.is_empty() {
540 None
541 } else {
542 Some(bucket.to_string())
543 }
544}
545
546// ── Client ────────────────────────────────────────────────────────────────────
547
548/// Concrete S3/R2/MinIO backend, wrapping a lazily-initialised
549/// `Arc<dyn ObjectStore>`. The config-driven path builds an S3 store, but
550/// [`Self::with_store`] accepts any prebuilt `ObjectStore` — the five
551/// replica operations are provider-neutral, and a host can inject e.g. a
552/// GCS or in-memory store.
553///
554/// Mirrors Go `ReplicaClient` (s3/replica_client.go:78-116). The inner store is
555/// created on the first call that needs it (`OnceCell`, mirroring `Init`,
556/// s3/replica_client.go:322-477), so construction is infallible and race-free.
557pub struct ObjectStoreClient {
558 store: tokio::sync::OnceCell<Arc<dyn ObjectStore>>,
559 /// The concrete store when this client built its own; `with_store`
560 /// leaves it empty, and the paged reader is then unavailable.
561 s3: tokio::sync::OnceCell<Arc<AmazonS3>>,
562 config: ObjectStoreConfig,
563}
564
565impl std::fmt::Debug for ObjectStoreClient {
566 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
567 f.debug_struct("ObjectStoreClient")
568 .field("config", &self.config)
569 .field("initialized", &self.store.initialized())
570 .finish()
571 }
572}
573
574impl ObjectStoreClient {
575 /// Create a client from config (no I/O; the store is built on first use).
576 pub fn new(config: ObjectStoreConfig) -> Self {
577 ObjectStoreClient {
578 store: tokio::sync::OnceCell::new(),
579 s3: tokio::sync::OnceCell::new(),
580 config,
581 }
582 }
583
584 /// Create a client directly from an already-built `ObjectStore`, such as an
585 /// in-memory store or a pre-configured backend.
586 pub fn with_store(config: ObjectStoreConfig, store: Arc<dyn ObjectStore>) -> Self {
587 let cell = tokio::sync::OnceCell::new();
588 cell.set(store).ok();
589 ObjectStoreClient {
590 store: cell,
591 s3: tokio::sync::OnceCell::new(),
592 config,
593 }
594 }
595
596 /// Get-or-build the inner store, once.
597 async fn store(&self) -> Result<&Arc<dyn ObjectStore>> {
598 self.store
599 .get_or_try_init(|| async {
600 let s3 = self.config.build_s3()?;
601 self.s3.set(s3.clone()).ok();
602 Ok(s3 as Arc<dyn ObjectStore>)
603 })
604 .await
605 }
606
607 /// A blocking ranged reader over this client's objects for the paged
608 /// VFS. It snapshots the store's credential now (an async fetch on the
609 /// caller's runtime) so each fault can sign its own request on whatever
610 /// thread SQLite is on, with no runtime in the loop.
611 pub async fn blocking_range_reader(&self) -> Result<Box<dyn RangeReader>> {
612 let config = &self.config;
613 // Only native S3 is read by a signed request of our own; any other
614 // store — the deterministic simulation's, a directory, memory —
615 // is read through the store on a helper thread.
616 let store = self.store().await?;
617 if !store.to_string().starts_with("AmazonS3") {
618 return Ok(Box::new(StoreRangeReader::new(
619 store.clone(),
620 config.path.clone(),
621 )));
622 }
623 // celld's per-cell clients share one pre-built store (`with_store`),
624 // so there is no concrete store to borrow a provider from; the static
625 // keys the config carries are the credential. Only an ambient
626 // credential chain needs the provider, and that needs a store this
627 // client built itself.
628 let mut provider = None;
629 let credential = if !config.access_key_id.is_empty() {
630 Arc::new(AwsCredential {
631 key_id: config.access_key_id.clone(),
632 secret_key: config.secret_access_key.clone(),
633 token: (!config.session_token.is_empty()).then(|| config.session_token.clone()),
634 })
635 } else {
636 self.store().await?;
637 let s3 = self.s3.get().ok_or_else(|| {
638 Error::Other(
639 "paged reads over an ambient credential chain need a store this client built"
640 .into(),
641 )
642 })?;
643 provider = Some(s3.credentials().clone());
644 s3.credentials()
645 .get_credential()
646 .await
647 .map_err(map_os_error)?
648 };
649 let region = if config.region.is_empty() {
650 DEFAULT_REGION.to_string()
651 } else {
652 config.region.clone()
653 };
654 // Mirror the store's own addressing so the signed host matches what
655 // the bucket expects: virtual-hosted unless path-style was forced.
656 let base = if config.endpoint.is_empty() {
657 format!("https://{}.s3.{region}.amazonaws.com", config.bucket)
658 } else if config.force_path_style {
659 format!(
660 "{}/{}",
661 config.endpoint.trim_end_matches('/'),
662 config.bucket
663 )
664 } else {
665 let (scheme, host) = config
666 .endpoint
667 .split_once("://")
668 .ok_or_else(|| Error::Other("s3: endpoint has no scheme".into()))?;
669 format!(
670 "{scheme}://{}.{}",
671 config.bucket,
672 host.trim_end_matches('/')
673 )
674 };
675 let tls = ureq::tls::TlsConfig::builder()
676 .disable_verification(config.skip_verify)
677 .build();
678 // A fault runs on the caller's thread — for the actor's queries the
679 // node's core — so this budget is how long one slow object read can
680 // stall every cell on the node. A normal fault is 65-200 ms; 10 s is
681 // fifty times that, and the single retry below bounds a stall at
682 // about 20 s instead of the 90 s three 30 s attempts allowed.
683 let agent = ureq::Agent::config_builder()
684 .timeout_global(Some(FAULT_TIMEOUT))
685 .http_status_as_error(false)
686 .tls_config(tls)
687 .build()
688 .new_agent();
689 Ok(Box::new(S3RangeReader {
690 credential: std::sync::RwLock::new(credential),
691 provider,
692 region,
693 base,
694 prefix: config.path.clone(),
695 agent,
696 }))
697 }
698
699 /// Returns whether the replica epoch prefix contains an object.
700 ///
701 /// The caller needs only an existence proof, so it stops the recursive,
702 /// delimiter-less listing after the first object. An empty or non-empty
703 /// prefix therefore costs one list request instead of one request for each
704 /// compaction level.
705 pub async fn has_any_object(&self) -> Result<bool> {
706 let store = self.store().await?;
707 let prefix = ObjPath::from(self.root_prefix());
708 store
709 .list(Some(&prefix))
710 .next()
711 .await
712 .transpose()
713 .map(|object| object.is_some())
714 .map_err(map_os_error)
715 }
716
717 /// Build the S3 key for an LTX file: `{path}/{level:04x}/{min}-{max}.ltx`.
718 /// Ported from s3/replica_client.go:629, 677, 1040-1042.
719 fn ltx_key(&self, level: i32, min_txid: TXID, max_txid: TXID) -> String {
720 let filename = ltx::format_filename(min_txid, max_txid);
721 format!("{}/{:04x}/{}", self.config.path, level, filename)
722 }
723
724 /// Prefix for listing a level: `{path}/{level:04x}/`.
725 /// Ported from s3/replica_client.go:1363.
726 fn level_prefix(&self, level: i32) -> String {
727 format!("{}/{:04x}/", self.config.path, level)
728 }
729
730 /// Root prefix for delete-all: `{path}/`. (s3/replica_client.go:1114).
731 fn root_prefix(&self) -> String {
732 format!("{}/", self.config.path)
733 }
734
735 /// The highest transaction any level holds, from one listing of the
736 /// whole path. A caller that only needs the watermark, such as a log
737 /// recovery deciding which gathered rows the bucket already covers, pays
738 /// one round trip here instead of one per level.
739 pub async fn max_txid_all_levels(&self) -> Result<TXID> {
740 let store = self.store().await?;
741 let prefix = ObjPath::from(self.root_prefix());
742 let mut listed = store.list(Some(&prefix));
743 let mut max = TXID(0);
744 while let Some(meta) = listed.try_next().await.map_err(map_os_error)? {
745 let name = meta.location.filename().unwrap_or("");
746 if let Ok((_, max_txid)) = ltx::parse_filename(name) {
747 max = max.max(max_txid);
748 }
749 }
750 Ok(max)
751 }
752}
753
754/// Map an `object_store::Error` to `crate::Error`, preserving NotFound as
755/// `io::ErrorKind::NotFound` so callers keep working with the std error kind.
756/// Mirrors `isNotExists` → `os.ErrNotExist` (s3/replica_client.go:647-649,
757/// 1662-1668).
758fn map_os_error(e: object_store::Error) -> Error {
759 match e {
760 object_store::Error::NotFound { .. } => {
761 Error::Io(std::io::Error::new(std::io::ErrorKind::NotFound, e))
762 }
763 other => Error::Other(Box::new(other)),
764 }
765}
766
767#[async_trait::async_trait]
768impl ReplicaClient for ObjectStoreClient {
769 async fn ltx_files(&self, level: i32, seek: TXID) -> Result<Vec<FileInfo>> {
770 self.ltx_files_bounded(level, seek, usize::MAX).await
771 }
772
773 async fn ltx_files_bounded(
774 &self,
775 level: i32,
776 seek: TXID,
777 limit: usize,
778 ) -> Result<Vec<FileInfo>> {
779 if limit == 0 {
780 return Ok(Vec::new());
781 }
782 let store = self.store().await?;
783 let prefix = ObjPath::from(self.level_prefix(level));
784 // The offset ends immediately before every filename with this minimum
785 // TXID. S3 and GCS can push it into the listing request, so an additive
786 // compaction does not scan the complete retained L0 history. The
787 // supported production stores return each page in lexical order. The
788 // compactor validates continuity and fails closed for an unordered
789 // custom store.
790 let offset = ObjPath::from(format!("{}{:016x}", self.level_prefix(level), seek.0));
791 let mut listed = store.list_with_offset(Some(&prefix), &offset);
792 let mut infos = Vec::with_capacity(limit.min(256));
793 while let Some(meta) = listed.try_next().await.map_err(map_os_error)? {
794 let name = meta.location.filename().unwrap_or("");
795 let (min_txid, max_txid) = match ltx::parse_filename(name) {
796 Ok(t) => t,
797 Err(_) => continue, // skip non-LTX keys
798 };
799 if min_txid < seek {
800 continue;
801 }
802 infos.push(FileInfo {
803 level,
804 min_txid,
805 max_txid,
806 size: meta.size as i64,
807 created_at: Some(std::time::SystemTime::from(meta.last_modified)),
808 ..Default::default()
809 });
810 if infos.len() == limit {
811 break;
812 }
813 }
814
815 // Iterator contract: ascending by (level, min_txid, max_txid).
816 infos.sort_by(|a, b| {
817 (a.level, a.min_txid.0, a.max_txid.0).cmp(&(b.level, b.min_txid.0, b.max_txid.0))
818 });
819 Ok(infos)
820 }
821
822 async fn open_ltx_file(&self, level: i32, min_txid: TXID, max_txid: TXID) -> Result<Vec<u8>> {
823 let store = self.store().await?;
824 let key = ObjPath::from(self.ltx_key(level, min_txid, max_txid));
825
826 let result = match store.get(&key).await {
827 Ok(r) => r,
828 Err(object_store::Error::NotFound { .. }) => {
829 return Err(Error::Io(std::io::Error::new(
830 std::io::ErrorKind::NotFound,
831 format!("replica: get object {key}: not found"),
832 )));
833 }
834 Err(e) => return Err(map_os_error(e)),
835 };
836
837 let bytes = result.bytes().await.map_err(map_os_error)?;
838 Ok(bytes.to_vec())
839 }
840
841 async fn read_range(
842 &self,
843 level: i32,
844 min_txid: TXID,
845 max_txid: TXID,
846 offset: u64,
847 len: u64,
848 ) -> Result<Vec<u8>> {
849 let store = self.store().await?;
850 let key = ObjPath::from(self.ltx_key(level, min_txid, max_txid));
851 let options = GetOptions {
852 range: Some(GetRange::Bounded(offset..offset.saturating_add(len))),
853 ..Default::default()
854 };
855 let result = match store.get_opts(&key, options).await {
856 Ok(r) => r,
857 Err(object_store::Error::NotFound { .. }) => {
858 return Err(Error::Io(std::io::Error::new(
859 std::io::ErrorKind::NotFound,
860 format!("replica: get range {key}: not found"),
861 )));
862 }
863 Err(e) => return Err(map_os_error(e)),
864 };
865 let bytes = result.bytes().await.map_err(map_os_error)?;
866 Ok(bytes.to_vec())
867 }
868
869 async fn write_ltx_file(
870 &self,
871 level: i32,
872 min_txid: TXID,
873 max_txid: TXID,
874 data: &[u8],
875 ) -> Result<FileInfo> {
876 let store = self.store().await?;
877
878 // Preserve the LTX header timestamp in the standard Litestream object
879 // metadata. This costs no extra request and lets Litestream perform an
880 // accurate timestamp restore without downloading every candidate file.
881 // The name is per backend, because Azure refuses a hyphen in it.
882 let header = ltx::Header::parse(data)?;
883 let created_at = std::time::UNIX_EPOCH
884 + std::time::Duration::from_millis(header.timestamp.max(0) as u64);
885 let mut attributes = Attributes::new();
886 attributes.insert(
887 Attribute::Metadata(self.config.timestamp_metadata_key.as_str().into()),
888 AttributeValue::from(format_rfc3339_nano(header.timestamp)?),
889 );
890 let key = ObjPath::from(self.ltx_key(level, min_txid, max_txid));
891
892 // Multipart threshold: < 5 MiB → single PUT; ≥ 5 MiB → multipart with
893 // fixed-size parts. Ported from the Go uploader's 5 MiB PartSize default
894 // (s3/replica_client.go:99, brief §5.1).
895 let part_size = self.config.effective_part_size();
896 if data.len() < MULTIPART_THRESHOLD {
897 let payload = PutPayload::from(data.to_vec());
898 let options = PutOptions {
899 attributes,
900 ..Default::default()
901 };
902 store
903 .put_opts(&key, payload, options)
904 .await
905 .map_err(|e| Error::Other(format!("replica: upload to {key}: {e}").into()))?;
906 } else {
907 let options = PutMultipartOptions {
908 attributes,
909 ..Default::default()
910 };
911 let mut upload = store
912 .put_multipart_opts(&key, options)
913 .await
914 .map_err(|e| Error::Other(format!("replica: upload to {key}: {e}").into()))?;
915 // Keep every fallible step inside one result. Otherwise, a new
916 // early return can leave completed parts in the storage service.
917 let upload_result: Result<()> = async {
918 // Upload in fixed-size parts (each ≥ 5 MiB except possibly the
919 // last, matching object_store's part-size requirement).
920 for chunk in data.chunks(part_size.max(MULTIPART_THRESHOLD)) {
921 upload
922 .put_part(PutPayload::from(chunk.to_vec()))
923 .await
924 .map_err(|e| {
925 Error::Other(format!("replica: upload part to {key}: {e}").into())
926 })?;
927 }
928 upload.complete().await.map_err(|e| {
929 Error::Other(format!("replica: complete upload to {key}: {e}").into())
930 })?;
931 Ok(())
932 }
933 .await;
934 if let Err(upload_error) = upload_result {
935 if let Err(abort_error) = upload.abort().await {
936 tracing::warn!(
937 %abort_error,
938 key = %key,
939 "failed LTX multipart upload could not be aborted"
940 );
941 }
942 return Err(upload_error);
943 }
944 }
945
946 Ok(FileInfo {
947 level,
948 min_txid,
949 max_txid,
950 size: data.len() as i64,
951 created_at: Some(created_at),
952 ..Default::default()
953 })
954 }
955
956 async fn delete_ltx_files(&self, files: &[FileInfo]) -> Result<()> {
957 if files.is_empty() {
958 return Ok(());
959 }
960 let store = self.store().await?;
961
962 // Build the key list, then delete in batches of MAX_KEYS via the
963 // store's delete_stream, surfacing per-key errors (brief §5.5).
964 let keys: Vec<ObjPath> = files
965 .iter()
966 .map(|info| ObjPath::from(self.ltx_key(info.level, info.min_txid, info.max_txid)))
967 .collect();
968
969 for batch in keys.chunks(MAX_KEYS) {
970 delete_batch(store.as_ref(), batch, /*ignore_missing=*/ true).await?;
971 }
972 Ok(())
973 }
974
975 async fn delete_all(&self) -> Result<()> {
976 let store = self.store().await?;
977 let prefix = ObjPath::from(self.root_prefix());
978
979 // List everything under the path prefix, then batch-delete.
980 // (s3/replica_client.go:1104-1148).
981 let keys: Vec<ObjPath> = store
982 .list(Some(&prefix))
983 .map_ok(|m| m.location)
984 .map_err(map_os_error)
985 .try_collect()
986 .await?;
987
988 for batch in keys.chunks(MAX_KEYS) {
989 delete_batch(store.as_ref(), batch, /*ignore_missing=*/ true).await?;
990 }
991 Ok(())
992 }
993}
994
995/// Delete a batch of keys via `delete_stream`, surfacing per-key errors.
996///
997/// When `ignore_missing` is set, `NotFound` is tolerated (delete is idempotent —
998/// the file client swallows ENOENT the same way), but every other per-key error
999/// is returned (brief §5.5: do not silently swallow partial failures).
1000async fn delete_batch(
1001 store: &dyn ObjectStore,
1002 keys: &[ObjPath],
1003 ignore_missing: bool,
1004) -> Result<()> {
1005 if keys.is_empty() {
1006 return Ok(());
1007 }
1008 let owned: Vec<ObjPath> = keys.to_vec();
1009 let stream = futures_util::stream::iter(owned.into_iter().map(Ok));
1010 let mut results = store.delete_stream(stream.boxed());
1011 while let Some(res) = results.next().await {
1012 match res {
1013 Ok(_) => {}
1014 Err(object_store::Error::NotFound { .. }) if ignore_missing => {}
1015 Err(e) => return Err(map_os_error(e)),
1016 }
1017 }
1018 Ok(())
1019}
1020
1021/// Format a Unix-millisecond timestamp like Go's `time.RFC3339Nano`.
1022fn format_rfc3339_nano(unix_millis: i64) -> Result<String> {
1023 let mut timestamp = DateTime::from_timestamp_millis(unix_millis.max(0))
1024 .ok_or_else(|| Error::Other("LTX timestamp is outside the RFC3339 range".into()))?
1025 .to_rfc3339_opts(SecondsFormat::AutoSi, true);
1026
1027 // Chrono keeps millisecond precision as three digits. Go removes trailing
1028 // zeros, so `.500Z` becomes `.5Z`.
1029 if timestamp.contains('.') {
1030 // The pop must stay outside debug_assert!, which vanishes in release
1031 // builds and would leave the Z in place to be doubled below.
1032 let suffix = timestamp.pop();
1033 debug_assert_eq!(suffix, Some('Z'));
1034 while timestamp.ends_with('0') {
1035 timestamp.pop();
1036 }
1037 timestamp.push('Z');
1038 }
1039 Ok(timestamp)
1040}
1041
1042#[doc(hidden)]
1043pub mod internal {
1044 use super::*;
1045
1046 pub const METADATA_KEY_TIMESTAMP: &str = super::METADATA_KEY_TIMESTAMP;
1047 pub const METADATA_KEY_TIMESTAMP_UNDERSCORE: &str = super::METADATA_KEY_TIMESTAMP_UNDERSCORE;
1048
1049 pub fn format_rfc3339_nano(unix_millis: i64) -> Result<String> {
1050 super::format_rfc3339_nano(unix_millis)
1051 }
1052
1053 pub fn ltx_key(client: &ObjectStoreClient, level: i32, min: TXID, max: TXID) -> String {
1054 client.ltx_key(level, min, max)
1055 }
1056
1057 pub fn level_prefix(client: &ObjectStoreClient, level: i32) -> String {
1058 client.level_prefix(level)
1059 }
1060
1061 pub fn root_prefix(client: &ObjectStoreClient) -> String {
1062 client.root_prefix()
1063 }
1064
1065 pub fn map_os_error(error: object_store::Error) -> Error {
1066 super::map_os_error(error)
1067 }
1068}
1069
1070/// Bytes the SigV4 canonical URI leaves unencoded, plus the segment
1071/// delimiter: A-Z a-z 0-9 `-` `.` `_` `~` and `/`.
1072const KEY_ENCODE_SET: &percent_encoding::AsciiSet = &percent_encoding::NON_ALPHANUMERIC
1073 .remove(b'-')
1074 .remove(b'.')
1075 .remove(b'_')
1076 .remove(b'~')
1077 .remove(b'/');
1078
1079/// One ranged read's budget on the fault path (see the agent below).
1080const FAULT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
1081
1082/// The paged VFS's fault-path reader: a SigV4-signed ranged GET over a
1083/// blocking socket. See [`RangeReader`] for why it must not touch a runtime.
1084///
1085/// The credential is the snapshot taken at activation; a credential that
1086/// rotates during a long residency makes later faults fail with 403, which
1087/// surfaces as an I/O error on that read. Refreshing it needs the async
1088/// provider and belongs to a re-activation, not to a fault.
1089/// The fault path over any [`ObjectStore`] that is not native S3: the
1090/// deterministic simulation's store, a directory, a memory store. Reads run
1091/// on one helper thread with its own runtime; the calling thread blocks on
1092/// the reply, which is the fault path's contract. The helper is a thread,
1093/// not a task on any caller's runtime, so the same-runtime deadlocks that
1094/// sank every bridge on the fleet do not apply (`refresh_aws_credential`
1095/// takes the same shape).
1096pub struct StoreRangeReader {
1097 requests: std::sync::mpsc::Sender<RangeRequest>,
1098 prefix: String,
1099}
1100
1101struct RangeRequest {
1102 key: String,
1103 offset: u64,
1104 len: u64,
1105 reply: std::sync::mpsc::Sender<Result<Vec<u8>>>,
1106}
1107
1108impl StoreRangeReader {
1109 pub fn new(store: Arc<dyn ObjectStore>, prefix: String) -> Self {
1110 let (requests, inbox) = std::sync::mpsc::channel::<RangeRequest>();
1111 std::thread::Builder::new()
1112 .name("paged-store-reader".into())
1113 .spawn(move || {
1114 let runtime = tokio::runtime::Builder::new_current_thread()
1115 .enable_all()
1116 .build()
1117 .expect("paged store reader runtime");
1118 for request in inbox {
1119 let path = ObjPath::from(request.key);
1120 let range = request.offset..request.offset + request.len;
1121 let out = runtime
1122 .block_on(store.get_range(&path, range))
1123 .map(|bytes| bytes.to_vec())
1124 .map_err(map_os_error);
1125 let _ = request.reply.send(out);
1126 }
1127 })
1128 .expect("spawn the paged store reader");
1129 Self { requests, prefix }
1130 }
1131}
1132
1133impl RangeReader for StoreRangeReader {
1134 fn read_range(&self, info: &FileInfo, offset: u64, len: u64) -> Result<Vec<u8>> {
1135 if len == 0 {
1136 return Ok(Vec::new());
1137 }
1138 let filename = ltx::format_filename(info.min_txid, info.max_txid);
1139 let key = format!("{}/{:04x}/{filename}", self.prefix, info.level);
1140 let (reply, inbox) = std::sync::mpsc::channel();
1141 let stopped = || Error::Other("the paged store reader stopped".into());
1142 self.requests
1143 .send(RangeRequest {
1144 key,
1145 offset,
1146 len,
1147 reply,
1148 })
1149 .map_err(|_| stopped())?;
1150 inbox.recv().map_err(|_| stopped())?
1151 }
1152}
1153
1154pub struct S3RangeReader {
1155 credential: std::sync::RwLock<Arc<AwsCredential>>,
1156 /// The store's provider when the credential came from an ambient chain
1157 /// (STS, instance roles), which rotates; `None` for static keys.
1158 provider: Option<object_store::aws::AwsCredentialProvider>,
1159 region: String,
1160 base: String,
1161 prefix: String,
1162 agent: ureq::Agent,
1163}
1164
1165impl S3RangeReader {
1166 fn get(&self, url: &str, offset: u64, len: u64) -> Result<Vec<u8>> {
1167 let mut signed = http::Request::builder()
1168 .method("GET")
1169 .uri(url)
1170 .header("range", format!("bytes={offset}-{}", offset + len - 1))
1171 .body(HttpRequestBody::empty())
1172 .map_err(|e| Error::Other(format!("paged: build request: {e}").into()))?;
1173 let credential = self.credential.read().unwrap().clone();
1174 AwsAuthorizer::new(&credential, "s3", &self.region).authorize(&mut signed, None);
1175 let mut request = self.agent.get(url);
1176 for (name, value) in signed.headers() {
1177 // ureq sets Host from the URL itself, identically to the signed
1178 // value; setting it again is refused.
1179 if name != http::header::HOST {
1180 let value = value
1181 .to_str()
1182 .map_err(|e| Error::Other(format!("paged: header: {e}").into()))?;
1183 request = request.header(name.as_str(), value);
1184 }
1185 }
1186 let mut response = request
1187 .call()
1188 .map_err(|e| Error::Io(std::io::Error::other(format!("paged get: {e}"))))?;
1189 if response.status() == http::StatusCode::FORBIDDEN {
1190 return Err(Error::Forbidden);
1191 }
1192 if response.status() != http::StatusCode::PARTIAL_CONTENT {
1193 // S3's error body names the code and, for a signature mismatch,
1194 // the canonical request it computed — the only way to see it.
1195 let status = response.status();
1196 let detail = response
1197 .body_mut()
1198 .with_config()
1199 .limit(8192)
1200 .read_to_string()
1201 .unwrap_or_default();
1202 // Not transient: the retry below is for transport errors only.
1203 return Err(Error::Other(
1204 format!("paged get: {status} for range {offset}+{len} of {url}: {detail}").into(),
1205 ));
1206 }
1207 let body = response
1208 .body_mut()
1209 .with_config()
1210 // ureq's limit is exclusive; the length check below is the real
1211 // bound.
1212 .limit(len + 1)
1213 .read_to_vec()
1214 .map_err(|e| Error::Io(std::io::Error::other(format!("paged body: {e}"))))?;
1215 if body.len() as u64 != len {
1216 return Err(Error::Io(std::io::Error::other(format!(
1217 "paged get: short range body {} of {len}",
1218 body.len()
1219 ))));
1220 }
1221 Ok(body)
1222 }
1223}
1224
1225impl RangeReader for S3RangeReader {
1226 fn read_range(&self, info: &FileInfo, offset: u64, len: u64) -> Result<Vec<u8>> {
1227 if len == 0 {
1228 return Ok(Vec::new());
1229 }
1230 let filename = ltx::format_filename(info.min_txid, info.max_txid);
1231 // SigV4's canonical URI percent-encodes every byte outside the
1232 // unreserved set — a `:` in a cell name is `%3A` — and R2 canonicalizes
1233 // what it receives. Signing the raw path therefore signs a different
1234 // string than the bucket checks (every fault a 403), so the path is
1235 // encoded before it is signed, and sent encoded.
1236 let key = format!("{}/{:04x}/{filename}", self.prefix, info.level);
1237 let key = percent_encoding::utf8_percent_encode(&key, KEY_ENCODE_SET);
1238 let url = format!("{}/{key}", self.base);
1239 // A transport hiccup on a 4KiB read is cheap to retry; a status
1240 // failure is not transient and returns at once.
1241 let mut attempt = 0;
1242 let mut refreshed = false;
1243 loop {
1244 match self.get(&url, offset, len) {
1245 Ok(body) => return Ok(body),
1246 // A rotated ambient credential fails with 403; take a fresh
1247 // one from the provider once, then treat a second 403 as
1248 // final.
1249 Err(Error::Forbidden) if !refreshed && self.provider.is_some() => {
1250 refreshed = true;
1251 match refresh_aws_credential(self.provider.as_ref().unwrap()) {
1252 Some(fresh) => *self.credential.write().unwrap() = fresh,
1253 None => return Err(Error::Forbidden),
1254 }
1255 }
1256 Err(error) if attempt < 1 && matches!(error, Error::Io(_)) => {
1257 attempt += 1;
1258 std::thread::sleep(std::time::Duration::from_millis(100 * attempt));
1259 }
1260 Err(error) => return Err(error),
1261 }
1262 }
1263 }
1264}
1265
1266/// Fetches a fresh credential from an ambient provider, from a thread that
1267/// is not on any runtime: the fault path runs on whatever thread SQLite is
1268/// on, which may be a runtime worker where `block_on` panics, so the async
1269/// provider is driven on a helper thread with its own runtime.
1270pub fn refresh_aws_credential(
1271 provider: &object_store::aws::AwsCredentialProvider,
1272) -> Option<Arc<AwsCredential>> {
1273 let provider = provider.clone();
1274 std::thread::spawn(move || {
1275 let runtime = tokio::runtime::Builder::new_current_thread()
1276 .enable_all()
1277 .build()
1278 .ok()?;
1279 runtime.block_on(provider.get_credential()).ok()
1280 })
1281 .join()
1282 .ok()
1283 .flatten()
1284}