1use std::fmt;
4use std::io;
5use std::path::PathBuf;
6use std::sync::{Arc, Mutex};
7use std::time::{Duration, SystemTime};
8
9use tracing::info;
10
11use super::backend::{S3Backend, Shared};
12use super::cache::MetaCache;
13use super::cachedir::{CacheDir, Recovered, cache_error, identity};
14use super::client::{ListRequest, Location, S3Client, Settings};
15use super::entry::{Entry, Own};
16use super::error::S3Error;
17use super::jobs::{Guard, Jobs};
18use super::keys::{MAX_KEY_LEN, dir_prefix};
19use super::meta::same_times;
20use super::overlay::Overlay;
21use super::parts::{MAX_PART_SIZE, MIN_PART_SIZE};
22use super::readahead::{MAX_CHUNK, MIN_CHUNK, ReadAhead};
23use super::retry::Retry;
24use super::sigv4::Credentials;
25
26const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
27const DEFAULT_METADATA_TTL: Duration = Duration::from_secs(30);
28const DEFAULT_LISTING_METADATA_MAX: usize = 1000;
29const DEFAULT_UPLOAD_DELAY: Duration = Duration::from_secs(5);
30const DEFAULT_PART_SIZE: u64 = 16 << 20;
31const DEFAULT_UPLOAD_CONCURRENCY: usize = 4;
32const DEFAULT_READ_CHUNK: u32 = 8 << 20;
33const DEFAULT_MAX_DIR_RENAME_OBJECTS: usize = 10_000;
34
35pub struct S3BackendBuilder {
38 endpoint: String,
39 region: String,
40 bucket: String,
41 credentials: Option<Credentials>,
42 prefix: String,
43 path_style: Option<bool>,
44 cache_dir: Option<PathBuf>,
45 read_only: bool,
46 case_insensitive: bool,
47 request_timeout: Duration,
48 metadata_ttl: Duration,
49 listing_metadata_max: usize,
50 upload_delay: Duration,
51 part_size: u64,
52 upload_concurrency: usize,
53 read_chunk: u32,
54 max_dir_rename_objects: usize,
55 #[cfg(test)]
57 held_uploads: bool,
58}
59
60impl fmt::Debug for S3BackendBuilder {
61 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62 f.debug_struct("S3BackendBuilder")
63 .field("endpoint", &origin(&self.endpoint))
64 .field("region", &self.region)
65 .field("bucket", &self.bucket)
66 .field("prefix", &self.prefix)
67 .finish_non_exhaustive()
68 }
69}
70
71fn origin(endpoint: &str) -> String {
74 let start = endpoint.find("://").map_or(0, |at| at + 3);
75 let end = endpoint[start..]
76 .find(['/', '?', '#'])
77 .map_or(endpoint.len(), |at| start + at);
78 let host = endpoint[start..end]
79 .rsplit_once('@')
80 .map_or(&endpoint[start..end], |(_, host)| host);
81 format!("{}{host}", &endpoint[..start])
82}
83
84impl S3Backend {
85 pub fn builder(
89 endpoint: impl Into<String>,
90 region: impl Into<String>,
91 bucket: impl Into<String>,
92 ) -> S3BackendBuilder {
93 S3BackendBuilder {
94 endpoint: endpoint.into(),
95 region: region.into(),
96 bucket: bucket.into(),
97 credentials: None,
98 prefix: String::new(),
99 path_style: None,
100 cache_dir: None,
101 read_only: false,
102 case_insensitive: true,
103 request_timeout: DEFAULT_REQUEST_TIMEOUT,
104 metadata_ttl: DEFAULT_METADATA_TTL,
105 listing_metadata_max: DEFAULT_LISTING_METADATA_MAX,
106 upload_delay: DEFAULT_UPLOAD_DELAY,
107 part_size: DEFAULT_PART_SIZE,
108 upload_concurrency: DEFAULT_UPLOAD_CONCURRENCY,
109 read_chunk: DEFAULT_READ_CHUNK,
110 max_dir_rename_objects: DEFAULT_MAX_DIR_RENAME_OBJECTS,
111 #[cfg(test)]
112 held_uploads: false,
113 }
114 }
115}
116
117impl S3BackendBuilder {
118 #[must_use]
120 pub fn credentials(
121 mut self,
122 access_key: impl Into<String>,
123 secret_key: impl Into<String>,
124 ) -> Self {
125 let session_token = self.credentials.take().and_then(|c| c.session_token);
126 self.credentials = Some(Credentials {
127 access_key: access_key.into(),
128 secret_key: secret_key.into(),
129 session_token,
130 });
131 self
132 }
133
134 #[must_use]
136 pub fn session_token(mut self, token: impl Into<String>) -> Self {
137 let token = Some(token.into());
138 match &mut self.credentials {
139 Some(credentials) => credentials.session_token = token,
140 None => {
141 self.credentials = Some(Credentials {
142 access_key: String::new(),
143 secret_key: String::new(),
144 session_token: token,
145 });
146 }
147 }
148 self
149 }
150
151 #[must_use]
154 pub fn prefix(mut self, prefix: impl AsRef<str>) -> Self {
155 self.prefix = prefix.as_ref().trim_matches('/').to_owned();
156 self
157 }
158
159 #[must_use]
164 pub fn path_style(mut self, path_style: bool) -> Self {
165 self.path_style = Some(path_style);
166 self
167 }
168
169 #[must_use]
179 pub fn cache_dir(mut self, dir: impl Into<PathBuf>) -> Self {
180 self.cache_dir = Some(dir.into());
181 self
182 }
183
184 #[must_use]
187 pub fn read_only(mut self) -> Self {
188 self.read_only = true;
189 self
190 }
191
192 #[must_use]
201 pub fn case_insensitive(mut self, case_insensitive: bool) -> Self {
202 self.case_insensitive = case_insensitive;
203 self
204 }
205
206 #[must_use]
209 pub fn request_timeout(mut self, timeout: Duration) -> Self {
210 self.request_timeout = timeout;
211 self
212 }
213
214 #[must_use]
217 pub fn metadata_ttl(mut self, ttl: Duration) -> Self {
218 self.metadata_ttl = ttl;
219 self
220 }
221
222 #[must_use]
229 pub fn listing_metadata_max(mut self, max: usize) -> Self {
230 self.listing_metadata_max = max;
231 self
232 }
233
234 #[must_use]
246 pub fn upload_delay(mut self, delay: Duration) -> Self {
247 self.upload_delay = delay;
248 self
249 }
250
251 #[must_use]
256 pub fn part_size(mut self, bytes: u64) -> Self {
257 self.part_size = bytes;
258 self
259 }
260
261 #[must_use]
265 pub fn upload_concurrency(mut self, concurrency: usize) -> Self {
266 self.upload_concurrency = concurrency;
267 self
268 }
269
270 #[must_use]
278 pub fn read_chunk(mut self, bytes: u32) -> Self {
279 self.read_chunk = bytes;
280 self
281 }
282
283 #[must_use]
290 pub fn max_dir_rename_objects(mut self, max: usize) -> Self {
291 self.max_dir_rename_objects = max;
292 self
293 }
294
295 #[cfg(test)]
298 #[must_use]
299 pub(crate) fn held_uploads(mut self, held: bool) -> Self {
300 self.held_uploads = held;
301 self
302 }
303
304 pub async fn build(self) -> Result<S3Backend, S3Error> {
330 let credentials = self.check()?;
331 let local = match &self.cache_dir {
332 None => None,
333 Some(dir) => {
334 let dir = dir.clone();
335 let who = identity(
336 &origin(&self.endpoint),
337 &self.bucket,
338 &self.prefix,
339 self.case_insensitive,
340 );
341 let opened = tokio::task::spawn_blocking(move || CacheDir::open(&dir, &who))
342 .await
343 .map_err(|e| cache_error(io::Error::other(e)))??;
344 Some(Arc::new(opened))
345 }
346 };
347 let mut settings = Settings::new(
348 Location {
349 endpoint: self.endpoint,
350 region: self.region,
351 bucket: self.bucket,
352 },
353 credentials,
354 );
355 settings.path_style = self.path_style;
356 let client = tokio::task::spawn_blocking(move || S3Client::new(settings))
358 .await
359 .map_err(S3Error::transport)??;
360
361 let root = dir_prefix(&self.prefix);
362 let request = ListRequest {
363 prefix: &root,
364 delimited: false,
365 continuation_token: None,
366 max_keys: Some(1),
367 };
368 client
369 .list_objects(&request, Retry::within(self.request_timeout))
370 .await?;
371
372 let recovered = match &local {
373 None => Recovered::default(),
374 Some(local) => {
375 let local = Arc::clone(local);
376 let (prefix, fold) = (self.prefix.clone(), self.case_insensitive);
377 tokio::task::spawn_blocking(move || local.recover(&prefix, fold))
378 .await
379 .map_err(|e| cache_error(io::Error::other(e)))?
380 .map_err(cache_error)?
381 }
382 };
383
384 let built = SystemTime::now();
385 let ahead = Arc::new(ReadAhead::new());
386 let overlay = Overlay::new(self.case_insensitive, self.upload_delay);
387 let entries = recovered
388 .entries
389 .into_iter()
390 .map(|(record, data)| Entry::recovered(record, data, &ahead))
391 .collect();
392 let restored = overlay.install(entries, recovered.tombstones);
393 if restored > 0 {
394 info!(
395 entries = restored,
396 "entries restored from the cache directory"
397 );
398 }
399
400 let jobs = Jobs::new(self.part_size, self.upload_concurrency);
401 #[cfg(test)]
402 jobs.held
403 .store(self.held_uploads, std::sync::atomic::Ordering::SeqCst);
404 let shared = Arc::new(Shared {
405 client,
406 prefix: self.prefix,
407 case_insensitive: self.case_insensitive,
408 request_timeout: self.request_timeout,
409 listing_metadata_max: self.listing_metadata_max,
410 head_concurrency: head_concurrency(self.upload_concurrency),
411 built,
412 cache: Mutex::new(MetaCache::new(self.metadata_ttl, self.case_insensitive)),
413 read_chunk: u64::from(self.read_chunk),
414 max_dir_rename_objects: self.max_dir_rename_objects,
415 ahead,
416 read_only: self.read_only,
417 overlay,
418 local,
419 root_own: Mutex::new(Own {
420 times: same_times(built),
421 attributes: 0,
422 }),
423 jobs,
424 });
425 let worker = Arc::new(Guard::start(&shared));
426 Ok(S3Backend {
427 shared,
428 _worker: worker,
429 })
430 }
431
432 fn check(&self) -> Result<Credentials, S3Error> {
433 let credentials = match &self.credentials {
434 Some(credentials) if !credentials.access_key.is_empty() => credentials,
435 Some(_) => {
436 return Err(S3Error::InvalidArgument("the access key is empty"));
437 }
438 None => return Err(S3Error::InvalidArgument("the credentials are not set")),
439 };
440 if credentials.secret_key.is_empty() {
441 return Err(S3Error::InvalidArgument("the secret key is empty"));
442 }
443 if credentials.session_token.as_deref() == Some("") {
444 return Err(S3Error::InvalidArgument("the session token is empty"));
445 }
446 if self.request_timeout.is_zero() {
447 return Err(S3Error::InvalidArgument("the request timeout is zero"));
448 }
449 if self.upload_concurrency == 0 {
450 return Err(S3Error::InvalidArgument("the upload concurrency is zero"));
451 }
452 if !(MIN_PART_SIZE..=MAX_PART_SIZE).contains(&self.part_size) {
453 return Err(S3Error::InvalidArgument(
454 "the part size is not between 5 MiB and 5 GiB",
455 ));
456 }
457 if !(MIN_CHUNK..=MAX_CHUNK).contains(&self.read_chunk) {
458 return Err(S3Error::InvalidArgument(
459 "the read chunk is not between 64 KiB and 32 MiB",
460 ));
461 }
462 if self
463 .prefix
464 .split('/')
465 .any(|name| name.is_empty() && !self.prefix.is_empty() || matches!(name, "." | ".."))
466 {
467 return Err(S3Error::InvalidArgument(
468 "the prefix has an empty, . or .. component",
469 ));
470 }
471 if dir_prefix(&self.prefix).len() >= MAX_KEY_LEN {
472 return Err(S3Error::InvalidArgument(
473 "the prefix is too long to leave room for a name",
474 ));
475 }
476 match (self.read_only, &self.cache_dir) {
477 (false, None) => {
478 return Err(S3Error::InvalidArgument(
479 "the cache directory is not set; call cache_dir() or read_only()",
480 ));
481 }
482 (true, Some(_)) => {
483 return Err(S3Error::InvalidArgument(
484 "a read-only backend has no use for a cache directory",
485 ));
486 }
487 _ => {}
488 }
489 Ok(credentials.clone())
490 }
491}
492
493const MAX_HEAD_CONCURRENCY: usize = 64;
495
496fn head_concurrency(upload_concurrency: usize) -> usize {
499 upload_concurrency
500 .saturating_mul(4)
501 .min(MAX_HEAD_CONCURRENCY)
502}
503
504#[cfg(test)]
505mod tests {
506 use super::*;
507
508 fn builder() -> S3BackendBuilder {
509 S3Backend::builder("http://127.0.0.1:1", "us-east-1", "bucket")
510 .credentials("access-key-id", "secret-key-value")
511 .read_only()
512 }
513
514 fn refusal(builder: S3BackendBuilder) -> &'static str {
515 match builder.check() {
516 Err(S3Error::InvalidArgument(why)) => why,
517 other => panic!("not refused: {:?}", other.map(|_| ())),
518 }
519 }
520
521 #[test]
522 fn the_defaults_are_valid() {
523 let credentials = builder().check().unwrap();
524 assert_eq!(credentials.access_key, "access-key-id");
525 assert_eq!(credentials.session_token, None);
526 }
527
528 #[test]
529 fn a_prefix_loses_its_outer_slashes() {
530 for (given, kept) in [
531 ("photos", "photos"),
532 ("/photos/", "photos"),
533 ("///a/b///", "a/b"),
534 ("a/b", "a/b"),
535 ("", ""),
536 ("/", ""),
537 ] {
538 assert_eq!(builder().prefix(given).prefix, kept, "{given:?}");
539 assert!(builder().prefix(given).check().is_ok(), "{given:?}");
540 }
541 }
542
543 #[test]
544 fn a_prefix_with_an_empty_or_dot_component_is_refused() {
545 for prefix in ["a//b", "a/./b", "a/../b", "./a", "a/..", "."] {
546 assert!(
547 refusal(builder().prefix(prefix)).contains("prefix"),
548 "{prefix:?}"
549 );
550 }
551 assert!(builder().prefix("a.b/..c/d..").check().is_ok());
552 }
553
554 #[test]
555 fn a_prefix_that_leaves_no_room_for_a_name_is_refused() {
556 let longest = "p".repeat(MAX_KEY_LEN - 2);
557 assert!(builder().prefix(&longest).check().is_ok());
558 let nested = format!("{}/{}", "p".repeat(500), "q".repeat(MAX_KEY_LEN - 2 - 501));
559 assert!(builder().prefix(&nested).check().is_ok());
560
561 let too_long = "p".repeat(MAX_KEY_LEN - 1);
562 assert!(refusal(builder().prefix(&too_long)).contains("prefix"));
563 let nested = format!("{}/{}", "p".repeat(500), "q".repeat(MAX_KEY_LEN - 1 - 501));
564 assert!(refusal(builder().prefix(&nested)).contains("prefix"));
565 }
566
567 #[test]
568 fn credentials_are_required_and_not_empty() {
569 let bare = S3Backend::builder("http://127.0.0.1:1", "r", "b").read_only();
570 assert!(refusal(bare).contains("credentials"));
571 assert!(refusal(builder().credentials("", "s")).contains("access key"));
572 assert!(refusal(builder().credentials("a", "")).contains("secret key"));
573 assert!(refusal(builder().session_token("")).contains("session token"));
574 let token_alone = S3Backend::builder("http://x", "r", "b")
575 .session_token("t")
576 .read_only();
577 assert!(refusal(token_alone).contains("access key"));
578 }
579
580 #[test]
581 fn a_session_token_survives_credentials_set_after_it() {
582 let set = builder().session_token("t").credentials("a", "s");
583 let credentials = set.check().unwrap();
584 assert_eq!(credentials.session_token.as_deref(), Some("t"));
585 assert_eq!(credentials.access_key, "a");
586 let before = builder().credentials("a", "s").session_token("t");
587 assert_eq!(before.check().unwrap().session_token.as_deref(), Some("t"));
588 }
589
590 #[test]
591 fn zero_limits_are_refused() {
592 assert!(refusal(builder().request_timeout(Duration::ZERO)).contains("timeout"));
593 assert!(refusal(builder().upload_concurrency(0)).contains("concurrency"));
594 assert!(
595 builder()
596 .metadata_ttl(Duration::ZERO)
597 .listing_metadata_max(0)
598 .check()
599 .is_ok()
600 );
601 }
602
603 #[test]
604 fn the_read_chunk_is_between_64_kib_and_32_mib() {
605 for bytes in [0, 1, MIN_CHUNK - 1, MAX_CHUNK + 1, u32::MAX] {
606 assert!(
607 refusal(builder().read_chunk(bytes)).contains("read chunk"),
608 "{bytes}"
609 );
610 }
611 for bytes in [MIN_CHUNK, DEFAULT_READ_CHUNK, MAX_CHUNK] {
612 assert!(builder().read_chunk(bytes).check().is_ok(), "{bytes}");
613 }
614 }
615
616 #[test]
617 fn a_writable_backend_needs_a_cache_directory_and_a_read_only_one_refuses_it() {
618 let writable = S3Backend::builder("http://127.0.0.1:1", "r", "b").credentials("a", "s");
619 let why = refusal(writable);
620 assert!(why.contains("cache_dir()"), "{why}");
621 assert!(why.contains("read_only()"), "{why}");
622
623 let both = builder().cache_dir("cache");
624 assert!(refusal(both).contains("read-only"));
625
626 let writable = S3Backend::builder("http://127.0.0.1:1", "r", "b")
627 .credentials("a", "s")
628 .cache_dir("cache");
629 assert!(writable.check().is_ok());
630 }
631
632 #[test]
633 fn the_part_size_is_between_5_mib_and_5_gib() {
634 assert!(builder().check().is_ok(), "the default");
635 for ok in [5 << 20, (5 << 20) + 1, 64 << 20, 5 << 30] {
636 assert!(builder().part_size(ok).check().is_ok(), "{ok}");
637 }
638 for refused in [0, 1, (5 << 20) - 1, (5 << 30) + 1, u64::MAX] {
639 assert!(
640 refusal(builder().part_size(refused)).contains("part size"),
641 "{refused}"
642 );
643 }
644 }
645
646 #[test]
647 fn head_requests_follow_the_upload_concurrency_within_a_bound() {
648 assert_eq!(head_concurrency(1), 4);
649 assert_eq!(head_concurrency(4), 16);
650 assert_eq!(head_concurrency(16), 64);
651 assert_eq!(head_concurrency(17), 64);
652 assert_eq!(head_concurrency(usize::MAX), 64);
653 }
654
655 #[test]
656 fn the_origin_of_an_endpoint_has_no_user_name_password_path_or_query() {
657 for (endpoint, shown) in [
658 ("https://store.example", "https://store.example"),
659 ("http://127.0.0.1:9000", "http://127.0.0.1:9000"),
660 (
661 "https://user:pass@store.example:9000",
662 "https://store.example:9000",
663 ),
664 (
665 "https://user@store.example/path?a=b@c",
666 "https://store.example",
667 ),
668 ("https://a@b@store.example", "https://store.example"),
669 ("https://store.example/a@b", "https://store.example"),
670 ("https://store.example?token=x#y", "https://store.example"),
671 ("user:pass@store.example", "store.example"),
672 ("", ""),
673 ] {
674 assert_eq!(origin(endpoint), shown, "{endpoint}");
675 }
676 }
677
678 #[test]
679 fn debug_output_hides_the_credentials() {
680 let shown = format!(
681 "{:?}",
682 builder().session_token("token-value").prefix("photos")
683 );
684 for secret in ["access-key-id", "secret-key-value", "token-value"] {
685 assert!(!shown.contains(secret), "{shown}");
686 }
687 assert!(shown.contains("photos"), "{shown}");
688
689 let shown = format!(
690 "{:?}",
691 S3Backend::builder(
692 "https://endpoint-user:endpoint-pass@store.example",
693 "r",
694 "b"
695 )
696 );
697 for secret in ["endpoint-user", "endpoint-pass"] {
698 assert!(!shown.contains(secret), "{shown}");
699 }
700 assert!(shown.contains("https://store.example"), "{shown}");
701 }
702
703 #[tokio::test]
704 async fn the_endpoint_the_region_and_the_bucket_are_checked() {
705 for (endpoint, region, bucket) in [
706 ("ftp://store.example", "us-east-1", "b"),
707 ("https://user:pass@store.example", "us-east-1", "b"),
708 ("https://store.example/path", "us-east-1", "b"),
709 ("store.example", "us-east-1", "b"),
710 ("https://store.example", "", "b"),
711 ("https://store.example", "us east", "b"),
712 ("https://store.example", "us-east-1", ""),
713 ("https://store.example", "us-east-1", "a/b"),
714 ] {
715 let built = S3Backend::builder(endpoint, region, bucket)
716 .credentials("a", "s")
717 .read_only()
718 .build()
719 .await;
720 assert!(
721 matches!(built, Err(S3Error::InvalidArgument(_))),
722 "{endpoint} {region} {bucket}"
723 );
724 }
725 }
726}