Skip to main content

ostrya_remote/s3/
bucket.rs

1//! The client of a bucket repository.
2
3use std::collections::HashSet;
4use std::io::ErrorKind;
5use std::pin::Pin;
6use std::sync::Arc;
7use std::sync::atomic::AtomicU64;
8use std::task::{Context, Poll};
9use std::time::Duration;
10
11use futures_io::AsyncRead;
12use futures_lite::io::AsyncReadExt;
13use ostrya_fetch::{
14    Body, ErrorResponse, FetchRequest, Fetched, Fetcher, Target, UploadBody, UploadMethod,
15    UploadRequest, Uploaded,
16};
17use quick_xml::escape::partial_escape;
18use sha2::{Digest, Sha256};
19
20use super::key::{
21    check_key, check_list_prefix, decode_listed, encode_path, encode_query, is_repository_key,
22};
23use super::sigv4::valid_region;
24use super::xml::{self, Doc, ErrorDoc, MAX_BODY, shown};
25use super::{Location, S3Endpoint};
26use crate::{Error, Result};
27
28/// The largest listing body and error body that the client reads: the limit
29/// of the XML reader, 4 MiB.
30const XML_CAP: u64 = MAX_BODY as u64;
31
32/// The largest number of truncated pages in a row, with no key and no common
33/// prefix, that a list follows.
34///
35/// S3 can give a truncated page of `ListObjectsV2` with no key and no common
36/// prefix, for example over many delete markers of a versioned bucket. The
37/// list follows such a page if its continuation token is new since the last
38/// page with a key or a common prefix. A run of more than this number of such
39/// pages fails the list, so a server that gives empty pages with new tokens
40/// and no end cannot keep the list open.
41const MAX_EMPTY_PAGES: usize = 1000;
42
43/// The largest body of one `PUT`: 5 GiB, the S3 limit. It is also the
44/// largest part of a multipart upload.
45const MAX_PUT: u64 = 5 * 1024 * 1024 * 1024;
46
47/// One MiB.
48const MIB: u64 = 1024 * 1024;
49
50/// The smallest part size of [`Bucket::put_stream`]: 5 MiB, the S3 limit of
51/// each part other than the last part.
52const MIN_PART: u64 = 5 * MIB;
53
54/// The smallest part size that [`part_size`] gives: 8 MiB.
55const DEFAULT_PART: u64 = 8 * MIB;
56
57/// The largest number of parts of one multipart upload: 10,000, the S3
58/// limit.
59const MAX_PARTS: u32 = 10_000;
60
61/// The largest upload id and the largest `ETag` of a part that the client
62/// takes: 1 KiB. So the `ETag` values of an upload and the document that
63/// completes it have a limit.
64const MAX_UPLOAD_TOKEN: usize = 1024;
65
66/// The namespace of the S3 documents.
67const S3_NAMESPACE: &str = "http://s3.amazonaws.com/doc/2006-03-01/";
68
69/// The largest capacity that a whole read of a listing body or of an error
70/// body reserves before the body arrives. A larger body grows the buffer as
71/// it arrives.
72const MAX_RESERVE: u64 = XML_CAP;
73
74/// The capacity that a whole read of a body with no declared length reserves
75/// before the body arrives: 8 KiB.
76const FIRST_READ: u64 = 8 * 1024;
77
78/// The size of the chunks in which the compare of a conditional `PUT` reads
79/// the object of the key: 64 KiB.
80const COMPARE_CHUNK: usize = 64 * 1024;
81
82/// The size above which the client hashes a body on the blocking pool, once
83/// before the first request: 1 MiB. The signer hashes a smaller body on the
84/// task of each request.
85const UNBLOCK_SIZE: usize = 1024 * 1024;
86
87/// The client of a bucket repository.
88///
89/// [`Bucket::new`] opens it from an [`S3Endpoint`], and
90/// [`Bucket::from_fetcher`] opens it over a fetcher that the caller built.
91/// [`Bucket::counted`] gives a client whose fetcher adds byte counters.
92/// Each method takes a key or a list prefix relative to the prefix of the
93/// repository, and the client adds `PREFIX/`. A key in a result is relative
94/// to the prefix of the repository too.
95///
96/// # Keys
97///
98/// The client refuses a key that is not a key of a bucket repository, before
99/// it sends a request:
100///
101/// - `config`, `summary`, `summary.sig`, `extensions/ostrya/lock`, and
102///   `extensions/ostrya/lock-probe`
103/// - `objects/XX/<62 hex digits>.<ext>`, in lowercase hex, with the
104///   extension `commit`, `commitmeta`, `dirtree`, `dirmeta`, `filez`, or
105///   `tombstone-commit`
106/// - `refs/heads/<name>`, with a ref name that
107///   [`is_ref_name`](ostrya_core::is_ref_name) accepts
108/// - `refs/mirrors/<id>/<name>`, with an id of at most 255 bytes that
109///   [`is_collection_id`](ostrya_core::is_collection_id) accepts, and a ref
110///   name that [`is_ref_name`](ostrya_core::is_ref_name) accepts
111/// - `deltas/<2>/<41>/<target>` and `deltas/<2>/<41>-<43>/<target>`, with
112///   checksums in modified base64, and the target `superblock` or a part
113///   number with no leading zero
114/// - `delta-indexes/<2>/<41>.index`.
115///
116/// A list prefix ends in `/`, so a list for `s3://b/repo` never gives the
117/// keys of `s3://b/repo2`. Its segments are not empty and are not `.` or
118/// `..`.
119///
120/// The request path of a key encodes each byte other than `A-Z`, `a-z`,
121/// `0-9`, `-`, `.`, `_`, `~`, and `/` as `%XX`. So a `+` of a delta key goes
122/// as `%2B`.
123///
124/// # Requests
125///
126/// The `GET` requests (get, get stream, the checks for an object, and the
127/// lists) are fetches. The fetcher repeats a fetch after a transport failure
128/// or a 408, 429, or 5xx, as [`Fetcher::fetch`] states, and fetches a failed
129/// body of a whole read again. A check for an object is a `GET` with
130/// `Range: bytes=0-0`, as [`exists`](Bucket::exists) states. The signature
131/// does not cover the `Range` header.
132///
133/// The client sends a `PUT`, a `DELETE`, and the `POST` that starts a
134/// multipart upload again after
135/// [`Error::UploadInterrupted`](ostrya_fetch::Error::UploadInterrupted) and
136/// after a 408, 429, or 5xx, at most
137/// [`max_retries`](ostrya_fetch::FetcherOptions::max_retries) times. The
138/// delay starts at 250 ms, doubles each time, and stops at 2 s.
139/// [`put_if_absent`](Bucket::put_if_absent) and
140/// [`delete_if_match`](Bucket::delete_if_match) state their own rules, and
141/// [`put_stream`](Bucket::put_stream) states more rules for the `POST`
142/// requests of a multipart upload.
143///
144/// The client follows no redirect. The body of each listing, of each answer
145/// to a request of a multipart upload, and of each error response is at most
146/// 4 MiB.
147///
148/// # Errors of the server
149///
150/// An unsuccessful status gives [`Error::S3`], with the code and the message
151/// of the S3 `Error` document in the body. A response whose
152/// `x-amz-bucket-region` header or whose `Region` element names a region
153/// other than the region of the location gives [`Error::S3Region`]. An
154/// absent key is not an error, whatever region its response names.
155///
156/// The body of an error response to a `PUT` or a `DELETE` that declares a
157/// coding, or a length over 4 MiB, is not read. The status then gives
158/// [`Error::S3`] with no code, and the client does not send a definitive
159/// status again.
160///
161/// The [`Debug`] output shows the location and the mirror of the fetcher.
162pub struct Bucket {
163    fetcher: Fetcher,
164    location: Location,
165    max_retries: u32,
166    /// The bucket URL, if each request names its URL. It is `None` if the
167    /// request paths go under the one mirror of the fetcher, the bucket URL.
168    base: Option<String>,
169}
170
171impl std::fmt::Debug for Bucket {
172    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
173        f.debug_struct("Bucket")
174            .field("location", &self.location)
175            .field("fetcher", &self.fetcher)
176            .finish_non_exhaustive()
177    }
178}
179
180/// An object that [`Bucket::get`], [`Bucket::get_strict`], or
181/// [`Bucket::get_for_pull`] read whole.
182#[derive(Clone, Debug, PartialEq, Eq)]
183#[non_exhaustive]
184pub struct Object {
185    /// The bytes of the object.
186    pub bytes: Vec<u8>,
187    /// The `ETag` of the response, as the server wrote it.
188    pub etag: Option<String>,
189}
190
191/// The body of an object that [`Bucket::get_stream`] and
192/// [`Bucket::get_stream_strict`] give.
193///
194/// A read gives the bytes in bounded chunks, as a [`Body`] does. The stream
195/// holds an admission permit of the fetcher until it ends or is dropped. A
196/// failure in transit fails the read, and the caller reads the object
197/// again.
198#[derive(Debug)]
199pub struct ObjectStream {
200    body: Body,
201    etag: Option<String>,
202}
203
204impl ObjectStream {
205    /// Returns the `ETag` of the response, as the server wrote it.
206    pub fn etag(&self) -> Option<&str> {
207        self.etag.as_deref()
208    }
209
210    /// Returns the `Content-Length` of the response, if it declared one.
211    pub fn content_length(&self) -> Option<u64> {
212        self.body.content_length()
213    }
214}
215
216impl AsyncRead for ObjectStream {
217    fn poll_read(
218        mut self: Pin<&mut Self>,
219        cx: &mut Context<'_>,
220        buf: &mut [u8],
221    ) -> Poll<std::io::Result<usize>> {
222        Pin::new(&mut self.body).poll_read(cx, buf)
223    }
224}
225
226/// The read trait of tokio.
227#[cfg(feature = "tokio")]
228impl ostrya_rt::tokio_io::AsyncRead for ObjectStream {
229    fn poll_read(
230        mut self: Pin<&mut Self>,
231        cx: &mut Context<'_>,
232        buf: &mut ostrya_rt::tokio_io::ReadBuf<'_>,
233    ) -> Poll<std::io::Result<()>> {
234        ostrya_rt::tokio_io::AsyncRead::poll_read(Pin::new(&mut self.body), cx, buf)
235    }
236}
237
238/// The outcome of [`Bucket::put_if_absent`].
239#[derive(Clone, Debug, PartialEq, Eq)]
240#[non_exhaustive]
241pub enum PutIfAbsent {
242    /// A request of this call wrote the object: the server answered it with
243    /// a 2xx.
244    Created {
245        /// The `ETag` of the response, as the server wrote it.
246        etag: Option<String>,
247    },
248    /// The key held an object, and the call wrote nothing. The server
249    /// answered 412 to the first request, or a read of the key after a
250    /// request with an unknown outcome found other bytes. Or a read after a
251    /// 412 that followed a request with an unknown outcome found no object.
252    Present,
253    /// The key holds the bytes of the body, and no answer of the server
254    /// states which writer put them there.
255    ///
256    /// A request of this call had an unknown outcome. Then a failed request
257    /// followed, and a read of the key found the same bytes. A request of
258    /// this call can have written them, or an earlier writer of the same
259    /// bytes.
260    Matches {
261        /// The `ETag` of the read of the key, as the server wrote it.
262        etag: Option<String>,
263    },
264    /// The key holds the bytes of the body, and the server answered 412 to
265    /// a request of this call.
266    ///
267    /// A request of this call had an unknown outcome. Then a request got
268    /// 412, and a read of the key found the same bytes. A request of this
269    /// call can have written them, or an earlier writer of the same bytes.
270    /// The 412 shows that the server honors `If-None-Match`.
271    Refused {
272        /// The `ETag` of the read of the key, as the server wrote it.
273        etag: Option<String>,
274    },
275}
276
277/// The outcome of [`Bucket::delete_if_match`].
278#[derive(Clone, Copy, Debug, PartialEq, Eq)]
279#[non_exhaustive]
280pub enum DeleteIfMatch {
281    /// The key holds no object after the call. A request of the call
282    /// deleted it, or the key was absent at a read after a request with an
283    /// unknown outcome.
284    Deleted,
285    /// The key did not hold an object with the `ETag` at the first request:
286    /// the server answered 412, or the key was absent. Or the read after a
287    /// request with an unknown outcome found an object.
288    NotMatched,
289}
290
291/// The keys and the common prefixes of a list.
292#[derive(Clone, Debug, Default, PartialEq, Eq)]
293#[non_exhaustive]
294pub struct Listing {
295    /// The objects, in the order of the server.
296    pub objects: Vec<Listed>,
297    /// The common prefixes of a list with a delimiter, relative to the prefix
298    /// of the repository, each with its trailing `/`.
299    pub common_prefixes: Vec<String>,
300}
301
302/// One object of a [`Listing`].
303#[derive(Clone, Debug, PartialEq, Eq)]
304#[non_exhaustive]
305pub struct Listed {
306    /// The key, relative to the prefix of the repository.
307    ///
308    /// The key is not checked. A key that is not a key of a bucket
309    /// repository is a stray key.
310    pub key: String,
311    /// The size of the object in bytes.
312    pub size: u64,
313}
314
315/// One incomplete multipart upload of a key of the repository.
316#[derive(Clone, Debug, PartialEq, Eq)]
317#[non_exhaustive]
318pub struct Upload {
319    /// The key, relative to the prefix of the repository.
320    pub key: String,
321    /// The upload id.
322    pub upload_id: String,
323    /// The `Initiated` time, as the server wrote it.
324    pub initiated: String,
325}
326
327/// The answer to one upload request, read whole.
328struct Reply {
329    status: u16,
330    etag: Option<String>,
331    region: Option<String>,
332    /// The body, or `None` if it is larger than 4 MiB or failed in transit.
333    body: Option<Vec<u8>>,
334}
335
336/// The outcome of one upload request.
337enum Sent {
338    /// The server answered.
339    Reply(Reply),
340    /// The request failed after the fetcher sent it, so the outcome is not
341    /// known.
342    Interrupted(ostrya_fetch::Error),
343}
344
345/// What a key holds, compared with the body of a request.
346enum Compared {
347    /// The same bytes, with the `ETag` of the read.
348    Same(Option<String>),
349    /// Other bytes.
350    Other,
351    /// No object.
352    Absent,
353}
354
355impl Bucket {
356    /// Opens the client of the bucket repository of `endpoint`.
357    ///
358    /// The call builds the fetcher. It sends no request.
359    /// [`S3Endpoint`] states the HTTP options that the client takes.
360    ///
361    /// # Errors
362    ///
363    /// - [`Error::InvalidInput`] if [`SigV4::new`](super::SigV4::new) refuses
364    ///   the region.
365    /// - [`Error::Fetch`] if [`Fetcher::new`] refuses the options. An example
366    ///   is an `http://` endpoint with
367    ///   [`allow_cleartext_credentials`](ostrya_fetch::FetcherOptions::allow_cleartext_credentials)
368    ///   set to `false`, because the signer is a credential. Another is
369    ///   [`basic_auth`](ostrya_fetch::FetcherOptions::basic_auth), a bearer
370    ///   token, or an `Authorization` header in the options.
371    pub async fn new(endpoint: &S3Endpoint) -> Result<Bucket> {
372        let location = endpoint.location.clone();
373        let options = endpoint.signed_options(location.bucket_url())?;
374        let fetcher = Fetcher::new(options).await.map_err(Error::Fetch)?;
375        Ok(Bucket {
376            fetcher,
377            location,
378            max_retries: endpoint.http.max_retries,
379            base: None,
380        })
381    }
382
383    /// Opens the client of the bucket repository of `endpoint` over
384    /// `fetcher`.
385    ///
386    /// The call builds no fetcher and sends no request. The client shares
387    /// the connection pool, the admission limit, and the counters of
388    /// `fetcher`. The client names each request by its URL under the
389    /// [`bucket_url`](Location::bucket_url) of the location, so it does not
390    /// use the mirrors of `fetcher`. An example of `fetcher` is the fetcher
391    /// of a pull, from the options that
392    /// [`pull_options`](S3Endpoint::pull_options) gives, whose mirror is the
393    /// [`repository_url`](Location::repository_url).
394    ///
395    /// The client takes the location and the retry count of `endpoint`.
396    /// `fetcher` must sign each request with the credentials and the region
397    /// of `endpoint`, and follow no redirect, as the fetcher of
398    /// [`Bucket::new`] does. The call cannot check this.
399    ///
400    /// # Examples
401    ///
402    /// ```no_run
403    /// use ostrya_fetch::Fetcher;
404    /// use ostrya_remote::s3::{Bucket, Environment, S3Endpoint, Settings};
405    /// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
406    /// let endpoint =
407    ///     S3Endpoint::resolve("s3://builds/exampleos", &Settings::default(), &Environment::Process)
408    ///         .await?;
409    /// let fetcher = Fetcher::new(endpoint.pull_options()?).await?;
410    /// let bucket = Bucket::from_fetcher(&endpoint, fetcher.clone());
411    /// // The fetcher reads the objects under the repository URL. The client
412    /// // reads `summary` with the S3 rules of an absent key and of an error.
413    /// let summary = bucket.get("summary", 1 << 20).await?;
414    /// # Ok(()) }
415    /// ```
416    pub fn from_fetcher(endpoint: &S3Endpoint, fetcher: Fetcher) -> Bucket {
417        Bucket {
418            fetcher,
419            location: endpoint.location.clone(),
420            max_retries: endpoint.http.max_retries,
421            base: Some(endpoint.location.bucket_url()),
422        }
423    }
424
425    /// Returns a client of the same bucket repository whose fetcher adds
426    /// counters of received body bytes.
427    ///
428    /// The fetcher of the new client is [`Fetcher::counted`] of the fetcher
429    /// of this client with `received`, so it has the counters of this client
430    /// and the counters of `received`. [`Fetcher::counted`] states which
431    /// bytes each counter gets. The new client has the location, the retry
432    /// count, and the request URLs of this client. The counters of this
433    /// client do not change.
434    pub fn counted(&self, received: Vec<Arc<AtomicU64>>) -> Bucket {
435        Bucket {
436            fetcher: self.fetcher.counted(received),
437            location: self.location.clone(),
438            max_retries: self.max_retries,
439            base: self.base.clone(),
440        }
441    }
442
443    /// Returns the location of the bucket repository.
444    pub fn location(&self) -> &Location {
445        &self.location
446    }
447
448    /// Reads the object of `key` whole, or returns `None` if the key holds no
449    /// object.
450    ///
451    /// A 404 is an absent key if its body arrived whole and holds the code
452    /// `NoSuchKey`, or holds no S3 code: an empty body, or a body that is
453    /// not an S3 `Error` document. A 404 with another code, for example
454    /// `NoSuchBucket`, is an error, so a missing bucket never reads as an
455    /// empty repository. A 404 whose body did not arrive is an error too,
456    /// with no code. An absent key is not an error, whatever region its
457    /// response names. [`get_strict`](Bucket::get_strict) reads a key by a
458    /// strict rule, and [`get_for_pull`](Bucket::get_for_pull) by the rule of
459    /// a pull.
460    ///
461    /// The bytes have the capacity of the object and one byte, if the
462    /// response declares the length of the object.
463    ///
464    /// # Errors
465    ///
466    /// - [`Error::InvalidInput`] if `key` is not a key of a bucket repository.
467    /// - [`Error::LimitExceeded`] if the object is larger than `max_size`
468    ///   bytes. The message names the key.
469    /// - [`Error::S3`] and [`Error::S3Region`] for an unsuccessful response.
470    /// - [`Error::Transport`] if the server answers with 304. The request
471    ///   sends no validators, so the answer cannot be used.
472    /// - [`Error::Fetch`] for a failure of the fetcher, and [`Error::Io`] for
473    ///   a body that failed in transit after the last refetch.
474    pub async fn get(&self, key: &str, max_size: u64) -> Result<Option<Object>> {
475        self.get_whole(key, max_size, is_absent).await
476    }
477
478    /// Reads the object of `key` whole, or returns `None` if the key holds no
479    /// object, by a strict rule of an absent key.
480    ///
481    /// A 404 is an absent key only if its body arrived whole and holds the
482    /// code `NoSuchKey`. Each other 404 is an error, also a 404 with an empty
483    /// body or with a body that is not an S3 `Error` document, for example a
484    /// page of a proxy. Use this call where a false absent key causes a loss
485    /// of data. Else the call is [`get`](Bucket::get).
486    ///
487    /// # Errors
488    ///
489    /// The errors of [`get`](Bucket::get). A 404 that is not an absent key
490    /// gives [`Error::S3`] with the status 404, and with no code if the body
491    /// holds no S3 code.
492    pub async fn get_strict(&self, key: &str, max_size: u64) -> Result<Option<Object>> {
493        self.get_whole(key, max_size, is_no_such_key).await
494    }
495
496    /// Reads the object of `key` whole, or returns `None` if the key holds no
497    /// object, by the rule of an absent key of a pull.
498    ///
499    /// An answer that [`get`](Bucket::get) reads as an absent key is an
500    /// absent key here too. A 403 is also an absent key if its body arrived
501    /// whole and holds the code `AccessDenied`. S3 answers so for an absent
502    /// key to a caller that has no `s3:ListBucket` on the bucket, so a pull
503    /// needs `s3:GetObject` alone. A 403 with another code, for example
504    /// `SignatureDoesNotMatch` or `InvalidAccessKeyId`, is an error, so a
505    /// wrong key fails at the first read. A key that holds an object that the
506    /// credentials cannot read is also an absent key here.
507    ///
508    /// A pull reads `summary` and `summary.sig` with this call. It reads
509    /// `config` with [`get`](Bucket::get).
510    ///
511    /// # Errors
512    ///
513    /// The errors of [`get`](Bucket::get). A 403 that is not an absent key
514    /// gives [`Error::S3`] with the status 403, or [`Error::S3Region`].
515    pub async fn get_for_pull(&self, key: &str, max_size: u64) -> Result<Option<Object>> {
516        self.get_whole(key, max_size, is_absent_or_denied).await
517    }
518
519    /// Reads the object of `key` whole, as [`get`](Bucket::get) does, with
520    /// `absent` as the rule of an absent key.
521    async fn get_whole(
522        &self,
523        key: &str,
524        max_size: u64,
525        absent: fn(u16, Option<&[u8]>) -> bool,
526    ) -> Result<Option<Object>> {
527        check_key(key)?;
528        let full = self.full_key(key);
529        let path = encode_path(&full);
530        let target = self.target(&path, "");
531        let mut refetch = self.fetcher.refetching(FetchRequest {
532            max_size: Some(max_size),
533            max_error_body: Some(XML_CAP),
534            ..target.fetch()
535        });
536        loop {
537            let mut body = match refetch.fetch().await {
538                Ok(Fetched::Body(body)) => body,
539                Ok(Fetched::NotModified) => return Err(not_modified(&full)),
540                Err(e) => {
541                    self.absent_or_error(e, &full, max_size, absent)?;
542                    return Ok(None);
543                }
544            };
545            let etag = body.validators().etag.clone();
546            let declared = body.content_length();
547            // The fetcher refuses a declared length over `max_size`, so the
548            // read reserves a declared length whole.
549            match read_whole(&mut body, declared, max_size, max_size).await {
550                Ok(bytes) => return Ok(Some(Object { bytes, etag })),
551                Err(e) if e.kind() == ErrorKind::FileTooLarge => {
552                    return Err(too_large(&full, max_size));
553                }
554                Err(e) => {
555                    drop(body);
556                    refetch.retry(e).await?;
557                }
558            }
559        }
560    }
561
562    /// Opens the body of the object of `key` as a stream, or returns `None`
563    /// if the key holds no object.
564    ///
565    /// The stream holds no more than one chunk of the object in memory.
566    /// [`get`](Bucket::get) states the rule of an absent key.
567    ///
568    /// # Errors
569    ///
570    /// The errors of [`get`](Bucket::get), other than the size limit: also
571    /// [`Error::Transport`] for a 304. A read of the stream fails with an I/O
572    /// error if the body fails in transit.
573    pub async fn get_stream(&self, key: &str) -> Result<Option<ObjectStream>> {
574        self.open_stream(key, is_absent).await
575    }
576
577    /// Opens the body of the object of `key` as a stream, or returns `None`
578    /// if the key holds no object, by the strict rule of an absent key of
579    /// [`get_strict`](Bucket::get_strict).
580    ///
581    /// The stream holds no more than one chunk of the object in memory.
582    ///
583    /// # Errors
584    ///
585    /// The errors of [`get_stream`](Bucket::get_stream). A 404 that is not an
586    /// absent key gives [`Error::S3`] with the status 404, and with no code
587    /// if the body holds no S3 code.
588    pub async fn get_stream_strict(&self, key: &str) -> Result<Option<ObjectStream>> {
589        self.open_stream(key, is_no_such_key).await
590    }
591
592    /// Opens the body of the object of `key` as a stream, as
593    /// [`get_stream`](Bucket::get_stream) does, with `absent` as the rule of
594    /// an absent key.
595    async fn open_stream(
596        &self,
597        key: &str,
598        absent: fn(u16, Option<&[u8]>) -> bool,
599    ) -> Result<Option<ObjectStream>> {
600        check_key(key)?;
601        let full = self.full_key(key);
602        let path = encode_path(&full);
603        let target = self.target(&path, "");
604        let fetched = self
605            .fetcher
606            .fetch(FetchRequest {
607                max_error_body: Some(XML_CAP),
608                ..target.fetch()
609            })
610            .await;
611        match fetched {
612            Ok(Fetched::Body(body)) => {
613                let etag = body.validators().etag.clone();
614                Ok(Some(ObjectStream { body, etag }))
615            }
616            Ok(Fetched::NotModified) => Err(not_modified(&full)),
617            Err(e) => {
618                self.absent_or_error(e, &full, u64::MAX, absent)?;
619                Ok(None)
620            }
621        }
622    }
623
624    /// Returns `true` if the key `key` holds an object.
625    ///
626    /// The request is `GET KEY` with `Range: bytes=0-0`, and the client reads
627    /// at most one byte of the object. A 206 and a 200 are an object. A 416
628    /// is an object too, because a server gives it for an object of zero
629    /// bytes. A server that ignores the range answers 200 with the whole
630    /// object. The client then refuses a declared length over one byte, and
631    /// reads no byte of it. The fetcher reads a declared body of at most
632    /// 64 KiB to its end, so the connection goes back to the pool. A larger
633    /// body, or a body with no declared length, closes the connection.
634    ///
635    /// The client reads a body that declares a length of at most one byte to
636    /// its end, so the connection goes back to the pool. If the body fails
637    /// after the status, the status decides, and the key holds an object. The
638    /// client does not read a body with no declared length, and its
639    /// connection closes. So a server that stalls such a body does not hold
640    /// the check until the progress timeout.
641    ///
642    /// [`get`](Bucket::get) states the rule of an absent key.
643    /// [`exists_strict`](Bucket::exists_strict) reads a key by the strict
644    /// rule.
645    ///
646    /// # Errors
647    ///
648    /// - [`Error::InvalidInput`] if `key` is not a key of a bucket repository.
649    /// - [`Error::S3`] and [`Error::S3Region`] for an unsuccessful response.
650    /// - [`Error::Transport`] if the server answers with 304. The request
651    ///   sends no validators, so the answer cannot be used.
652    /// - [`Error::Fetch`] for a failure of the fetcher.
653    pub async fn exists(&self, key: &str) -> Result<bool> {
654        self.probe(key, is_absent).await
655    }
656
657    /// Returns `true` if the key `key` holds an object, by the strict rule of
658    /// an absent key of [`get_strict`](Bucket::get_strict).
659    ///
660    /// [`exists`](Bucket::exists) states the request and the rules of an
661    /// object.
662    ///
663    /// # Errors
664    ///
665    /// The errors of [`exists`](Bucket::exists). A 404 that is not an absent
666    /// key gives [`Error::S3`] with the status 404, and with no code if the
667    /// body holds no S3 code.
668    pub async fn exists_strict(&self, key: &str) -> Result<bool> {
669        self.probe(key, is_no_such_key).await
670    }
671
672    /// Returns `true` if the key `key` holds an object, as
673    /// [`exists`](Bucket::exists) does, with `absent` as the rule of an
674    /// absent key.
675    async fn probe(&self, key: &str, absent: fn(u16, Option<&[u8]>) -> bool) -> Result<bool> {
676        check_key(key)?;
677        let full = self.full_key(key);
678        let path = encode_path(&full);
679        let target = self.target(&path, "");
680        let range = [("Range".to_owned(), "bytes=0-0".to_owned())];
681        let fetched = self
682            .fetcher
683            .fetch(FetchRequest {
684                headers: &range,
685                max_size: Some(1),
686                max_error_body: Some(XML_CAP),
687                ..target.fetch()
688            })
689            .await;
690        match fetched {
691            Ok(Fetched::Body(mut body)) => {
692                // The end of a declared body returns the connection to the
693                // pool. A failure drops the connection, and the status still
694                // decides. A body with no declared length is not read, so a
695                // server that stalls it does not hold the check, and the drop
696                // closes the connection.
697                if body.content_length().is_some_and(|length| length <= 1) {
698                    let mut bytes = [0u8; 8];
699                    while let Ok(1..) = body.read(&mut bytes).await {}
700                }
701                Ok(true)
702            }
703            Ok(Fetched::NotModified) => Err(not_modified(&full)),
704            Err(ostrya_fetch::Error::FetchTooLarge { .. }) => Ok(true),
705            Err(ostrya_fetch::Error::HttpStatus { status: 416, .. }) => Ok(true),
706            Err(e) => {
707                self.absent_or_error(e, &full, 1, absent)?;
708                Ok(false)
709            }
710        }
711    }
712
713    /// Writes `body` to `key`, and returns the `ETag` of the response.
714    ///
715    /// The request is idempotent, so the client sends it again by the rule
716    /// of [`Bucket`]. A second request shares the bytes of the first one, so
717    /// the client holds one copy of the body.
718    ///
719    /// The client hashes a body of more than 1 MiB once, on the blocking pool
720    /// of the runtime, before the first request. Each request signs that
721    /// digest. The signer hashes a smaller body on the task of each request.
722    ///
723    /// # Errors
724    ///
725    /// - [`Error::InvalidInput`] if `key` is not a key of a bucket repository,
726    ///   or if `body` is larger than 5 GiB, the limit of one S3 `PUT`.
727    /// - [`Error::S3`] and [`Error::S3Region`] for an unsuccessful response.
728    /// - [`Error::Fetch`] for a failure of the fetcher, also after the last
729    ///   request that the client sent again.
730    pub async fn put(&self, key: &str, body: Vec<u8>) -> Result<Option<String>> {
731        check_key(key)?;
732        check_put_size(key, &body)?;
733        let full = self.full_key(key);
734        let path = encode_path(&full);
735        self.put_body(&full, &path, upload_body(body).await).await
736    }
737
738    /// Writes the bytes that `body` gives to `key`, and returns the `ETag`
739    /// of the answer that wrote the object, as the server wrote it.
740    ///
741    /// Servers give different `ETag` values for one object of several
742    /// parts. Do not compare the result with the `ETag` of a later read of
743    /// the key.
744    ///
745    /// The call reads `body` in parts of `part_size` bytes. [`part_size`]
746    /// gives the part size of an object of a known size. A body of at most
747    /// one part goes in one `PUT`. A longer body goes in a multipart upload:
748    ///
749    /// 1. `POST KEY?uploads` starts the upload and gives the upload id.
750    /// 2. `PUT KEY?partNumber=N&uploadId=ID` sends each part, one part after
751    ///    the other. The part numbers start at 1 and have no gap. Each part
752    ///    other than the last one holds `part_size` bytes.
753    /// 3. `POST KEY?uploadId=ID` with a `CompleteMultipartUpload` document
754    ///    completes the upload. The document gives each part number with the
755    ///    `ETag` of its answer, as the server wrote it.
756    ///
757    /// The call holds one part in memory, with the `ETag` of each part that
758    /// it sent and the document that completes the upload. The first part
759    /// starts at 8 KiB and doubles up to `part_size` while the bytes arrive,
760    /// so a small body takes a small buffer. After each part, the call takes
761    /// the buffer back and reads the next part into it. If the fetcher still
762    /// holds the bytes of a part, the next part takes a new buffer. After a
763    /// full part, the call reads one byte more to find if the body goes on.
764    /// The call hashes each part of more than 1 MiB once, on the blocking
765    /// pool of the runtime, before the first request of the part. The part
766    /// moves to the pool and back with no copy, and each request of the part
767    /// signs that digest. The signer hashes a smaller part on the task of
768    /// each request.
769    ///
770    /// The client takes an upload id and an `ETag` of a part of at most
771    /// 1 KiB each. So the `ETag` values of an upload and the document that
772    /// completes it have a limit.
773    ///
774    /// The client sends each part again by the rule of [`Bucket`]. A part
775    /// has the same bytes in each request. The `POST` that starts the upload
776    /// is sent again by the same rule, and also after a 2xx whose body did
777    /// not arrive. The `POST` that completes the upload is sent again after
778    /// an interrupted request, after a 408, 429, or 5xx, after a 2xx whose
779    /// body cannot be read, and after a 2xx whose body is an S3 `Error`
780    /// document. S3 can send such a document after the head of a 200.
781    ///
782    /// After an interrupted request, a 408, 429, or 5xx, or an unusable 2xx
783    /// to the `POST` that completes the upload, the server can have
784    /// completed the upload. If a later request then gets a 404 with the code
785    /// `NoSuchUpload`, the client reads the key as
786    /// [`get_stream`](Bucket::get_stream) does. A `Content-Length` equal to
787    /// the number of bytes of the body gives success with the `ETag` of the
788    /// read, and the client reads no byte of the object. An absent object and
789    /// an object of another length give an error.
790    ///
791    /// This check compares the length alone. It is sound for a key whose
792    /// name sets its content, such as a content-addressed object or a static
793    /// delta. For a key whose content changes, an older object of the same
794    /// length passes the check.
795    ///
796    /// After each failure that comes after the start of the upload, the
797    /// client sends one `DELETE KEY?uploadId=ID` to abort the upload, and
798    /// ignores its outcome. Then it returns the error of the failure. If the
799    /// last answer to a request of the upload is a 404 with the code
800    /// `NoSuchUpload`, the server holds no such upload, and the client sends
801    /// no abort.
802    ///
803    /// A dropped future sends no abort, so the upload stays open, and it
804    /// holds storage in the bucket. [`list_uploads`](Bucket::list_uploads)
805    /// gives each such upload, and [`abort_upload`](Bucket::abort_upload)
806    /// aborts it. The prune of a bucket repository of the `ostrya` crate
807    /// aborts each such upload. To remove such uploads with no call of the
808    /// client, set a lifecycle rule on the bucket that aborts incomplete
809    /// multipart uploads.
810    ///
811    /// # Errors
812    ///
813    /// - [`Error::InvalidInput`] if `key` is not a key of a bucket repository,
814    ///   or if `part_size` is less than 5 MiB or more than 5 GiB, the S3
815    ///   limits of a part. The call then reads no byte of `body`.
816    /// - [`Error::Io`] if a read of `body` fails.
817    /// - [`Error::LimitExceeded`] if the body is longer than 10,000 parts of
818    ///   `part_size` bytes, the S3 limit of the parts of an upload. The
819    ///   message names the key and the part size.
820    /// - [`Error::S3`] and [`Error::S3Region`] for an unsuccessful response,
821    ///   and [`Error::S3`] for an S3 `Error` document with a 2xx after the
822    ///   last request that the client sent again.
823    /// - [`Error::Transport`] if the answer that starts the upload has no
824    ///   usable upload id or an upload id of more than 1 KiB, if its body did
825    ///   not arrive after the last request that the client sent again, if the
826    ///   answer to a part has no `ETag` or an `ETag` of more than 1 KiB, or if
827    ///   no answer that completes the upload can be read. Also if the key
828    ///   holds no object or an object of another length after a 404
829    ///   `NoSuchUpload` to a completion whose outcome is not known. The
830    ///   message then states what the key holds.
831    /// - The errors of [`get_stream`](Bucket::get_stream) for the read of
832    ///   the key after such a 404 `NoSuchUpload`.
833    /// - [`Error::Fetch`] for a failure of the fetcher, also after the last
834    ///   request that the client sent again.
835    pub async fn put_stream<R>(&self, key: &str, body: R, part_size: u64) -> Result<Option<String>>
836    where
837        R: AsyncRead + Unpin + Send,
838    {
839        check_key(key)?;
840        let size = usize::try_from(part_size)
841            .ok()
842            .filter(|_| (MIN_PART..=MAX_PUT).contains(&part_size))
843            .ok_or_else(|| {
844                Error::InvalidInput(format!(
845                    "S3: the part size {part_size} of {key} is outside the range of \
846                     {MIN_PART} to {MAX_PUT} bytes of a part"
847                ))
848            })?;
849        self.put_parts(key, Parts::new(body, size, MAX_PARTS)).await
850    }
851
852    /// Writes `body` to `key` if the key holds no object.
853    ///
854    /// The request carries `If-None-Match: *`. A 2xx gives
855    /// [`PutIfAbsent::Created`]. A 412 to the first request gives
856    /// [`PutIfAbsent::Present`]. A 409 with the code
857    /// `ConditionalRequestConflict` is sent again, at most
858    /// [`max_retries`](ostrya_fetch::FetcherOptions::max_retries) times.
859    ///
860    /// After an interrupted request, the outcome is not known. The client
861    /// then reads the key and compares the SHA-256 of what it holds with the
862    /// SHA-256 of `body`:
863    ///
864    /// - The same bytes give [`PutIfAbsent::Matches`].
865    /// - Other bytes give [`PutIfAbsent::Present`].
866    /// - An absent key sends the request again, within the retry count.
867    ///
868    /// After a 408, 429, or 5xx, the client sends the request again within
869    /// the retry count. A 412 after such a status, or after an interrupted
870    /// request, can answer a request of this call. So the client then reads
871    /// the key and compares it in the same way: the same bytes give
872    /// [`PutIfAbsent::Refused`], and other bytes or an absent key give
873    /// [`PutIfAbsent::Present`].
874    ///
875    /// The compare reads the object as a stream, in chunks of 64 KiB. A
876    /// response that declares a length other than the length of `body`
877    /// holds other bytes, and the client reads none of it. The client
878    /// computes the SHA-256 of `body` on the blocking pool of the runtime:
879    /// for a body of more than 1 MiB once before the first request, which
880    /// each request signs, and for a smaller body at the first compare.
881    ///
882    /// A server that does not honor `If-None-Match` writes the object over
883    /// the one that the key holds, and gives [`PutIfAbsent::Created`].
884    ///
885    /// # Errors
886    ///
887    /// The errors of [`put`](Bucket::put), and the errors of
888    /// [`get`](Bucket::get) for the read of the key.
889    pub async fn put_if_absent(&self, key: &str, body: Vec<u8>) -> Result<PutIfAbsent> {
890        check_key(key)?;
891        check_put_size(key, &body)?;
892        let full = self.full_key(key);
893        let path = encode_path(&full);
894        let body = upload_body(body).await;
895        let headers = [("If-None-Match".to_owned(), "*".to_owned())];
896        let mut round = 0;
897        // `true` after a request whose outcome is not known.
898        let mut unsure = false;
899        // The SHA-256 of `body`: the digest of a large body, or else computed
900        // at the first compare that needs it.
901        let mut digest = body.sha256();
902        loop {
903            match self
904                .send(UploadMethod::Put, &path, "", copy(&body), &headers)
905                .await?
906            {
907                Sent::Reply(reply) if is_success(reply.status) => {
908                    return Ok(PutIfAbsent::Created { etag: reply.etag });
909                }
910                Sent::Reply(reply) if reply.status == 412 => {
911                    if !unsure {
912                        return Ok(PutIfAbsent::Present);
913                    }
914                    return Ok(match self.compare(&full, &body, &mut digest).await? {
915                        Compared::Same(etag) => PutIfAbsent::Refused { etag },
916                        Compared::Other | Compared::Absent => PutIfAbsent::Present,
917                    });
918                }
919                Sent::Reply(reply)
920                    if reply.status == 409
921                        && reply_code(&reply).as_deref() == Some("ConditionalRequestConflict")
922                        && round < self.max_retries => {}
923                Sent::Reply(reply) if is_retryable(reply.status) && round < self.max_retries => {
924                    unsure = true;
925                }
926                Sent::Reply(reply) => return Err(self.reply_error(reply, Some(&full))),
927                Sent::Interrupted(e) => match self.compare(&full, &body, &mut digest).await? {
928                    Compared::Same(etag) => return Ok(PutIfAbsent::Matches { etag }),
929                    Compared::Other => return Ok(PutIfAbsent::Present),
930                    Compared::Absent if round < self.max_retries => unsure = true,
931                    Compared::Absent => return Err(Error::Fetch(e)),
932                },
933            }
934            round += 1;
935            ostrya_rt::Timer::after(backoff(round)).await;
936        }
937    }
938
939    /// Deletes the object of `key`.
940    ///
941    /// A 2xx and an absent key are success. [`get`](Bucket::get) states the
942    /// rule of an absent key. The client sends the request again by the rule
943    /// of [`Bucket`].
944    ///
945    /// # Errors
946    ///
947    /// - [`Error::InvalidInput`] if `key` is not a key of a bucket repository.
948    /// - [`Error::S3`] and [`Error::S3Region`] for an unsuccessful response.
949    /// - [`Error::Fetch`] for a failure of the fetcher, also after the last
950    ///   request that the client sent again.
951    pub async fn delete(&self, key: &str) -> Result<()> {
952        check_key(key)?;
953        let full = self.full_key(key);
954        let path = encode_path(&full);
955        let mut round = 0;
956        loop {
957            let empty = UploadBody::bytes(Vec::new());
958            match self
959                .send(UploadMethod::Delete, &path, "", empty, &[])
960                .await?
961            {
962                Sent::Reply(reply) if is_success(reply.status) => return Ok(()),
963                Sent::Reply(reply) if is_absent(reply.status, reply.body.as_deref()) => {
964                    return Ok(());
965                }
966                Sent::Reply(reply) if is_retryable(reply.status) && round < self.max_retries => {}
967                Sent::Reply(reply) => return Err(self.reply_error(reply, Some(&full))),
968                Sent::Interrupted(_) if round < self.max_retries => {}
969                Sent::Interrupted(e) => return Err(Error::Fetch(e)),
970            }
971            round += 1;
972            ostrya_rt::Timer::after(backoff(round)).await;
973        }
974    }
975
976    /// Deletes the object of `key` if its `ETag` is `etag`.
977    ///
978    /// The request is `DELETE KEY` with `If-Match: ETAG`. `etag` goes as the
979    /// server wrote it, for example the [`etag`](Object::etag) of a read. A
980    /// 2xx gives [`DeleteIfMatch::Deleted`]. A 412 or an absent key to the
981    /// first request gives [`DeleteIfMatch::NotMatched`].
982    /// [`get`](Bucket::get) states the rule of an absent key. SeaweedFS 4.36
983    /// answers 412 for an absent key.
984    ///
985    /// The client sends the request again by the rule of [`Bucket`]. A 412
986    /// or an absent key after a request with an unknown outcome can answer a
987    /// request of this call. So the client then reads the key as
988    /// [`exists`](Bucket::exists) does. An absent key gives
989    /// [`DeleteIfMatch::Deleted`], and an object gives
990    /// [`DeleteIfMatch::NotMatched`].
991    ///
992    /// A server that does not honor `If-Match` deletes the object whatever
993    /// its `ETag` is, and gives [`DeleteIfMatch::Deleted`].
994    /// `rclone serve s3` 1.75.1 is such a server.
995    ///
996    /// # Errors
997    ///
998    /// - [`Error::InvalidInput`] if `key` is not a key of a bucket repository,
999    ///   or if `etag` is empty or longer than 1 KiB. The client then sends no
1000    ///   request.
1001    /// - [`Error::S3`] and [`Error::S3Region`] for an unsuccessful response.
1002    /// - [`Error::Fetch`] for a failure of the fetcher, also after the last
1003    ///   request that the client sent again.
1004    /// - The errors of [`exists`](Bucket::exists) for the read of the key.
1005    pub async fn delete_if_match(&self, key: &str, etag: &str) -> Result<DeleteIfMatch> {
1006        check_key(key)?;
1007        if etag.is_empty() || etag.len() > MAX_UPLOAD_TOKEN {
1008            return Err(Error::InvalidInput(format!(
1009                "S3: the ETag of a conditional delete of {key} is empty or longer than \
1010                 {MAX_UPLOAD_TOKEN} bytes"
1011            )));
1012        }
1013        let full = self.full_key(key);
1014        let path = encode_path(&full);
1015        let headers = [("If-Match".to_owned(), etag.to_owned())];
1016        let mut round = 0;
1017        // `true` after a request whose outcome is not known.
1018        let mut unsure = false;
1019        loop {
1020            let empty = UploadBody::bytes(Vec::new());
1021            match self
1022                .send(UploadMethod::Delete, &path, "", empty, &headers)
1023                .await?
1024            {
1025                Sent::Reply(reply) if is_success(reply.status) => {
1026                    return Ok(DeleteIfMatch::Deleted);
1027                }
1028                Sent::Reply(reply)
1029                    if reply.status == 412 || is_absent(reply.status, reply.body.as_deref()) =>
1030                {
1031                    if !unsure {
1032                        return Ok(DeleteIfMatch::NotMatched);
1033                    }
1034                    return Ok(if self.exists(key).await? {
1035                        DeleteIfMatch::NotMatched
1036                    } else {
1037                        DeleteIfMatch::Deleted
1038                    });
1039                }
1040                Sent::Reply(reply) if is_retryable(reply.status) && round < self.max_retries => {
1041                    unsure = true;
1042                }
1043                Sent::Reply(reply) => return Err(self.reply_error(reply, Some(&full))),
1044                Sent::Interrupted(_) if round < self.max_retries => unsure = true,
1045                Sent::Interrupted(e) => return Err(Error::Fetch(e)),
1046            }
1047            round += 1;
1048            ostrya_rt::Timer::after(backoff(round)).await;
1049        }
1050    }
1051
1052    /// Aborts the multipart upload `upload_id` of `key`.
1053    ///
1054    /// The request is `DELETE KEY?uploadId=ID`. A 2xx and a 404 with the
1055    /// code `NoSuchUpload` are success, so an upload that a server already
1056    /// removed is not an error. The client sends the request again by the
1057    /// rule of [`Bucket`].
1058    ///
1059    /// # Errors
1060    ///
1061    /// - [`Error::InvalidInput`] if `key` is not a key of a bucket repository,
1062    ///   or if `upload_id` is empty.
1063    /// - [`Error::S3`] and [`Error::S3Region`] for an unsuccessful response.
1064    /// - [`Error::Fetch`] for a failure of the fetcher, also after the last
1065    ///   request that the client sent again.
1066    pub async fn abort_upload(&self, key: &str, upload_id: &str) -> Result<()> {
1067        check_key(key)?;
1068        if upload_id.is_empty() {
1069            return Err(Error::InvalidInput(format!(
1070                "S3: the upload id of an abort of {key} is empty"
1071            )));
1072        }
1073        let full = self.full_key(key);
1074        let path = encode_path(&full);
1075        let query = upload_query(upload_id);
1076        let empty = UploadBody::bytes(Vec::new());
1077        let reply = self
1078            .send_retrying(UploadMethod::Delete, &path, &query, &empty)
1079            .await?;
1080        if is_success(reply.status) || is_no_such_upload(&reply) {
1081            return Ok(());
1082        }
1083        Err(self.reply_error(reply, Some(&full)))
1084    }
1085
1086    /// Lists each object under `prefix`, over all pages.
1087    ///
1088    /// `prefix` is relative to the prefix of the repository and ends in `/`,
1089    /// for example `objects/ab/` or `refs/heads/`. The request is
1090    /// `ListObjectsV2` with the encoding type `url`, and the client decodes
1091    /// each key.
1092    ///
1093    /// # Errors
1094    ///
1095    /// - [`Error::InvalidInput`] if `prefix` does not end in `/`, or holds an
1096    ///   empty segment, `.`, `..`, or a character outside the alphabet of a
1097    ///   key.
1098    /// - [`Error::Transport`] if a page cannot be used: a body that the XML
1099    ///   reader refuses, a truncated page with no continuation token, a key
1100    ///   outside the prefix, or a page that does not move forward. Each key
1101    ///   and common prefix of a page comes after each one of the earlier
1102    ///   pages, in the byte order of UTF-8. A truncated page that holds no
1103    ///   key and no common prefix gives a continuation token that no page
1104    ///   gave after the last page with a key or a common prefix. More than
1105    ///   1000 truncated pages in a row with no key and no common prefix fail
1106    ///   the list. So a server that gives the same page again, or empty
1107    ///   pages with no end, fails the list.
1108    /// - [`Error::Transport`] if the server answers with 304.
1109    /// - [`Error::LimitExceeded`] if a page is larger than 4 MiB.
1110    /// - [`Error::S3`] and [`Error::S3Region`] for an unsuccessful response,
1111    ///   or for an S3 `Error` document with a 200.
1112    /// - [`Error::Fetch`] and [`Error::Io`] as for [`get`](Bucket::get).
1113    pub async fn list(&self, prefix: &str) -> Result<Listing> {
1114        self.list_pages(prefix, false).await
1115    }
1116
1117    /// Lists the objects and the common prefixes under `prefix`, with the
1118    /// delimiter `/`, over all pages.
1119    ///
1120    /// Each key and each common prefix is relative to the prefix of the
1121    /// repository.
1122    ///
1123    /// # Errors
1124    ///
1125    /// The errors of [`list`](Bucket::list).
1126    pub async fn list_delimited(&self, prefix: &str) -> Result<Listing> {
1127        self.list_pages(prefix, true).await
1128    }
1129
1130    /// Lists the incomplete multipart uploads of the keys of the repository,
1131    /// over all pages.
1132    ///
1133    /// The request is `ListMultipartUploads` with the prefix `PREFIX/`. With
1134    /// no prefix, the list covers the whole bucket, and the client keeps an
1135    /// upload only if its key is a key of a bucket repository. A 404 with
1136    /// the code `NoSuchUpload` is an empty list, because a server can answer
1137    /// a bucket with no upload in this way.
1138    ///
1139    /// # Errors
1140    ///
1141    /// The errors of [`list`](Bucket::list), with the markers of the next
1142    /// page in place of the continuation token. The rule of progress is
1143    /// different:
1144    ///
1145    /// - The `NextKeyMarker` of each truncated page does not come before the
1146    ///   key marker of the page before it, in the byte order of UTF-8.
1147    /// - While the key marker stays the same, the `NextUploadIdMarker` of
1148    ///   each truncated page is one that no earlier page gave for that key
1149    ///   marker. S3 sorts the uploads of one key by the time of their start,
1150    ///   and not by the upload id, so the upload id markers of one key have
1151    ///   no order.
1152    ///
1153    /// So a truncated page that holds no upload must move the markers.
1154    pub async fn list_uploads(&self) -> Result<Vec<Upload>> {
1155        let repository = self.repository_prefix();
1156        let mut uploads = Vec::new();
1157        let mut markers: Option<(String, String)> = None;
1158        // The upload id markers of the key marker of `markers`.
1159        let mut ids: HashSet<String> = HashSet::new();
1160        loop {
1161            let mut query = "uploads".to_owned();
1162            if !repository.is_empty() {
1163                query.push_str("&prefix=");
1164                query.push_str(&encode_query(&repository));
1165            }
1166            query.push_str("&encoding-type=url");
1167            if let Some((key_marker, id_marker)) = &markers {
1168                query.push_str("&key-marker=");
1169                query.push_str(&encode_query(key_marker));
1170                query.push_str("&upload-id-marker=");
1171                query.push_str(&encode_query(id_marker));
1172            }
1173            let body = match self.fetch_listing(&query).await {
1174                Ok(body) => body,
1175                Err(Error::S3 {
1176                    status: 404,
1177                    code: Some(code),
1178                    ..
1179                }) if code == "NoSuchUpload" => return Ok(uploads),
1180                Err(e) => return Err(e),
1181            };
1182            let page = match xml::list_uploads(&body).map_err(|why| self.unusable(&why))? {
1183                Doc::Result(page) => page,
1184                Doc::Error(doc) => return Err(self.answer_error(200, None, Some(doc), None)),
1185            };
1186            for (key, upload_id, initiated) in page.uploads {
1187                let key = self.listed(&key, page.encoded, &repository, repository.len())?;
1188                if is_repository_key(&key) {
1189                    uploads.push(Upload {
1190                        key,
1191                        upload_id,
1192                        initiated,
1193                    });
1194                }
1195            }
1196            if !page.truncated {
1197                return Ok(uploads);
1198            }
1199            let key_marker = page
1200                .next_key_marker
1201                .filter(|marker| !marker.is_empty())
1202                .map(|marker| decode_listed(&marker, page.encoded));
1203            let id_marker = page.next_upload_id_marker.filter(|id| !id.is_empty());
1204            let (Some(key_marker), Some(id_marker)) = (key_marker, id_marker) else {
1205                return Err(
1206                    self.unusable("a truncated page has no NextKeyMarker or no NextUploadIdMarker")
1207                );
1208            };
1209            match &markers {
1210                Some((earlier, _)) if key_marker < *earlier => {
1211                    return Err(self.unusable(
1212                        "the markers of a page do not move past the markers of the page \
1213                         before it: its NextKeyMarker comes before the key marker",
1214                    ));
1215                }
1216                Some((earlier, _)) if key_marker == *earlier => {
1217                    if !ids.insert(id_marker.clone()) {
1218                        return Err(self.unusable(
1219                            "the markers of a page do not move past the markers of the earlier \
1220                             pages: an earlier page gave the same NextUploadIdMarker for the \
1221                             same NextKeyMarker",
1222                        ));
1223                    }
1224                }
1225                _ => {
1226                    ids.clear();
1227                    ids.insert(id_marker.clone());
1228                }
1229            }
1230            markers = Some((key_marker, id_marker));
1231        }
1232    }
1233
1234    /// Lists the objects under `prefix`, with the delimiter `/` if
1235    /// `delimited` is `true`.
1236    async fn list_pages(&self, prefix: &str, delimited: bool) -> Result<Listing> {
1237        check_list_prefix(prefix)?;
1238        let strip = self.repository_prefix().len();
1239        let full = self.full_key(prefix);
1240        let mut listing = Listing::default();
1241        let mut token: Option<String> = None;
1242        // The last key or common prefix of the earlier pages.
1243        let mut last: Option<String> = None;
1244        // The continuation tokens of the pages after the last page with a
1245        // key or a common prefix, and of that page.
1246        let mut tokens: HashSet<String> = HashSet::new();
1247        // The number of truncated pages in a row with no key and no common
1248        // prefix.
1249        let mut empty_run = 0usize;
1250        loop {
1251            let mut query = format!(
1252                "list-type=2&prefix={}&encoding-type=url",
1253                encode_query(&full)
1254            );
1255            if delimited {
1256                query.push_str("&delimiter=%2F");
1257            }
1258            if let Some(token) = &token {
1259                query.push_str("&continuation-token=");
1260                query.push_str(&encode_query(token));
1261            }
1262            let body = self.fetch_listing(&query).await?;
1263            let page = match xml::list_objects(&body).map_err(|why| self.unusable(&why))? {
1264                Doc::Result(page) => page,
1265                Doc::Error(doc) => return Err(self.answer_error(200, None, Some(doc), None)),
1266            };
1267            let (objects, prefixes) = (listing.objects.len(), listing.common_prefixes.len());
1268            for (key, size) in page.contents {
1269                let key = self.listed(&key, page.encoded, &full, strip)?;
1270                listing.objects.push(Listed { key, size });
1271            }
1272            for common in page.prefixes {
1273                let common = self.listed(&common, page.encoded, &full, strip)?;
1274                listing.common_prefixes.push(common);
1275            }
1276            let entries = listing.objects[objects..]
1277                .iter()
1278                .map(|listed| listed.key.as_str())
1279                .chain(
1280                    listing.common_prefixes[prefixes..]
1281                        .iter()
1282                        .map(String::as_str),
1283                );
1284            let (first, page_last) = entries.fold((None, None), |(low, high), entry| {
1285                (
1286                    low.filter(|low| low <= &entry).or(Some(entry)),
1287                    high.filter(|high| high >= &entry).or(Some(entry)),
1288                )
1289            });
1290            if let (Some(first), Some(last)) = (first, &last)
1291                && first <= last.as_str()
1292            {
1293                return Err(self.unusable(&format!(
1294                    "a page does not move past the keys of the earlier pages: it holds {:?} \
1295                     after {:?}",
1296                    shown(first),
1297                    shown(last)
1298                )));
1299            }
1300            if let Some(page_last) = page_last {
1301                last = Some(page_last.to_owned());
1302            }
1303            if !page.truncated {
1304                return Ok(listing);
1305            }
1306            let Some(next) = page.token.filter(|token| !token.is_empty()) else {
1307                return Err(self.unusable("a truncated page has no NextContinuationToken"));
1308            };
1309            if page_last.is_some() {
1310                tokens.clear();
1311                empty_run = 0;
1312            } else {
1313                empty_run += 1;
1314                if empty_run > MAX_EMPTY_PAGES {
1315                    return Err(self.unusable(&format!(
1316                        "more than {MAX_EMPTY_PAGES} truncated pages in a row hold no key and \
1317                         no common prefix"
1318                    )));
1319                }
1320            }
1321            if !tokens.insert(next.clone()) {
1322                return Err(self.unusable(
1323                    "a truncated page holds no key and no common prefix, and gives the \
1324                     continuation token of an earlier page",
1325                ));
1326            }
1327            token = Some(next);
1328        }
1329    }
1330
1331    /// Fetches the listing of `query` on the bucket, and returns its body.
1332    async fn fetch_listing(&self, query: &str) -> Result<Vec<u8>> {
1333        let target = self.target("", query);
1334        let mut refetch = self.fetcher.refetching(FetchRequest {
1335            max_size: Some(XML_CAP),
1336            max_error_body: Some(XML_CAP),
1337            ..target.fetch()
1338        });
1339        loop {
1340            let mut body = match refetch.fetch().await {
1341                Ok(Fetched::Body(body)) => body,
1342                Ok(Fetched::NotModified) => {
1343                    return Err(self.unusable("the server answered a list with 304"));
1344                }
1345                Err(ostrya_fetch::Error::FetchTooLarge { .. }) => {
1346                    return Err(self.listing_too_large());
1347                }
1348                Err(ostrya_fetch::Error::HttpStatus {
1349                    status, response, ..
1350                }) => return Err(self.status_error(status, response.as_deref(), None)),
1351                Err(e) => return Err(Error::Fetch(e)),
1352            };
1353            let declared = body.content_length();
1354            match read_whole(&mut body, declared, XML_CAP, MAX_RESERVE).await {
1355                Ok(bytes) => return Ok(bytes),
1356                Err(e) if e.kind() == ErrorKind::FileTooLarge => {
1357                    return Err(self.listing_too_large());
1358                }
1359                Err(e) => {
1360                    drop(body);
1361                    refetch.retry(e).await?;
1362                }
1363            }
1364        }
1365    }
1366
1367    /// Sends one upload request of `method` to `path` with the query
1368    /// `query`, `body`, and `headers`, and reads the answer whole. An empty
1369    /// query is no query.
1370    async fn send(
1371        &self,
1372        method: UploadMethod,
1373        path: &str,
1374        query: &str,
1375        body: UploadBody,
1376        headers: &[(String, String)],
1377    ) -> Result<Sent> {
1378        let target = self.target(path, query);
1379        let request = UploadRequest {
1380            method,
1381            max_response: XML_CAP,
1382            headers,
1383            ..target.upload(body)
1384        };
1385        match self.fetcher.upload(request).await {
1386            Ok(uploaded) => Ok(Sent::Reply(read_reply(uploaded).await)),
1387            Err(e) if !e.is_unsent() => Ok(Sent::Interrupted(e)),
1388            Err(e) => Err(Error::Fetch(e)),
1389        }
1390    }
1391
1392    /// Sends one request of `method` to `path` with the query `query` and
1393    /// `body` by the rule of [`Bucket`], and returns the last answer.
1394    ///
1395    /// The client sends the request again after an interrupted request and
1396    /// after a 408, 429, or 5xx, at most `max_retries` times. Each request
1397    /// shares the bytes of `body`.
1398    async fn send_retrying(
1399        &self,
1400        method: UploadMethod,
1401        path: &str,
1402        query: &str,
1403        body: &UploadBody,
1404    ) -> Result<Reply> {
1405        let mut round = 0;
1406        loop {
1407            match self.send(method, path, query, copy(body), &[]).await? {
1408                Sent::Reply(reply) if is_retryable(reply.status) && round < self.max_retries => {}
1409                Sent::Reply(reply) => return Ok(reply),
1410                Sent::Interrupted(_) if round < self.max_retries => {}
1411                Sent::Interrupted(e) => return Err(Error::Fetch(e)),
1412            }
1413            round += 1;
1414            ostrya_rt::Timer::after(backoff(round)).await;
1415        }
1416    }
1417
1418    /// Writes `body` to the full key `full`, whose encoded path is `path`,
1419    /// with one `PUT`, and returns the `ETag` of the answer.
1420    async fn put_body(&self, full: &str, path: &str, body: UploadBody) -> Result<Option<String>> {
1421        let reply = self
1422            .send_retrying(UploadMethod::Put, path, "", &body)
1423            .await?;
1424        if is_success(reply.status) {
1425            return Ok(reply.etag);
1426        }
1427        Err(self.reply_error(reply, Some(full)))
1428    }
1429
1430    /// Writes the parts that `parts` reads to `key`, with one `PUT` for a
1431    /// body of one part and a multipart upload for a longer body.
1432    async fn put_parts<R: AsyncRead + Unpin>(
1433        &self,
1434        key: &str,
1435        mut parts: Parts<R>,
1436    ) -> Result<Option<String>> {
1437        let full = self.full_key(key);
1438        let path = encode_path(&full);
1439        let first = parts.next().await.map_err(|stop| stop.error(&full))?;
1440        if first.last {
1441            return self
1442                .put_body(&full, &path, upload_body(first.bytes).await)
1443                .await;
1444        }
1445        let upload_id = self.create_upload(&full, &path).await?;
1446        let query = upload_query(&upload_id);
1447        match self
1448            .send_parts(key, &full, &path, &query, first, parts)
1449            .await
1450        {
1451            Ok(etag) => Ok(etag),
1452            // The server holds no such upload, so the client sends no abort.
1453            Err(Failed { error, gone: true }) => Err(error),
1454            Err(Failed { error, gone: false }) => {
1455                // One abort, sent once. Its outcome does not change the
1456                // error of the call.
1457                let empty = UploadBody::bytes(Vec::new());
1458                let _ = self
1459                    .send(UploadMethod::Delete, &path, &query, empty, &[])
1460                    .await;
1461                Err(error)
1462            }
1463        }
1464    }
1465
1466    /// Sends `first` and each later part that `parts` reads to the upload
1467    /// of the query `query`, and completes the upload.
1468    ///
1469    /// After each part other than the last one, `parts` takes the buffer of
1470    /// the part back for the next part.
1471    async fn send_parts<R: AsyncRead + Unpin>(
1472        &self,
1473        key: &str,
1474        full: &str,
1475        path: &str,
1476        query: &str,
1477        first: Part,
1478        mut parts: Parts<R>,
1479    ) -> std::result::Result<Option<String>, Failed> {
1480        let mut etags = Vec::new();
1481        let mut sent = 0u64;
1482        let mut part = first;
1483        loop {
1484            sent += part.bytes.len() as u64;
1485            let last = part.last;
1486            let (etag, body) = self.upload_part(full, path, query, part).await?;
1487            etags.push(etag);
1488            if last {
1489                break;
1490            }
1491            parts.recycle(body);
1492            part = parts.next().await.map_err(|stop| stop.error(full))?;
1493        }
1494        let body = upload_body(complete_body(&etags)).await;
1495        drop(etags);
1496        self.complete_upload(key, full, path, query, body, sent)
1497            .await
1498    }
1499
1500    /// Starts a multipart upload of the full key `full`, and returns its
1501    /// upload id.
1502    ///
1503    /// The client sends the request again by the rule of [`Bucket`], and
1504    /// also after a 2xx whose body did not arrive.
1505    async fn create_upload(&self, full: &str, path: &str) -> Result<String> {
1506        let unusable = |why: &str| {
1507            self.unusable(&format!(
1508                "the answer that starts the multipart upload of {full}: {why}"
1509            ))
1510        };
1511        let mut round = 0;
1512        loop {
1513            let empty = UploadBody::bytes(Vec::new());
1514            let failure = match self
1515                .send(UploadMethod::Post, path, "uploads", empty, &[])
1516                .await?
1517            {
1518                Sent::Reply(reply) if is_success(reply.status) => match reply.body.as_deref() {
1519                    // A body that failed in transit counts as an interrupted
1520                    // request.
1521                    None => unusable("the body did not arrive"),
1522                    Some(body) => {
1523                        return match xml::initiate(body).map_err(|why| unusable(&why))? {
1524                            Doc::Result(upload_id) if upload_id.len() > MAX_UPLOAD_TOKEN => {
1525                                Err(unusable(&format!(
1526                                    "the UploadId has more than {MAX_UPLOAD_TOKEN} bytes"
1527                                )))
1528                            }
1529                            Doc::Result(upload_id) => Ok(upload_id),
1530                            Doc::Error(doc) => Err(self.answer_error(
1531                                reply.status,
1532                                reply.region.as_deref(),
1533                                Some(doc),
1534                                Some(full),
1535                            )),
1536                        };
1537                    }
1538                },
1539                Sent::Reply(reply) if is_retryable(reply.status) => {
1540                    self.reply_error(reply, Some(full))
1541                }
1542                Sent::Reply(reply) => return Err(self.reply_error(reply, Some(full))),
1543                Sent::Interrupted(e) => Error::Fetch(e),
1544            };
1545            if round >= self.max_retries {
1546                return Err(failure);
1547            }
1548            round += 1;
1549            ostrya_rt::Timer::after(backoff(round)).await;
1550        }
1551    }
1552
1553    /// Sends `part` to the upload of the query `query`, and returns the
1554    /// `ETag` of the answer with the body of the part.
1555    async fn upload_part(
1556        &self,
1557        full: &str,
1558        path: &str,
1559        query: &str,
1560        part: Part,
1561    ) -> std::result::Result<(String, UploadBody), Failed> {
1562        let number = part.number;
1563        let query = format!("partNumber={number}&{query}");
1564        let body = upload_body(part.bytes).await;
1565        let reply = self
1566            .send_retrying(UploadMethod::Put, path, &query, &body)
1567            .await?;
1568        if !is_success(reply.status) {
1569            return Err(self.upload_failed(reply, full));
1570        }
1571        let why = match reply.etag {
1572            Some(etag) if etag.len() <= MAX_UPLOAD_TOKEN => return Ok((etag, body)),
1573            Some(_) => format!("an ETag of more than {MAX_UPLOAD_TOKEN} bytes"),
1574            None => "no ETag".to_owned(),
1575        };
1576        Err(self
1577            .unusable(&format!("the answer to part {number} of {full} has {why}"))
1578            .into())
1579    }
1580
1581    /// Completes the upload of the query `query` with the
1582    /// `CompleteMultipartUpload` document `body`, and returns the `ETag` of
1583    /// the object. `sent` is the number of bytes of the parts.
1584    ///
1585    /// After an unsure request, a 404 with the code `NoSuchUpload` makes the
1586    /// client read the key `key`, by the rule of [`Bucket::put_stream`].
1587    async fn complete_upload(
1588        &self,
1589        key: &str,
1590        full: &str,
1591        path: &str,
1592        query: &str,
1593        body: UploadBody,
1594        sent: u64,
1595    ) -> std::result::Result<Option<String>, Failed> {
1596        let mut round = 0;
1597        // `true` after a request whose outcome is not known.
1598        let mut unsure = false;
1599        loop {
1600            let failure = match self
1601                .send(UploadMethod::Post, path, query, copy(&body), &[])
1602                .await?
1603            {
1604                Sent::Reply(reply) if is_success(reply.status) => {
1605                    unsure = true;
1606                    match reply.body.as_deref().map(xml::complete) {
1607                        Some(Ok(Doc::Result(etag))) => return Ok(etag.or(reply.etag)),
1608                        Some(Ok(Doc::Error(doc))) => self.answer_error(
1609                            reply.status,
1610                            reply.region.as_deref(),
1611                            Some(doc),
1612                            Some(full),
1613                        ),
1614                        Some(Err(why)) => self.unusable(&format!(
1615                            "the answer that completes the multipart upload of {full}: {why}"
1616                        )),
1617                        None => self.unusable(&format!(
1618                            "the answer that completes the multipart upload of {full}: the \
1619                             body did not arrive"
1620                        )),
1621                    }
1622                }
1623                Sent::Reply(reply) if unsure && is_no_such_upload(&reply) => {
1624                    return self
1625                        .completed_object(key, full, sent)
1626                        .await
1627                        .map_err(|error| Failed { error, gone: true });
1628                }
1629                Sent::Reply(reply) if is_retryable(reply.status) => {
1630                    unsure = true;
1631                    self.reply_error(reply, Some(full))
1632                }
1633                Sent::Reply(reply) => return Err(self.upload_failed(reply, full)),
1634                Sent::Interrupted(e) => {
1635                    unsure = true;
1636                    Error::Fetch(e)
1637                }
1638            };
1639            if round >= self.max_retries {
1640                return Err(failure.into());
1641            }
1642            round += 1;
1643            ostrya_rt::Timer::after(backoff(round)).await;
1644        }
1645    }
1646
1647    /// Reads the key `key`, whose full key is `full`, after a 404 with the
1648    /// code `NoSuchUpload` to the completion of its upload, and returns the
1649    /// `ETag` of the object if its declared length is `sent`.
1650    ///
1651    /// The client reads no byte of the object.
1652    async fn completed_object(&self, key: &str, full: &str, sent: u64) -> Result<Option<String>> {
1653        let held = match self.get_stream(key).await? {
1654            Some(stream) => match stream.content_length() {
1655                Some(length) if length == sent => return Ok(stream.etag),
1656                Some(length) => format!("an object of {length} bytes"),
1657                None => "an object of no declared length".to_owned(),
1658            },
1659            None => "no object".to_owned(),
1660        };
1661        Err(self.unusable(&format!(
1662            "the answer that completes the multipart upload of {full} is 404 NoSuchUpload \
1663             after a request with no known outcome, and the key holds {held}, not the \
1664             {sent} bytes of the parts"
1665        )))
1666    }
1667
1668    /// Returns the failure of an unsuccessful `reply` to a request of the
1669    /// multipart upload of the full key `full`.
1670    fn upload_failed(&self, reply: Reply, full: &str) -> Failed {
1671        let gone = is_no_such_upload(&reply);
1672        Failed {
1673            error: self.reply_error(reply, Some(full)),
1674            gone,
1675        }
1676    }
1677
1678    /// Reads the object of the full key `full` as a stream, and compares it
1679    /// with `body`.
1680    ///
1681    /// A declared length other than the length of `body` gives
1682    /// [`Compared::Other`] with no read of the object. Else the function
1683    /// hashes the object in chunks of [`COMPARE_CHUNK`] bytes, and stops at
1684    /// the first byte past the length of `body`. `digest` keeps the SHA-256
1685    /// of `body` for a later compare.
1686    async fn compare(
1687        &self,
1688        full: &str,
1689        body: &UploadBody,
1690        digest: &mut Option<[u8; 32]>,
1691    ) -> Result<Compared> {
1692        let size = body.as_bytes().map_or(0, <[u8]>::len) as u64;
1693        let path = encode_path(full);
1694        let target = self.target(&path, "");
1695        let mut refetch = self.fetcher.refetching(FetchRequest {
1696            max_error_body: Some(XML_CAP),
1697            ..target.fetch()
1698        });
1699        let (stored, etag) = loop {
1700            let mut stream = match refetch.fetch().await {
1701                Ok(Fetched::Body(stream)) => stream,
1702                Ok(Fetched::NotModified) => return Err(not_modified(full)),
1703                Err(e) => {
1704                    self.absent_or_error(e, full, u64::MAX, is_absent)?;
1705                    return Ok(Compared::Absent);
1706                }
1707            };
1708            if stream.content_length().is_some_and(|length| length != size) {
1709                return Ok(Compared::Other);
1710            }
1711            let etag = stream.validators().etag.clone();
1712            match hash_exact(&mut stream, size).await {
1713                Ok(Some(stored)) => break (stored, etag),
1714                Ok(None) => return Ok(Compared::Other),
1715                Err(e) => {
1716                    drop(stream);
1717                    refetch.retry(e).await?;
1718                }
1719            }
1720        };
1721        let ours = match *digest {
1722            Some(ours) => ours,
1723            None => {
1724                let copy = copy(body);
1725                let ours: [u8; 32] = ostrya_rt::unblock(move || {
1726                    Sha256::digest(copy.as_bytes().unwrap_or_default()).into()
1727                })
1728                .await;
1729                *digest = Some(ours);
1730                ours
1731            }
1732        };
1733        Ok(if stored == ours {
1734            Compared::Same(etag)
1735        } else {
1736            Compared::Other
1737        })
1738    }
1739
1740    /// Returns `Ok` if the failed fetch `e` of the object `full` states that
1741    /// the key holds no object by the rule `absent`, and the error of the
1742    /// fetch otherwise.
1743    ///
1744    /// The absent-key rule runs before the region check, so an absent key is
1745    /// never a region error.
1746    fn absent_or_error(
1747        &self,
1748        e: ostrya_fetch::Error,
1749        full: &str,
1750        max_size: u64,
1751        absent: fn(u16, Option<&[u8]>) -> bool,
1752    ) -> Result<()> {
1753        match e {
1754            ostrya_fetch::Error::FetchTooLarge { .. } => Err(too_large(full, max_size)),
1755            ostrya_fetch::Error::HttpStatus {
1756                status, response, ..
1757            } => {
1758                let response = response.as_deref();
1759                if absent(status, response.and_then(ErrorResponse::body)) {
1760                    Ok(())
1761                } else {
1762                    Err(self.status_error(status, response, Some(full)))
1763                }
1764            }
1765            other => Err(Error::Fetch(other)),
1766        }
1767    }
1768
1769    /// Returns the error of an unsuccessful fetch with `status` and the kept
1770    /// `response`.
1771    fn status_error(
1772        &self,
1773        status: u16,
1774        response: Option<&ErrorResponse>,
1775        key: Option<&str>,
1776    ) -> Error {
1777        let region = response
1778            .and_then(|response| response.headers().get("x-amz-bucket-region"))
1779            .and_then(|value| value.to_str().ok());
1780        let doc = response.and_then(ErrorResponse::body).and_then(xml::error);
1781        self.answer_error(status, region, doc, key)
1782    }
1783
1784    /// Returns the error of an unsuccessful upload `reply`.
1785    fn reply_error(&self, reply: Reply, key: Option<&str>) -> Error {
1786        let doc = reply.body.as_deref().and_then(xml::error);
1787        self.answer_error(reply.status, reply.region.as_deref(), doc, key)
1788    }
1789
1790    /// Returns the error of an answer with `status`, the region header
1791    /// `region`, and the S3 `Error` document `doc`.
1792    ///
1793    /// A region of the header, else of the `Region` element, that differs
1794    /// from the region of the location gives [`Error::S3Region`]. A value
1795    /// that is not a region counts as absent.
1796    fn answer_error(
1797        &self,
1798        status: u16,
1799        region: Option<&str>,
1800        doc: Option<ErrorDoc>,
1801        key: Option<&str>,
1802    ) -> Error {
1803        let doc = doc.unwrap_or_default();
1804        let bucket_region = region
1805            .map(str::trim)
1806            .filter(|region| valid_region(region))
1807            .or_else(|| {
1808                doc.region
1809                    .as_deref()
1810                    .map(str::trim)
1811                    .filter(|region| valid_region(region))
1812            });
1813        if let Some(bucket_region) = bucket_region
1814            && bucket_region != self.location.region()
1815        {
1816            return Error::S3Region {
1817                bucket: self.location.address().bucket().to_owned(),
1818                region: self.location.region().to_owned(),
1819                bucket_region: bucket_region.to_owned(),
1820            };
1821        }
1822        Error::S3 {
1823            status,
1824            code: doc.code.as_deref().map(str::trim).map(shown),
1825            message: doc.message.as_deref().map(shown),
1826            key: key.map(str::to_owned),
1827        }
1828    }
1829
1830    /// Returns the key or the common prefix `text` of a listing, relative to
1831    /// the prefix of the repository, which is the first `strip` bytes.
1832    ///
1833    /// `encoded` states that the listing has the encoding type `url`. A text
1834    /// outside `requested`, the prefix of the request, fails the listing.
1835    /// `requested` starts with the prefix of the repository.
1836    fn listed(&self, text: &str, encoded: bool, requested: &str, strip: usize) -> Result<String> {
1837        let mut decoded = decode_listed(text, encoded);
1838        if !decoded.starts_with(requested) {
1839            return Err(self.unusable(&format!(
1840                "the listing holds the key {:?}, which is outside the prefix {requested:?}",
1841                shown(&decoded)
1842            )));
1843        }
1844        decoded.drain(..strip);
1845        Ok(decoded)
1846    }
1847
1848    /// Returns the target of a request to the encoded path `path`, relative
1849    /// to the bucket URL, with the query `query`. An empty query is no query.
1850    fn target<'a>(&self, path: &'a str, query: &'a str) -> RequestTarget<'a> {
1851        match &self.base {
1852            None => RequestTarget::Mirror { path, query },
1853            Some(base) if query.is_empty() => RequestTarget::Url(format!("{base}/{path}")),
1854            Some(base) => RequestTarget::Url(format!("{base}/{path}?{query}")),
1855        }
1856    }
1857
1858    /// Returns the prefix of each key of the repository: `PREFIX/`, or empty
1859    /// for an address with no prefix.
1860    fn repository_prefix(&self) -> String {
1861        match self.location.address().prefix() {
1862            "" => String::new(),
1863            prefix => format!("{prefix}/"),
1864        }
1865    }
1866
1867    /// Returns the full key of `key`, which is relative to the prefix of the
1868    /// repository.
1869    fn full_key(&self, key: &str) -> String {
1870        format!("{}{key}", self.repository_prefix())
1871    }
1872
1873    /// Returns the error of a listing that the client cannot use.
1874    fn unusable(&self, why: &str) -> Error {
1875        Error::Transport(format!(
1876            "S3: the answer of {} cannot be used: {why}",
1877            self.location.address()
1878        ))
1879    }
1880
1881    /// Returns the error of a listing page over the limit of the reader.
1882    fn listing_too_large(&self) -> Error {
1883        Error::LimitExceeded(format!(
1884            "S3: a listing page of {} is larger than {XML_CAP} bytes",
1885            self.location.address()
1886        ))
1887    }
1888}
1889
1890/// The target of one request of the client.
1891enum RequestTarget<'a> {
1892    /// A path and a query under the one mirror of the fetcher, the bucket
1893    /// URL. An empty query is no query.
1894    Mirror {
1895        /// The encoded path.
1896        path: &'a str,
1897        /// The query.
1898        query: &'a str,
1899    },
1900    /// The URL of the request, under the bucket URL.
1901    Url(String),
1902}
1903
1904impl RequestTarget<'_> {
1905    /// Returns a fetch of the target with the default of each other field.
1906    fn fetch(&self) -> FetchRequest<'_> {
1907        match self {
1908            RequestTarget::Mirror { path, query: "" } => FetchRequest::path(path),
1909            RequestTarget::Mirror { path, query } => FetchRequest::path_query(path, query),
1910            RequestTarget::Url(url) => FetchRequest::url(url),
1911        }
1912    }
1913
1914    /// Returns an upload of `body` to the target with the default of each
1915    /// other field.
1916    fn upload(&self, body: UploadBody) -> UploadRequest<'_> {
1917        match self {
1918            RequestTarget::Mirror { path, query: "" } => UploadRequest::path(path, body),
1919            RequestTarget::Mirror { path, query } => UploadRequest {
1920                target: Target::PathQuery { path, query },
1921                ..UploadRequest::path(path, body)
1922            },
1923            RequestTarget::Url(url) => UploadRequest::url(url, body),
1924        }
1925    }
1926}
1927
1928/// Returns the part size of a multipart upload of an object of `size`
1929/// bytes.
1930///
1931/// The part size is the larger of 8 MiB and `(2 * size + 1 MiB) / 10,000`,
1932/// rounded up to a whole MiB. So 10,000 parts hold `2 * size + 1 MiB` bytes,
1933/// more than the bytes of a `.filez` object whose file has `size` bytes of
1934/// content. The part size is 8 MiB up to a size of 41,942,515,712 bytes, and
1935/// 9 MiB from one byte more.
1936///
1937/// # Errors
1938///
1939/// [`Error::LimitExceeded`] if the part size is more than 5 GiB, the S3 limit
1940/// of a part. This is the case for a size of more than 26,843,545,075,712
1941/// bytes.
1942pub fn part_size(size: u64) -> Result<u64> {
1943    let too_large = || {
1944        Error::LimitExceeded(format!(
1945            "S3: an object of {size} bytes needs parts of more than {MAX_PUT} bytes, the limit \
1946             of a part"
1947        ))
1948    };
1949    let span = size
1950        .checked_mul(2)
1951        .and_then(|span| span.checked_add(MIB))
1952        .ok_or_else(too_large)?;
1953    let part = span
1954        .div_ceil(u64::from(MAX_PARTS) * MIB)
1955        .checked_mul(MIB)
1956        .ok_or_else(too_large)?
1957        .max(DEFAULT_PART);
1958    if part > MAX_PUT {
1959        return Err(too_large());
1960    }
1961    Ok(part)
1962}
1963
1964/// One part of a body that [`Parts`] read.
1965struct Part {
1966    /// The part number, from 1.
1967    number: u32,
1968    /// The bytes of the part.
1969    bytes: Vec<u8>,
1970    /// `true` if the body ends with this part.
1971    last: bool,
1972}
1973
1974/// A failure of a multipart upload after its start.
1975struct Failed {
1976    /// The error of the call.
1977    error: Error,
1978    /// `true` if the last answer to a request of the upload is a 404 with
1979    /// the code `NoSuchUpload`. The server then holds no such upload, so the
1980    /// client sends no abort.
1981    gone: bool,
1982}
1983
1984impl From<Error> for Failed {
1985    fn from(error: Error) -> Failed {
1986        Failed { error, gone: false }
1987    }
1988}
1989
1990/// Why [`Parts::next`] gave no part.
1991enum Stop {
1992    /// A read of the body failed.
1993    Io(std::io::Error),
1994    /// The part with the largest number is full, and the body goes on.
1995    TooMany {
1996        /// The largest number of parts.
1997        max_parts: u32,
1998        /// The part size.
1999        part_size: usize,
2000    },
2001}
2002
2003impl Stop {
2004    /// Returns the error of a stop of the parts of the full key `full`.
2005    fn error(self, full: &str) -> Error {
2006        match self {
2007            Stop::Io(e) => Error::Io(e),
2008            Stop::TooMany {
2009                max_parts,
2010                part_size,
2011            } => Error::LimitExceeded(format!(
2012                "S3: the body of {full} is longer than {max_parts} parts of {part_size} bytes"
2013            )),
2014        }
2015    }
2016}
2017
2018/// The reader of the parts of a body, one part after the other.
2019struct Parts<R> {
2020    body: R,
2021    part_size: usize,
2022    max_parts: u32,
2023    /// The number of the last part that [`Parts::next`] gave.
2024    number: u32,
2025    /// The first byte of the next part, which the read after a full part
2026    /// gave.
2027    carry: Option<u8>,
2028    /// The buffer of an earlier part, which [`Parts::recycle`] took back.
2029    spare: Option<Vec<u8>>,
2030}
2031
2032impl<R: AsyncRead + Unpin> Parts<R> {
2033    /// Returns the reader of the parts of `body`, each of `part_size` bytes
2034    /// other than the last one, at most `max_parts` parts.
2035    fn new(body: R, part_size: usize, max_parts: u32) -> Parts<R> {
2036        Parts {
2037            body,
2038            part_size,
2039            max_parts,
2040            number: 0,
2041            carry: None,
2042            spare: None,
2043        }
2044    }
2045
2046    /// Reads the next part.
2047    ///
2048    /// The first part starts with no capacity and grows as [`fill`] states.
2049    /// A later part reads into the buffer that [`Parts::recycle`] took back,
2050    /// with no fill of zeros. Else it starts with the capacity of a whole
2051    /// part. After a full part, the reader reads one byte more to find if the
2052    /// body goes on, and keeps it for the next part. A full part with the
2053    /// number `max_parts` and a byte after it gives [`Stop::TooMany`].
2054    async fn next(&mut self) -> std::result::Result<Part, Stop> {
2055        let mut bytes = self.spare.take().unwrap_or_default();
2056        let mut filled = 0;
2057        if let Some(byte) = self.carry.take() {
2058            match bytes.first_mut() {
2059                Some(first) => *first = byte,
2060                None => {
2061                    bytes.reserve_exact(self.part_size);
2062                    bytes.push(byte);
2063                }
2064            }
2065            filled = 1;
2066        }
2067        let filled = fill(&mut self.body, &mut bytes, filled, self.part_size)
2068            .await
2069            .map_err(Stop::Io)?;
2070        bytes.truncate(filled);
2071        self.number += 1;
2072        let mut last = true;
2073        if bytes.len() == self.part_size {
2074            let mut probe = [0u8; 1];
2075            if self.body.read(&mut probe).await.map_err(Stop::Io)? == 1 {
2076                if self.number >= self.max_parts {
2077                    return Err(Stop::TooMany {
2078                        max_parts: self.max_parts,
2079                        part_size: self.part_size,
2080                    });
2081                }
2082                self.carry = Some(probe[0]);
2083                last = false;
2084            }
2085        }
2086        Ok(Part {
2087            number: self.number,
2088            bytes,
2089            last,
2090        })
2091    }
2092
2093    /// Takes back the buffer of `body`, the body of a part that the upload
2094    /// sent, for the next part. A buffer that another body still shares
2095    /// stays with that body.
2096    fn recycle(&mut self, body: UploadBody) {
2097        self.spare = body.into_vec().ok();
2098    }
2099}
2100
2101/// Reads from `body` into `buffer`, from the byte `filled`, until the
2102/// buffer holds `limit` bytes or the body ends, and returns the number of
2103/// bytes that the buffer holds. `buffer` has a length and a capacity of at
2104/// most `limit` bytes, and `filled` is at most its length.
2105///
2106/// The read overwrites the bytes of `buffer` past `filled`, with no fill of
2107/// zeros. When the read reaches the length of `buffer`, the length doubles,
2108/// from [`FIRST_READ`] bytes, up to `limit`, and only the new bytes are
2109/// zeros. The capacity grows with the length when it must, and never passes
2110/// `limit`.
2111async fn fill(
2112    body: &mut (impl AsyncRead + Unpin),
2113    buffer: &mut Vec<u8>,
2114    mut filled: usize,
2115    limit: usize,
2116) -> std::io::Result<usize> {
2117    loop {
2118        if filled == limit {
2119            return Ok(filled);
2120        }
2121        if filled == buffer.len() {
2122            let grown = filled.saturating_mul(2).max(FIRST_READ as usize).min(limit);
2123            buffer.reserve_exact(grown - filled);
2124            buffer.resize(grown, 0);
2125        }
2126        match body.read(&mut buffer[filled..]).await? {
2127            0 => return Ok(filled),
2128            n => filled += n,
2129        }
2130    }
2131}
2132
2133/// Returns the query `uploadId=ID` of the upload `upload_id`.
2134fn upload_query(upload_id: &str) -> String {
2135    format!("uploadId={}", encode_query(upload_id))
2136}
2137
2138/// Returns the `CompleteMultipartUpload` document of the parts whose `ETag`
2139/// values are `etags`, the first one for part 1.
2140///
2141/// Each `ETag` goes as the server wrote it, with `&`, `<`, and `>` escaped.
2142fn complete_body(etags: &[String]) -> Vec<u8> {
2143    let mut body = format!("<CompleteMultipartUpload xmlns=\"{S3_NAMESPACE}\">");
2144    for (number, etag) in (1u32..).zip(etags) {
2145        body.push_str(&format!(
2146            "<Part><PartNumber>{number}</PartNumber><ETag>{}</ETag></Part>",
2147            partial_escape(etag.as_str())
2148        ));
2149    }
2150    body.push_str("</CompleteMultipartUpload>");
2151    body.into_bytes()
2152}
2153
2154/// Returns the body of `bytes`.
2155///
2156/// A body of more than [`UNBLOCK_SIZE`] bytes moves to the blocking pool,
2157/// which hashes it and gives it back with its SHA-256, with no copy of its
2158/// bytes. A smaller body has no digest, and the signer hashes it.
2159async fn upload_body(bytes: Vec<u8>) -> UploadBody {
2160    if bytes.len() <= UNBLOCK_SIZE {
2161        return UploadBody::bytes(bytes);
2162    }
2163    ostrya_rt::unblock(move || {
2164        let sha256 = Sha256::digest(&bytes).into();
2165        UploadBody::bytes_with_sha256(bytes, sha256)
2166    })
2167    .await
2168}
2169
2170/// Returns a second body with the bytes of `body`.
2171fn copy(body: &UploadBody) -> UploadBody {
2172    body.try_clone()
2173        .expect("a body of bytes has a copy that shares its bytes")
2174}
2175
2176/// Refuses a body larger than one S3 `PUT` takes.
2177fn check_put_size(key: &str, body: &[u8]) -> Result<()> {
2178    if body.len() as u64 > MAX_PUT {
2179        return Err(Error::InvalidInput(format!(
2180            "S3: the body of {key} has {} bytes, more than the {MAX_PUT}-byte limit of one PUT",
2181            body.len()
2182        )));
2183    }
2184    Ok(())
2185}
2186
2187/// Reads the status, the `ETag`, the region header, and the body of
2188/// `uploaded`.
2189async fn read_reply(uploaded: Uploaded) -> Reply {
2190    let header = |name: &str| {
2191        uploaded
2192            .headers()
2193            .get(name)
2194            .and_then(|value| value.to_str().ok())
2195            .map(str::to_owned)
2196    };
2197    let status = uploaded.status();
2198    let etag = header("etag");
2199    let region = header("x-amz-bucket-region");
2200    let withheld = uploaded.body_withheld();
2201    let mut body = uploaded.into_body();
2202    let declared = body.content_length();
2203    let body = if withheld {
2204        None
2205    } else {
2206        read_whole(&mut body, declared, XML_CAP, MAX_RESERVE)
2207            .await
2208            .ok()
2209    };
2210    Reply {
2211        status,
2212        etag,
2213        region,
2214        body,
2215    }
2216}
2217
2218/// Returns the `Code` of the S3 `Error` document of `reply`.
2219fn reply_code(reply: &Reply) -> Option<String> {
2220    reply.body.as_deref().and_then(xml::error)?.code
2221}
2222
2223/// Returns `true` if `reply` is a 404 with the code `NoSuchUpload`.
2224fn is_no_such_upload(reply: &Reply) -> bool {
2225    reply.status == 404 && reply_code(reply).is_some_and(|code| code.trim() == "NoSuchUpload")
2226}
2227
2228/// Returns `true` for a 2xx status.
2229fn is_success(status: u16) -> bool {
2230    (200..300).contains(&status)
2231}
2232
2233/// Returns `true` for a status that a later request can avoid: 408, 429,
2234/// and 5xx.
2235fn is_retryable(status: u16) -> bool {
2236    status == 408 || status == 429 || (500..600).contains(&status)
2237}
2238
2239/// Returns `true` if an answer with `status` and the whole body `body`
2240/// states an absent key: a 404 whose body holds the code `NoSuchKey`, or no
2241/// S3 code.
2242///
2243/// `body` is `None` if the body did not arrive whole. Such a 404 can come
2244/// from a missing bucket, so it is not an absent key.
2245fn is_absent(status: u16, body: Option<&[u8]>) -> bool {
2246    status == 404
2247        && body.is_some_and(|body| {
2248            xml::error(body)
2249                .and_then(|doc| doc.code)
2250                .is_none_or(|code| code.trim() == "NoSuchKey")
2251        })
2252}
2253
2254/// Returns `true` if an answer with `status` and the whole body `body`
2255/// states an absent key by the rule of a pull: an answer that [`is_absent`]
2256/// accepts, or a 403 whose body holds the code `AccessDenied`.
2257///
2258/// `body` is `None` if the body did not arrive whole. A 403 with another
2259/// code, or with no code, is not an absent key.
2260fn is_absent_or_denied(status: u16, body: Option<&[u8]>) -> bool {
2261    is_absent(status, body)
2262        || (status == 403
2263            && body
2264                .and_then(xml::error)
2265                .and_then(|doc| doc.code)
2266                .is_some_and(|code| code.trim() == "AccessDenied"))
2267}
2268
2269/// Returns `true` if an answer with `status` and the whole body `body`
2270/// states an absent key by the strict rule: a 404 whose body holds the code
2271/// `NoSuchKey`.
2272///
2273/// `body` is `None` if the body did not arrive whole. A 404 with no S3 code
2274/// can come from a proxy or from a missing bucket, so it is not an absent
2275/// key.
2276fn is_no_such_key(status: u16, body: Option<&[u8]>) -> bool {
2277    status == 404
2278        && body
2279            .and_then(xml::error)
2280            .and_then(|doc| doc.code)
2281            .is_some_and(|code| code.trim() == "NoSuchKey")
2282}
2283
2284/// Reads `body` to its end, and refuses a body larger than `limit` bytes
2285/// with [`ErrorKind::FileTooLarge`].
2286///
2287/// The vector reserves the `declared` length and one byte for the end of
2288/// the body, up to `reserve` bytes before the body arrives. With no
2289/// declared length, it reserves [`FIRST_READ`] bytes, up to `reserve`. It
2290/// then doubles as the bytes arrive, and its capacity never passes the
2291/// declared length or `limit` by more than one byte.
2292async fn read_whole(
2293    body: &mut (impl AsyncRead + Unpin),
2294    declared: Option<u64>,
2295    limit: u64,
2296    reserve: u64,
2297) -> std::io::Result<Vec<u8>> {
2298    let most = declared.map_or(limit, |declared| declared.min(limit));
2299    let ceiling = usize::try_from(most.saturating_add(1)).unwrap_or(usize::MAX);
2300    let first = usize::try_from(declared.unwrap_or(FIRST_READ).min(most).min(reserve))
2301        .unwrap_or(0)
2302        .saturating_add(1);
2303    let mut bytes = vec![0u8; first];
2304    let mut filled = 0;
2305    loop {
2306        if filled == bytes.len() {
2307            if bytes.len() >= ceiling {
2308                return Err(std::io::Error::new(
2309                    ErrorKind::FileTooLarge,
2310                    format!("the body is larger than {limit} bytes"),
2311                ));
2312            }
2313            let grown = bytes.len().saturating_mul(2).min(ceiling);
2314            bytes.reserve_exact(grown - bytes.len());
2315            bytes.resize(grown, 0);
2316        }
2317        let n = body.read(&mut bytes[filled..]).await?;
2318        if n == 0 {
2319            bytes.truncate(filled);
2320            return Ok(bytes);
2321        }
2322        filled += n;
2323    }
2324}
2325
2326/// Hashes the stream `body` with SHA-256, in chunks of [`COMPARE_CHUNK`]
2327/// bytes, if it holds exactly `size` bytes.
2328///
2329/// Returns `None` at the first byte past `size`, or at an end before `size`.
2330async fn hash_exact(
2331    body: &mut (impl AsyncRead + Unpin),
2332    size: u64,
2333) -> std::io::Result<Option<[u8; 32]>> {
2334    let chunk =
2335        usize::try_from(size.saturating_add(1)).map_or(COMPARE_CHUNK, |len| len.min(COMPARE_CHUNK));
2336    let mut buf = vec![0u8; chunk];
2337    let mut hasher = Sha256::new();
2338    let mut read = 0u64;
2339    loop {
2340        let n = body.read(&mut buf).await?;
2341        if n == 0 {
2342            return Ok((read == size).then(|| hasher.finalize().into()));
2343        }
2344        read += n as u64;
2345        if read > size {
2346            return Ok(None);
2347        }
2348        hasher.update(&buf[..n]);
2349    }
2350}
2351
2352/// Returns the delay before the request of retry `round`: 250 ms, doubled for
2353/// each round, up to 2 s.
2354fn backoff(round: u32) -> Duration {
2355    Duration::from_millis(250u64 << round.saturating_sub(1).min(3))
2356}
2357
2358/// Returns the error of an object over the limit of the caller.
2359fn too_large(key: &str, max_size: u64) -> Error {
2360    Error::LimitExceeded(format!(
2361        "S3: the object {key} is larger than the limit of {max_size} bytes"
2362    ))
2363}
2364
2365/// Returns the error of a 304 to a request with no validators.
2366fn not_modified(key: &str) -> Error {
2367    Error::Transport(format!(
2368        "S3: the server answered the read of {key}, which sent no validators, with 304"
2369    ))
2370}
2371
2372#[cfg(test)]
2373mod tests {
2374    use super::*;
2375
2376    #[test]
2377    fn the_backoff_doubles_and_stops_at_two_seconds() {
2378        let delays: Vec<u64> = (1..=6)
2379            .map(|round| backoff(round).as_millis() as u64)
2380            .collect();
2381        assert_eq!(delays, [250, 500, 1000, 2000, 2000, 2000]);
2382    }
2383
2384    #[test]
2385    fn the_retryable_statuses_are_408_429_and_5xx() {
2386        for status in [408, 429, 500, 503, 599] {
2387            assert!(is_retryable(status), "{status}");
2388        }
2389        for status in [200, 301, 400, 403, 404, 409, 412] {
2390            assert!(!is_retryable(status), "{status}");
2391        }
2392    }
2393
2394    #[test]
2395    fn an_absent_key_is_a_404_whose_body_has_no_code_or_no_such_key() {
2396        let coded = |code: &str| format!("<Error><Code>{code}</Code></Error>").into_bytes();
2397        assert!(is_absent(404, Some(b"")));
2398        assert!(is_absent(404, Some(b"not found")));
2399        assert!(is_absent(404, Some(b"<Error><Message>m</Message></Error>")));
2400        assert!(is_absent(404, Some(&coded("NoSuchKey"))));
2401        assert!(!is_absent(404, Some(&coded("NoSuchBucket"))));
2402        assert!(!is_absent(404, None));
2403        assert!(!is_absent(403, Some(b"")));
2404    }
2405
2406    #[test]
2407    fn an_absent_key_of_a_pull_is_also_a_403_whose_body_has_access_denied() {
2408        let coded = |code: &str| format!("<Error><Code>{code}</Code></Error>").into_bytes();
2409        assert!(is_absent_or_denied(403, Some(&coded("AccessDenied"))));
2410        assert!(is_absent_or_denied(403, Some(&coded(" AccessDenied\n"))));
2411        assert!(is_absent_or_denied(404, Some(b"")));
2412        assert!(is_absent_or_denied(404, Some(b"not found")));
2413        assert!(is_absent_or_denied(
2414            404,
2415            Some(b"<Error><Message>m</Message></Error>")
2416        ));
2417        assert!(is_absent_or_denied(404, Some(&coded("NoSuchKey"))));
2418        assert!(!is_absent_or_denied(
2419            403,
2420            Some(&coded("SignatureDoesNotMatch"))
2421        ));
2422        assert!(!is_absent_or_denied(
2423            403,
2424            Some(&coded("InvalidAccessKeyId"))
2425        ));
2426        assert!(!is_absent_or_denied(403, Some(b"")));
2427        assert!(!is_absent_or_denied(403, None));
2428        assert!(!is_absent_or_denied(404, Some(&coded("NoSuchBucket"))));
2429        assert!(!is_absent_or_denied(404, None));
2430        assert!(!is_absent_or_denied(410, Some(&coded("AccessDenied"))));
2431    }
2432
2433    #[test]
2434    fn a_strict_absent_key_is_a_404_whose_body_has_no_such_key() {
2435        let coded = |code: &str| format!("<Error><Code>{code}</Code></Error>").into_bytes();
2436        assert!(is_no_such_key(404, Some(&coded("NoSuchKey"))));
2437        assert!(is_no_such_key(404, Some(&coded(" NoSuchKey\n"))));
2438        assert!(!is_no_such_key(404, Some(b"")));
2439        assert!(!is_no_such_key(404, Some(b"<html>Not Found</html>")));
2440        assert!(!is_no_such_key(
2441            404,
2442            Some(b"<Error><Message>m</Message></Error>")
2443        ));
2444        assert!(!is_no_such_key(404, Some(&coded("NoSuchBucket"))));
2445        assert!(!is_no_such_key(404, None));
2446        assert!(!is_no_such_key(403, Some(&coded("NoSuchKey"))));
2447    }
2448
2449    #[test]
2450    fn a_whole_read_holds_no_capacity_past_its_limit() {
2451        ostrya_rt::block_on(async {
2452            let data = vec![b'x'; XML_CAP as usize];
2453            // No declared length: the vector doubles up to the limit and one
2454            // byte.
2455            let mut reader = futures_lite::io::Cursor::new(data.clone());
2456            let bytes = read_whole(&mut reader, None, XML_CAP, MAX_RESERVE)
2457                .await
2458                .unwrap();
2459            assert_eq!(bytes.len(), data.len());
2460            assert!(bytes.capacity() <= data.len() + 1, "{}", bytes.capacity());
2461            // A declared length: the vector reserves it and one byte.
2462            let mut reader = futures_lite::io::Cursor::new(data[..3000].to_vec());
2463            let bytes = read_whole(&mut reader, Some(3000), XML_CAP, MAX_RESERVE)
2464                .await
2465                .unwrap();
2466            assert_eq!(bytes.len(), 3000);
2467            assert!(bytes.capacity() <= 3001, "{}", bytes.capacity());
2468            // A body past the limit fails.
2469            let mut reader = futures_lite::io::Cursor::new(vec![b'x'; 11]);
2470            let err = read_whole(&mut reader, None, 10, MAX_RESERVE)
2471                .await
2472                .unwrap_err();
2473            assert_eq!(err.kind(), ErrorKind::FileTooLarge);
2474        });
2475    }
2476
2477    /// A read with a reserve over 4 MiB reserves a declared length whole, at
2478    /// once. With no declared length, it reserves 8 KiB first.
2479    #[test]
2480    fn a_whole_read_reserves_a_declared_length_at_once() {
2481        ostrya_rt::block_on(async {
2482            let size = 2 * XML_CAP as usize + 5;
2483            let limit = 4 * XML_CAP;
2484            /// A reader that records the length of the buffer of its first
2485            /// read.
2486            struct First {
2487                data: futures_lite::io::Cursor<Vec<u8>>,
2488                first: Option<usize>,
2489            }
2490            impl AsyncRead for First {
2491                fn poll_read(
2492                    mut self: Pin<&mut Self>,
2493                    cx: &mut Context<'_>,
2494                    buf: &mut [u8],
2495                ) -> Poll<std::io::Result<usize>> {
2496                    self.first.get_or_insert(buf.len());
2497                    Pin::new(&mut self.data).poll_read(cx, buf)
2498                }
2499            }
2500            let mut reader = First {
2501                data: futures_lite::io::Cursor::new(vec![b'x'; size]),
2502                first: None,
2503            };
2504            let bytes = read_whole(&mut reader, Some(size as u64), limit, limit)
2505                .await
2506                .unwrap();
2507            assert_eq!(bytes.len(), size);
2508            assert_eq!(reader.first, Some(size + 1));
2509            assert!(bytes.capacity() <= size + 1, "{}", bytes.capacity());
2510            // The listing reserve caps the first read at 4 MiB.
2511            let mut reader = First {
2512                data: futures_lite::io::Cursor::new(vec![b'x'; size]),
2513                first: None,
2514            };
2515            read_whole(&mut reader, Some(size as u64), limit, MAX_RESERVE)
2516                .await
2517                .unwrap();
2518            assert_eq!(reader.first, Some(XML_CAP as usize + 1));
2519            // No declared length: 8 KiB first, whatever the reserve.
2520            let mut reader = First {
2521                data: futures_lite::io::Cursor::new(vec![b'x'; size]),
2522                first: None,
2523            };
2524            read_whole(&mut reader, None, limit, limit).await.unwrap();
2525            assert_eq!(reader.first, Some(FIRST_READ as usize + 1));
2526        });
2527    }
2528
2529    #[test]
2530    fn the_part_size_grows_by_whole_mib_past_8_mib() {
2531        assert_eq!(part_size(0).unwrap(), 8 * MIB);
2532        assert_eq!(part_size(41_942_515_712).unwrap(), 8 * MIB);
2533        assert_eq!(part_size(41_942_515_713).unwrap(), 9 * MIB);
2534        assert_eq!(part_size(26_843_545_075_712).unwrap(), MAX_PUT);
2535        for size in [26_843_545_075_713, u64::MAX / 2, u64::MAX] {
2536            let err = part_size(size).unwrap_err();
2537            assert!(matches!(err, Error::LimitExceeded(_)), "{size}: {err}");
2538        }
2539    }
2540
2541    #[test]
2542    fn the_complete_document_lists_each_part_with_its_escaped_etag() {
2543        let etags = [
2544            "\"5d41402abc4b2a76b9719d911017c592\"".to_owned(),
2545            "\"a&b<c>\"".to_owned(),
2546        ];
2547        assert_eq!(
2548            String::from_utf8(complete_body(&etags)).unwrap(),
2549            "<CompleteMultipartUpload xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">\
2550             <Part><PartNumber>1</PartNumber>\
2551             <ETag>\"5d41402abc4b2a76b9719d911017c592\"</ETag></Part>\
2552             <Part><PartNumber>2</PartNumber><ETag>\"a&amp;b&lt;c&gt;\"</ETag></Part>\
2553             </CompleteMultipartUpload>"
2554        );
2555    }
2556
2557    /// Reads each part of `data` with parts of `part_size` bytes, at most
2558    /// `max_parts` parts, and returns the parts or the stop.
2559    fn read_parts(
2560        data: &[u8],
2561        part_size: usize,
2562        max_parts: u32,
2563    ) -> std::result::Result<Vec<Part>, Stop> {
2564        ostrya_rt::block_on(async {
2565            let mut parts = Parts::new(futures_lite::io::Cursor::new(data), part_size, max_parts);
2566            let mut read = Vec::new();
2567            loop {
2568                let part = parts.next().await?;
2569                let last = part.last;
2570                read.push(part);
2571                if last {
2572                    return Ok(read);
2573                }
2574            }
2575        })
2576    }
2577
2578    #[test]
2579    fn a_body_reads_as_numbered_parts_with_a_probe_byte_between_them() {
2580        let data: Vec<u8> = (0..10u8).collect();
2581        let Ok(parts) = read_parts(&data, 4, 3) else {
2582            panic!("three parts of four bytes hold ten bytes");
2583        };
2584        let found: Vec<(u32, &[u8], bool)> = parts
2585            .iter()
2586            .map(|part| (part.number, part.bytes.as_slice(), part.last))
2587            .collect();
2588        assert_eq!(
2589            found,
2590            [
2591                (1, &data[..4], false),
2592                (2, &data[4..8], false),
2593                (3, &data[8..], true)
2594            ]
2595        );
2596        // A body of whole parts ends with a full part, and an empty body is
2597        // one empty part.
2598        let parts = read_parts(&data[..8], 4, 3).ok().unwrap();
2599        assert_eq!(parts.len(), 2);
2600        assert!(parts[1].last && parts[1].bytes == data[4..8]);
2601        let parts = read_parts(&[], 4, 3).ok().unwrap();
2602        assert_eq!(parts.len(), 1);
2603        assert!(parts[0].last && parts[0].bytes.is_empty());
2604    }
2605
2606    #[test]
2607    fn a_body_past_the_last_part_stops_at_the_probe_byte() {
2608        assert!(read_parts(&[7u8; 12], 4, 3).is_ok());
2609        match read_parts(&[7u8; 13], 4, 3) {
2610            Err(Stop::TooMany {
2611                max_parts: 3,
2612                part_size: 4,
2613            }) => {}
2614            Err(Stop::TooMany { .. }) => panic!("another limit"),
2615            Err(Stop::Io(e)) => panic!("{e}"),
2616            Ok(parts) => panic!("{} parts", parts.len()),
2617        }
2618        let err = Stop::TooMany {
2619            max_parts: 3,
2620            part_size: 4,
2621        }
2622        .error("repo/config");
2623        assert!(matches!(err, Error::LimitExceeded(_)), "{err}");
2624        let text = err.to_string();
2625        assert!(
2626            text.contains("repo/config") && text.contains("3 parts of 4 bytes"),
2627            "{text}"
2628        );
2629    }
2630
2631    #[test]
2632    fn a_part_holds_no_capacity_past_the_part_size() {
2633        // The first part grows from 8 KiB: a small body takes a small
2634        // buffer.
2635        let small = read_parts(&[1u8; 100], 1 << 20, 3).ok().unwrap();
2636        assert_eq!(small[0].bytes.len(), 100);
2637        assert_eq!(small[0].bytes.capacity(), FIRST_READ as usize);
2638        // A part size that is not a power of two: the doubling stops at the
2639        // part size, and a later part with no buffer to take back takes the
2640        // capacity of a whole part at once.
2641        let size = 3 * FIRST_READ as usize + 5;
2642        let data = vec![2u8; 2 * size + 1];
2643        let parts = read_parts(&data, size, 3).ok().unwrap();
2644        assert_eq!(parts.len(), 3);
2645        for part in &parts[..2] {
2646            assert_eq!(part.bytes.len(), size);
2647            assert_eq!(part.bytes.capacity(), size);
2648        }
2649        assert_eq!(parts[2].bytes, [2u8]);
2650        assert_eq!(parts[2].bytes.capacity(), size);
2651    }
2652
2653    #[test]
2654    fn a_later_part_reads_into_the_buffer_that_came_back() {
2655        /// A reader of `data` that counts the zero bytes of each buffer of
2656        /// more than one byte that it gets. The probe after a full part
2657        /// reads into a buffer of one byte.
2658        struct Counting {
2659            data: futures_lite::io::Cursor<Vec<u8>>,
2660            zeros: usize,
2661        }
2662        impl AsyncRead for Counting {
2663            fn poll_read(
2664                mut self: Pin<&mut Self>,
2665                cx: &mut Context<'_>,
2666                buf: &mut [u8],
2667            ) -> Poll<std::io::Result<usize>> {
2668                if buf.len() > 1 {
2669                    self.zeros += buf.iter().filter(|byte| **byte == 0).count();
2670                }
2671                Pin::new(&mut self.data).poll_read(cx, buf)
2672            }
2673        }
2674        let size = 3 * FIRST_READ as usize + 5;
2675        let data: Vec<u8> = (0..3 * size + 1).map(|at| (at % 255) as u8 + 1).collect();
2676        ostrya_rt::block_on(async {
2677            let mut parts = Parts::new(
2678                Counting {
2679                    data: futures_lite::io::Cursor::new(data.clone()),
2680                    zeros: 0,
2681                },
2682                size,
2683                4,
2684            );
2685            // The first part grows, and the fill of zeros comes with the
2686            // growth.
2687            let first = parts.next().await.ok().unwrap();
2688            let zeros = parts.body.zeros;
2689            assert!(zeros > 0);
2690            let address = first.bytes.as_ptr();
2691            // No copy shares the body, so the second part reads into the
2692            // same buffer with no fill of zeros.
2693            parts.recycle(UploadBody::bytes(first.bytes));
2694            let second = parts.next().await.ok().unwrap();
2695            assert_eq!(second.bytes, data[size..2 * size]);
2696            assert_eq!(second.bytes.as_ptr(), address);
2697            assert_eq!(second.bytes.capacity(), size);
2698            assert_eq!(parts.body.zeros, zeros);
2699            // A copy shares the body, so the third part takes a new buffer.
2700            let body = UploadBody::bytes(second.bytes);
2701            let shared = body.try_clone().unwrap();
2702            parts.recycle(body);
2703            let third = parts.next().await.ok().unwrap();
2704            assert_eq!(third.bytes, data[2 * size..3 * size]);
2705            assert_ne!(third.bytes.as_ptr(), address);
2706            assert_eq!(third.bytes.capacity(), size);
2707            assert_eq!(shared.as_bytes(), Some(&data[size..2 * size]));
2708            let zeros = parts.body.zeros;
2709            // A short last part reads into the buffer that came back, with
2710            // no fill of zeros.
2711            let address = third.bytes.as_ptr();
2712            parts.recycle(UploadBody::bytes(third.bytes));
2713            let last = parts.next().await.ok().unwrap();
2714            assert!(last.last);
2715            assert_eq!(last.bytes, data[3 * size..]);
2716            assert_eq!(last.bytes.as_ptr(), address);
2717            assert_eq!(last.bytes.capacity(), size);
2718            assert_eq!(parts.body.zeros, zeros);
2719        });
2720    }
2721
2722    #[test]
2723    fn a_body_over_the_limit_comes_back_from_the_pool_with_its_digest() {
2724        ostrya_rt::block_on(async {
2725            let small = upload_body(vec![1; UNBLOCK_SIZE]).await;
2726            assert_eq!(small.sha256(), None);
2727            assert_eq!(small.as_bytes().map(<[u8]>::len), Some(UNBLOCK_SIZE));
2728
2729            let mut bytes = Vec::with_capacity(UNBLOCK_SIZE + 8);
2730            bytes.resize(UNBLOCK_SIZE + 1, 2);
2731            let digest: [u8; 32] = Sha256::digest(&bytes).into();
2732            let (address, capacity) = (bytes.as_ptr(), bytes.capacity());
2733            let body = upload_body(bytes).await;
2734            assert_eq!(body.sha256(), Some(digest));
2735            assert_eq!(body.as_bytes().map(<[u8]>::as_ptr), Some(address));
2736            // The buffer of the body comes back for the next part.
2737            let mut parts = Parts::new(&[][..], UNBLOCK_SIZE + 1, 2);
2738            parts.recycle(body);
2739            let spare = parts.spare.take().expect("the buffer comes back");
2740            assert_eq!(spare.as_ptr(), address);
2741            assert_eq!(spare.capacity(), capacity);
2742        });
2743    }
2744
2745    #[test]
2746    fn a_failed_read_of_the_body_stops_the_parts() {
2747        /// A reader that gives four bytes and then fails.
2748        struct Failing {
2749            given: bool,
2750        }
2751        impl AsyncRead for Failing {
2752            fn poll_read(
2753                mut self: Pin<&mut Self>,
2754                _: &mut Context<'_>,
2755                buf: &mut [u8],
2756            ) -> Poll<std::io::Result<usize>> {
2757                if self.given {
2758                    return Poll::Ready(Err(std::io::Error::other("the source failed")));
2759                }
2760                self.given = true;
2761                let n = buf.len().min(4);
2762                buf[..n].fill(9);
2763                Poll::Ready(Ok(n))
2764            }
2765        }
2766        ostrya_rt::block_on(async {
2767            let mut parts = Parts::new(Failing { given: false }, 4, 3);
2768            // The probe after the full first part fails.
2769            let Err(Stop::Io(e)) = parts.next().await else {
2770                panic!("a failed read stops the parts");
2771            };
2772            assert_eq!(e.to_string(), "the source failed");
2773            assert!(matches!(Stop::Io(e).error("k"), Error::Io(_)));
2774        });
2775    }
2776
2777    #[test]
2778    fn a_stream_hashes_only_at_its_exact_length() {
2779        ostrya_rt::block_on(async {
2780            let data = vec![b'h'; 3 * COMPARE_CHUNK + 7];
2781            let size = data.len() as u64;
2782            let digest: [u8; 32] = Sha256::digest(&data).into();
2783            let mut reader = futures_lite::io::Cursor::new(data.clone());
2784            assert_eq!(hash_exact(&mut reader, size).await.unwrap(), Some(digest));
2785            let mut reader = futures_lite::io::Cursor::new(data.clone());
2786            assert_eq!(hash_exact(&mut reader, size - 1).await.unwrap(), None);
2787            let mut reader = futures_lite::io::Cursor::new(data);
2788            assert_eq!(hash_exact(&mut reader, size + 1).await.unwrap(), None);
2789        });
2790    }
2791}