Diffinery

homeflare/celldpublic

celld/crates/ltx/src/client/object_store.rs
1350 lines · 53.1 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 config's S3 store, initialized for replica I/O or when a shared
560 /// store's paged reader needs an ambient credential provider.
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 { Ok(self.s3().await?.clone() as Arc<dyn ObjectStore>) })
600 .await
601 }
602
603 async fn s3(&self) -> Result<&Arc<AmazonS3>> {
604 self.s3
605 .get_or_try_init(|| async { self.config.build_s3() })
606 .await
607 }
608
609 /// A blocking ranged reader over this client's objects for the paged
610 /// VFS. It snapshots the store's credential now (an async fetch on the
611 /// caller's runtime) so each fault can sign its own request on whatever
612 /// thread SQLite is on, with no runtime in the loop.
613 pub async fn blocking_range_reader(&self) -> Result<Box<dyn RangeReader>> {
614 let config = &self.config;
615 // Only native S3 is read by a signed request of our own; any other
616 // store — the deterministic simulation's, a directory, memory —
617 // is read through the store on a helper thread.
618 let store = self.store().await?;
619 if !store.to_string().starts_with("AmazonS3") {
620 return Ok(Box::new(StoreRangeReader::new(
621 store.clone(),
622 config.path.clone(),
623 )));
624 }
625 let mut provider = None;
626 let credential = if !config.access_key_id.is_empty() {
627 Arc::new(AwsCredential {
628 key_id: config.access_key_id.clone(),
629 secret_key: config.secret_access_key.clone(),
630 token: (!config.session_token.is_empty()).then(|| config.session_token.clone()),
631 })
632 } else {
633 // A shared store erases AmazonS3's credential provider. Waiting
634 // for replica I/O to install it leaves every paged restore with
635 // ambient credentials failing. Build it from the same config on
636 // demand; retain its provider so expired role credentials can
637 // refresh during page faults. Static keys need no second store.
638 let s3 = self.s3().await?;
639 provider = Some(s3.credentials().clone());
640 s3.credentials()
641 .get_credential()
642 .await
643 .map_err(map_os_error)?
644 };
645 let region = if config.region.is_empty() {
646 DEFAULT_REGION.to_string()
647 } else {
648 config.region.clone()
649 };
650 // Mirror the store's own addressing so the signed host matches what
651 // the bucket expects: virtual-hosted unless path-style was forced.
652 let base = if config.endpoint.is_empty() {
653 format!("https://{}.s3.{region}.amazonaws.com", config.bucket)
654 } else if config.force_path_style {
655 format!(
656 "{}/{}",
657 config.endpoint.trim_end_matches('/'),
658 config.bucket
659 )
660 } else {
661 let (scheme, host) = config
662 .endpoint
663 .split_once("://")
664 .ok_or_else(|| Error::Other("s3: endpoint has no scheme".into()))?;
665 format!(
666 "{scheme}://{}.{}",
667 config.bucket,
668 host.trim_end_matches('/')
669 )
670 };
671 let tls = ureq::tls::TlsConfig::builder()
672 .disable_verification(config.skip_verify)
673 .build();
674 // A fault runs on the caller's thread — for the actor's queries the
675 // node's core — so this budget is how long one slow object read can
676 // stall every cell on the node. A normal fault is 65-200 ms; 10 s is
677 // fifty times that, and the single retry below bounds a stall at
678 // about 20 s instead of the 90 s three 30 s attempts allowed.
679 let agent = ureq::Agent::config_builder()
680 .timeout_global(Some(FAULT_TIMEOUT))
681 .http_status_as_error(false)
682 .tls_config(tls)
683 .build()
684 .new_agent();
685 Ok(Box::new(S3RangeReader {
686 credential: std::sync::RwLock::new(credential),
687 provider,
688 region,
689 base,
690 prefix: config.path.clone(),
691 agent,
692 }))
693 }
694
695 /// Returns whether the replica epoch prefix contains an object.
696 ///
697 /// The caller needs only an existence proof, so it stops the recursive,
698 /// delimiter-less listing after the first object. An empty or non-empty
699 /// prefix therefore costs one list request instead of one request for each
700 /// compaction level.
701 pub async fn has_any_object(&self) -> Result<bool> {
702 let store = self.store().await?;
703 let prefix = ObjPath::from(self.root_prefix());
704 store
705 .list(Some(&prefix))
706 .next()
707 .await
708 .transpose()
709 .map(|object| object.is_some())
710 .map_err(map_os_error)
711 }
712
713 /// Build the S3 key for an LTX file: `{path}/{level:04x}/{min}-{max}.ltx`.
714 /// Ported from s3/replica_client.go:629, 677, 1040-1042.
715 fn ltx_key(&self, level: i32, min_txid: TXID, max_txid: TXID) -> String {
716 let filename = ltx::format_filename(min_txid, max_txid);
717 format!("{}/{:04x}/{}", self.config.path, level, filename)
718 }
719
720 /// Prefix for listing a level: `{path}/{level:04x}/`.
721 /// Ported from s3/replica_client.go:1363.
722 fn level_prefix(&self, level: i32) -> String {
723 format!("{}/{:04x}/", self.config.path, level)
724 }
725
726 /// Root prefix for delete-all: `{path}/`. (s3/replica_client.go:1114).
727 fn root_prefix(&self) -> String {
728 format!("{}/", self.config.path)
729 }
730
731 /// The highest transaction any level holds, from one listing of the
732 /// whole path. A caller that only needs the watermark, such as a log
733 /// recovery deciding which gathered rows the bucket already covers, pays
734 /// one round trip here instead of one per level.
735 pub async fn max_txid_all_levels(&self) -> Result<TXID> {
736 let store = self.store().await?;
737 let prefix = ObjPath::from(self.root_prefix());
738 let mut listed = store.list(Some(&prefix));
739 let mut max = TXID(0);
740 while let Some(meta) = listed.try_next().await.map_err(map_os_error)? {
741 let name = meta.location.filename().unwrap_or("");
742 if let Ok((_, max_txid)) = ltx::parse_filename(name) {
743 max = max.max(max_txid);
744 }
745 }
746 Ok(max)
747 }
748}
749
750/// Map an `object_store::Error` to `crate::Error`, preserving NotFound as
751/// `io::ErrorKind::NotFound` so callers keep working with the std error kind.
752/// Mirrors `isNotExists` → `os.ErrNotExist` (s3/replica_client.go:647-649,
753/// 1662-1668).
754fn map_os_error(e: object_store::Error) -> Error {
755 match e {
756 object_store::Error::NotFound { .. } => {
757 Error::Io(std::io::Error::new(std::io::ErrorKind::NotFound, e))
758 }
759 other => Error::Other(Box::new(other)),
760 }
761}
762
763#[async_trait::async_trait]
764impl ReplicaClient for ObjectStoreClient {
765 async fn ltx_files(&self, level: i32, seek: TXID) -> Result<Vec<FileInfo>> {
766 self.ltx_files_bounded(level, seek, usize::MAX).await
767 }
768
769 async fn ltx_files_bounded(
770 &self,
771 level: i32,
772 seek: TXID,
773 limit: usize,
774 ) -> Result<Vec<FileInfo>> {
775 if limit == 0 {
776 return Ok(Vec::new());
777 }
778 let store = self.store().await?;
779 let prefix = ObjPath::from(self.level_prefix(level));
780 // The offset ends immediately before every filename with this minimum
781 // TXID. S3 and GCS can push it into the listing request, so an additive
782 // compaction does not scan the complete retained L0 history. The
783 // supported production stores return each page in lexical order. The
784 // compactor validates continuity and fails closed for an unordered
785 // custom store.
786 let offset = ObjPath::from(format!("{}{:016x}", self.level_prefix(level), seek.0));
787 let mut listed = store.list_with_offset(Some(&prefix), &offset);
788 let mut infos = Vec::with_capacity(limit.min(256));
789 while let Some(meta) = listed.try_next().await.map_err(map_os_error)? {
790 let name = meta.location.filename().unwrap_or("");
791 let (min_txid, max_txid) = match ltx::parse_filename(name) {
792 Ok(t) => t,
793 Err(_) => continue, // skip non-LTX keys
794 };
795 if min_txid < seek {
796 continue;
797 }
798 infos.push(FileInfo {
799 level,
800 min_txid,
801 max_txid,
802 size: meta.size as i64,
803 created_at: Some(std::time::SystemTime::from(meta.last_modified)),
804 ..Default::default()
805 });
806 if infos.len() == limit {
807 break;
808 }
809 }
810
811 // Iterator contract: ascending by (level, min_txid, max_txid).
812 infos.sort_by(|a, b| {
813 (a.level, a.min_txid.0, a.max_txid.0).cmp(&(b.level, b.min_txid.0, b.max_txid.0))
814 });
815 Ok(infos)
816 }
817
818 async fn open_ltx_file(&self, level: i32, min_txid: TXID, max_txid: TXID) -> Result<Vec<u8>> {
819 let store = self.store().await?;
820 let key = ObjPath::from(self.ltx_key(level, min_txid, max_txid));
821
822 let result = match store.get(&key).await {
823 Ok(r) => r,
824 Err(object_store::Error::NotFound { .. }) => {
825 return Err(Error::Io(std::io::Error::new(
826 std::io::ErrorKind::NotFound,
827 format!("replica: get object {key}: not found"),
828 )));
829 }
830 Err(e) => return Err(map_os_error(e)),
831 };
832
833 let bytes = result.bytes().await.map_err(map_os_error)?;
834 Ok(bytes.to_vec())
835 }
836
837 async fn read_range(
838 &self,
839 level: i32,
840 min_txid: TXID,
841 max_txid: TXID,
842 offset: u64,
843 len: u64,
844 ) -> Result<Vec<u8>> {
845 let store = self.store().await?;
846 let key = ObjPath::from(self.ltx_key(level, min_txid, max_txid));
847 let options = GetOptions {
848 range: Some(GetRange::Bounded(offset..offset.saturating_add(len))),
849 ..Default::default()
850 };
851 let result = match store.get_opts(&key, options).await {
852 Ok(r) => r,
853 Err(object_store::Error::NotFound { .. }) => {
854 return Err(Error::Io(std::io::Error::new(
855 std::io::ErrorKind::NotFound,
856 format!("replica: get range {key}: not found"),
857 )));
858 }
859 Err(e) => return Err(map_os_error(e)),
860 };
861 let bytes = result.bytes().await.map_err(map_os_error)?;
862 Ok(bytes.to_vec())
863 }
864
865 async fn write_ltx_file(
866 &self,
867 level: i32,
868 min_txid: TXID,
869 max_txid: TXID,
870 data: &[u8],
871 ) -> Result<FileInfo> {
872 let store = self.store().await?;
873
874 // Preserve the LTX header timestamp in the standard Litestream object
875 // metadata. This costs no extra request and lets Litestream perform an
876 // accurate timestamp restore without downloading every candidate file.
877 // The name is per backend, because Azure refuses a hyphen in it.
878 let header = ltx::Header::parse(data)?;
879 let created_at = std::time::UNIX_EPOCH
880 + std::time::Duration::from_millis(header.timestamp.max(0) as u64);
881 let mut attributes = Attributes::new();
882 attributes.insert(
883 Attribute::Metadata(self.config.timestamp_metadata_key.as_str().into()),
884 AttributeValue::from(format_rfc3339_nano(header.timestamp)?),
885 );
886 let key = ObjPath::from(self.ltx_key(level, min_txid, max_txid));
887
888 // Multipart threshold: < 5 MiB → single PUT; ≥ 5 MiB → multipart with
889 // fixed-size parts. Ported from the Go uploader's 5 MiB PartSize default
890 // (s3/replica_client.go:99, brief §5.1).
891 let part_size = self.config.effective_part_size();
892 if data.len() < MULTIPART_THRESHOLD {
893 let payload = PutPayload::from(data.to_vec());
894 let options = PutOptions {
895 attributes,
896 ..Default::default()
897 };
898 store
899 .put_opts(&key, payload, options)
900 .await
901 .map_err(|e| Error::Other(format!("replica: upload to {key}: {e}").into()))?;
902 } else {
903 let options = PutMultipartOptions {
904 attributes,
905 ..Default::default()
906 };
907 let mut upload = store
908 .put_multipart_opts(&key, options)
909 .await
910 .map_err(|e| Error::Other(format!("replica: upload to {key}: {e}").into()))?;
911 // Keep every fallible step inside one result. Otherwise, a new
912 // early return can leave completed parts in the storage service.
913 let upload_result: Result<()> = async {
914 // Upload in fixed-size parts (each ≥ 5 MiB except possibly the
915 // last, matching object_store's part-size requirement).
916 for chunk in data.chunks(part_size.max(MULTIPART_THRESHOLD)) {
917 upload
918 .put_part(PutPayload::from(chunk.to_vec()))
919 .await
920 .map_err(|e| {
921 Error::Other(format!("replica: upload part to {key}: {e}").into())
922 })?;
923 }
924 upload.complete().await.map_err(|e| {
925 Error::Other(format!("replica: complete upload to {key}: {e}").into())
926 })?;
927 Ok(())
928 }
929 .await;
930 if let Err(upload_error) = upload_result {
931 if let Err(abort_error) = upload.abort().await {
932 tracing::warn!(
933 %abort_error,
934 key = %key,
935 "failed LTX multipart upload could not be aborted"
936 );
937 }
938 return Err(upload_error);
939 }
940 }
941
942 Ok(FileInfo {
943 level,
944 min_txid,
945 max_txid,
946 size: data.len() as i64,
947 created_at: Some(created_at),
948 ..Default::default()
949 })
950 }
951
952 async fn write_ltx_file_from_file(
953 &self,
954 level: i32,
955 min_txid: TXID,
956 max_txid: TXID,
957 file: crate::host::HostFile,
958 host: crate::LtxHost,
959 ) -> Result<FileInfo> {
960 let part_size = self.config.effective_part_size().max(MULTIPART_THRESHOLD);
961 let (mut file, first, size) = super::read_upload_chunk(file, &host, 0, part_size).await?;
962 if size < MULTIPART_THRESHOLD as u64 {
963 return self.write_ltx_file(level, min_txid, max_txid, &first).await;
964 }
965 let header = ltx::Header::parse(&first)?;
966 let mut attributes = Attributes::new();
967 attributes.insert(
968 Attribute::Metadata(self.config.timestamp_metadata_key.as_str().into()),
969 AttributeValue::from(format_rfc3339_nano(header.timestamp)?),
970 );
971 let store = self.store().await?;
972 let key = ObjPath::from(self.ltx_key(level, min_txid, max_txid));
973 let mut upload = store
974 .put_multipart_opts(
975 &key,
976 PutMultipartOptions {
977 attributes,
978 ..Default::default()
979 },
980 )
981 .await
982 .map_err(map_os_error)?;
983 let upload_result: Result<()> = async {
984 let mut offset = first.len() as u64;
985 upload
986 .put_part(PutPayload::from(first))
987 .await
988 .map_err(map_os_error)?;
989 while offset < size {
990 let (next_file, bytes, _) =
991 super::read_upload_chunk(file, &host, offset, part_size).await?;
992 file = next_file;
993 offset += bytes.len() as u64;
994 upload
995 .put_part(PutPayload::from(bytes))
996 .await
997 .map_err(map_os_error)?;
998 }
999 upload.complete().await.map_err(map_os_error)?;
1000 Ok(())
1001 }
1002 .await;
1003 if let Err(error) = upload_result {
1004 if let Err(abort_error) = upload.abort().await {
1005 tracing::warn!(%abort_error, %key, "failed LTX multipart upload could not be aborted");
1006 }
1007 return Err(error);
1008 }
1009 Ok(FileInfo {
1010 level,
1011 min_txid,
1012 max_txid,
1013 size: size as i64,
1014 created_at: Some(
1015 std::time::UNIX_EPOCH
1016 + std::time::Duration::from_millis(header.timestamp.max(0) as u64),
1017 ),
1018 ..Default::default()
1019 })
1020 }
1021
1022 async fn delete_ltx_files(&self, files: &[FileInfo]) -> Result<()> {
1023 if files.is_empty() {
1024 return Ok(());
1025 }
1026 let store = self.store().await?;
1027
1028 // Build the key list, then delete in batches of MAX_KEYS via the
1029 // store's delete_stream, surfacing per-key errors (brief §5.5).
1030 let keys: Vec<ObjPath> = files
1031 .iter()
1032 .map(|info| ObjPath::from(self.ltx_key(info.level, info.min_txid, info.max_txid)))
1033 .collect();
1034
1035 for batch in keys.chunks(MAX_KEYS) {
1036 delete_batch(store.as_ref(), batch, /*ignore_missing=*/ true).await?;
1037 }
1038 Ok(())
1039 }
1040
1041 async fn delete_all(&self) -> Result<()> {
1042 let store = self.store().await?;
1043 let prefix = ObjPath::from(self.root_prefix());
1044
1045 // List everything under the path prefix, then batch-delete.
1046 // (s3/replica_client.go:1104-1148).
1047 let keys: Vec<ObjPath> = store
1048 .list(Some(&prefix))
1049 .map_ok(|m| m.location)
1050 .map_err(map_os_error)
1051 .try_collect()
1052 .await?;
1053
1054 for batch in keys.chunks(MAX_KEYS) {
1055 delete_batch(store.as_ref(), batch, /*ignore_missing=*/ true).await?;
1056 }
1057 Ok(())
1058 }
1059}
1060
1061/// Delete a batch of keys via `delete_stream`, surfacing per-key errors.
1062///
1063/// When `ignore_missing` is set, `NotFound` is tolerated (delete is idempotent —
1064/// the file client swallows ENOENT the same way), but every other per-key error
1065/// is returned (brief §5.5: do not silently swallow partial failures).
1066async fn delete_batch(
1067 store: &dyn ObjectStore,
1068 keys: &[ObjPath],
1069 ignore_missing: bool,
1070) -> Result<()> {
1071 if keys.is_empty() {
1072 return Ok(());
1073 }
1074 let owned: Vec<ObjPath> = keys.to_vec();
1075 let stream = futures_util::stream::iter(owned.into_iter().map(Ok));
1076 let mut results = store.delete_stream(stream.boxed());
1077 while let Some(res) = results.next().await {
1078 match res {
1079 Ok(_) => {}
1080 Err(object_store::Error::NotFound { .. }) if ignore_missing => {}
1081 Err(e) => return Err(map_os_error(e)),
1082 }
1083 }
1084 Ok(())
1085}
1086
1087/// Format a Unix-millisecond timestamp like Go's `time.RFC3339Nano`.
1088fn format_rfc3339_nano(unix_millis: i64) -> Result<String> {
1089 let mut timestamp = DateTime::from_timestamp_millis(unix_millis.max(0))
1090 .ok_or_else(|| Error::Other("LTX timestamp is outside the RFC3339 range".into()))?
1091 .to_rfc3339_opts(SecondsFormat::AutoSi, true);
1092
1093 // Chrono keeps millisecond precision as three digits. Go removes trailing
1094 // zeros, so `.500Z` becomes `.5Z`.
1095 if timestamp.contains('.') {
1096 // The pop must stay outside debug_assert!, which vanishes in release
1097 // builds and would leave the Z in place to be doubled below.
1098 let suffix = timestamp.pop();
1099 debug_assert_eq!(suffix, Some('Z'));
1100 while timestamp.ends_with('0') {
1101 timestamp.pop();
1102 }
1103 timestamp.push('Z');
1104 }
1105 Ok(timestamp)
1106}
1107
1108#[doc(hidden)]
1109pub mod internal {
1110 use super::*;
1111
1112 pub const METADATA_KEY_TIMESTAMP: &str = super::METADATA_KEY_TIMESTAMP;
1113 pub const METADATA_KEY_TIMESTAMP_UNDERSCORE: &str = super::METADATA_KEY_TIMESTAMP_UNDERSCORE;
1114
1115 pub fn format_rfc3339_nano(unix_millis: i64) -> Result<String> {
1116 super::format_rfc3339_nano(unix_millis)
1117 }
1118
1119 pub fn ltx_key(client: &ObjectStoreClient, level: i32, min: TXID, max: TXID) -> String {
1120 client.ltx_key(level, min, max)
1121 }
1122
1123 pub fn level_prefix(client: &ObjectStoreClient, level: i32) -> String {
1124 client.level_prefix(level)
1125 }
1126
1127 pub fn root_prefix(client: &ObjectStoreClient) -> String {
1128 client.root_prefix()
1129 }
1130
1131 pub fn map_os_error(error: object_store::Error) -> Error {
1132 super::map_os_error(error)
1133 }
1134}
1135
1136/// Bytes the SigV4 canonical URI leaves unencoded, plus the segment
1137/// delimiter: A-Z a-z 0-9 `-` `.` `_` `~` and `/`.
1138const KEY_ENCODE_SET: &percent_encoding::AsciiSet = &percent_encoding::NON_ALPHANUMERIC
1139 .remove(b'-')
1140 .remove(b'.')
1141 .remove(b'_')
1142 .remove(b'~')
1143 .remove(b'/');
1144
1145/// One ranged read's budget on the fault path (see the agent below).
1146const FAULT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
1147
1148/// The paged VFS's fault-path reader: a SigV4-signed ranged GET over a
1149/// blocking socket. See [`RangeReader`] for why it must not touch a runtime.
1150///
1151/// The credential is the snapshot taken at activation; a credential that
1152/// rotates during a long residency makes later faults fail with 403, which
1153/// surfaces as an I/O error on that read. Refreshing it needs the async
1154/// provider and belongs to a re-activation, not to a fault.
1155/// The fault path over any [`ObjectStore`] that is not native S3: the
1156/// deterministic simulation's store, a directory, a memory store. Reads run
1157/// on one helper thread with its own runtime; the calling thread blocks on
1158/// the reply, which is the fault path's contract. The helper is a thread,
1159/// not a task on any caller's runtime, so the same-runtime deadlocks that
1160/// sank every bridge on the fleet do not apply (`refresh_aws_credential`
1161/// takes the same shape).
1162pub struct StoreRangeReader {
1163 requests: std::sync::mpsc::Sender<RangeRequest>,
1164 prefix: String,
1165}
1166
1167struct RangeRequest {
1168 key: String,
1169 offset: u64,
1170 len: u64,
1171 reply: std::sync::mpsc::Sender<Result<Vec<u8>>>,
1172}
1173
1174impl StoreRangeReader {
1175 pub fn new(store: Arc<dyn ObjectStore>, prefix: String) -> Self {
1176 let (requests, inbox) = std::sync::mpsc::channel::<RangeRequest>();
1177 std::thread::Builder::new()
1178 .name("paged-store-reader".into())
1179 .spawn(move || {
1180 let runtime = tokio::runtime::Builder::new_current_thread()
1181 .enable_all()
1182 .build()
1183 .expect("paged store reader runtime");
1184 for request in inbox {
1185 let path = ObjPath::from(request.key);
1186 let range = request.offset..request.offset + request.len;
1187 let out = runtime
1188 .block_on(store.get_range(&path, range))
1189 .map(|bytes| bytes.to_vec())
1190 .map_err(map_os_error);
1191 let _ = request.reply.send(out);
1192 }
1193 })
1194 .expect("spawn the paged store reader");
1195 Self { requests, prefix }
1196 }
1197}
1198
1199impl RangeReader for StoreRangeReader {
1200 fn read_range(&self, info: &FileInfo, offset: u64, len: u64) -> Result<Vec<u8>> {
1201 if len == 0 {
1202 return Ok(Vec::new());
1203 }
1204 let filename = ltx::format_filename(info.min_txid, info.max_txid);
1205 let key = format!("{}/{:04x}/{filename}", self.prefix, info.level);
1206 let (reply, inbox) = std::sync::mpsc::channel();
1207 let stopped = || Error::Other("the paged store reader stopped".into());
1208 self.requests
1209 .send(RangeRequest {
1210 key,
1211 offset,
1212 len,
1213 reply,
1214 })
1215 .map_err(|_| stopped())?;
1216 inbox.recv().map_err(|_| stopped())?
1217 }
1218}
1219
1220pub struct S3RangeReader {
1221 credential: std::sync::RwLock<Arc<AwsCredential>>,
1222 /// The store's provider when the credential came from an ambient chain
1223 /// (STS, instance roles), which rotates; `None` for static keys.
1224 provider: Option<object_store::aws::AwsCredentialProvider>,
1225 region: String,
1226 base: String,
1227 prefix: String,
1228 agent: ureq::Agent,
1229}
1230
1231impl S3RangeReader {
1232 fn get(&self, url: &str, offset: u64, len: u64) -> Result<Vec<u8>> {
1233 let mut signed = http::Request::builder()
1234 .method("GET")
1235 .uri(url)
1236 .header("range", format!("bytes={offset}-{}", offset + len - 1))
1237 .body(HttpRequestBody::empty())
1238 .map_err(|e| Error::Other(format!("paged: build request: {e}").into()))?;
1239 let credential = self.credential.read().unwrap().clone();
1240 AwsAuthorizer::new(&credential, "s3", &self.region).authorize(&mut signed, None);
1241 let mut request = self.agent.get(url);
1242 for (name, value) in signed.headers() {
1243 // ureq sets Host from the URL itself, identically to the signed
1244 // value; setting it again is refused.
1245 if name != http::header::HOST {
1246 let value = value
1247 .to_str()
1248 .map_err(|e| Error::Other(format!("paged: header: {e}").into()))?;
1249 request = request.header(name.as_str(), value);
1250 }
1251 }
1252 let mut response = request
1253 .call()
1254 .map_err(|e| Error::Io(std::io::Error::other(format!("paged get: {e}"))))?;
1255 if response.status() == http::StatusCode::FORBIDDEN {
1256 return Err(Error::Forbidden);
1257 }
1258 if response.status() != http::StatusCode::PARTIAL_CONTENT {
1259 // S3's error body names the code and, for a signature mismatch,
1260 // the canonical request it computed — the only way to see it.
1261 let status = response.status();
1262 let detail = response
1263 .body_mut()
1264 .with_config()
1265 .limit(8192)
1266 .read_to_string()
1267 .unwrap_or_default();
1268 // Not transient: the retry below is for transport errors only.
1269 return Err(Error::Other(
1270 format!("paged get: {status} for range {offset}+{len} of {url}: {detail}").into(),
1271 ));
1272 }
1273 let body = response
1274 .body_mut()
1275 .with_config()
1276 // ureq's limit is exclusive; the length check below is the real
1277 // bound.
1278 .limit(len + 1)
1279 .read_to_vec()
1280 .map_err(|e| Error::Io(std::io::Error::other(format!("paged body: {e}"))))?;
1281 if body.len() as u64 != len {
1282 return Err(Error::Io(std::io::Error::other(format!(
1283 "paged get: short range body {} of {len}",
1284 body.len()
1285 ))));
1286 }
1287 Ok(body)
1288 }
1289}
1290
1291impl RangeReader for S3RangeReader {
1292 fn read_range(&self, info: &FileInfo, offset: u64, len: u64) -> Result<Vec<u8>> {
1293 if len == 0 {
1294 return Ok(Vec::new());
1295 }
1296 let filename = ltx::format_filename(info.min_txid, info.max_txid);
1297 // SigV4's canonical URI percent-encodes every byte outside the
1298 // unreserved set — a `:` in a cell name is `%3A` — and R2 canonicalizes
1299 // what it receives. Signing the raw path therefore signs a different
1300 // string than the bucket checks (every fault a 403), so the path is
1301 // encoded before it is signed, and sent encoded.
1302 let key = format!("{}/{:04x}/{filename}", self.prefix, info.level);
1303 let key = percent_encoding::utf8_percent_encode(&key, KEY_ENCODE_SET);
1304 let url = format!("{}/{key}", self.base);
1305 // A transport hiccup on a 4KiB read is cheap to retry; a status
1306 // failure is not transient and returns at once.
1307 let mut attempt = 0;
1308 let mut refreshed = false;
1309 loop {
1310 match self.get(&url, offset, len) {
1311 Ok(body) => return Ok(body),
1312 // A rotated ambient credential fails with 403; take a fresh
1313 // one from the provider once, then treat a second 403 as
1314 // final.
1315 Err(Error::Forbidden) if !refreshed && self.provider.is_some() => {
1316 refreshed = true;
1317 match refresh_aws_credential(self.provider.as_ref().unwrap()) {
1318 Some(fresh) => *self.credential.write().unwrap() = fresh,
1319 None => return Err(Error::Forbidden),
1320 }
1321 }
1322 Err(error) if attempt < 1 && matches!(error, Error::Io(_)) => {
1323 attempt += 1;
1324 std::thread::sleep(std::time::Duration::from_millis(100 * attempt));
1325 }
1326 Err(error) => return Err(error),
1327 }
1328 }
1329 }
1330}
1331
1332/// Fetches a fresh credential from an ambient provider, from a thread that
1333/// is not on any runtime: the fault path runs on whatever thread SQLite is
1334/// on, which may be a runtime worker where `block_on` panics, so the async
1335/// provider is driven on a helper thread with its own runtime.
1336pub fn refresh_aws_credential(
1337 provider: &object_store::aws::AwsCredentialProvider,
1338) -> Option<Arc<AwsCredential>> {
1339 let provider = provider.clone();
1340 std::thread::spawn(move || {
1341 let runtime = tokio::runtime::Builder::new_current_thread()
1342 .enable_all()
1343 .build()
1344 .ok()?;
1345 runtime.block_on(provider.get_credential()).ok()
1346 })
1347 .join()
1348 .ok()
1349 .flatten()
1350}