use std::collections::HashSet;
use std::io::ErrorKind;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::AtomicU64;
use std::task::{Context, Poll};
use std::time::Duration;
use futures_io::AsyncRead;
use futures_lite::io::AsyncReadExt;
use ostrya_fetch::{
Body, ErrorResponse, FetchRequest, Fetched, Fetcher, Target, UploadBody, UploadMethod,
UploadRequest, Uploaded,
};
use quick_xml::escape::partial_escape;
use sha2::{Digest, Sha256};
use super::key::{
check_key, check_list_prefix, decode_listed, encode_path, encode_query, is_repository_key,
};
use super::sigv4::valid_region;
use super::xml::{self, Doc, ErrorDoc, MAX_BODY, shown};
use super::{Location, S3Endpoint};
use crate::{Error, Result};
const XML_CAP: u64 = MAX_BODY as u64;
const MAX_EMPTY_PAGES: usize = 1000;
const MAX_PUT: u64 = 5 * 1024 * 1024 * 1024;
const MIB: u64 = 1024 * 1024;
const MIN_PART: u64 = 5 * MIB;
const DEFAULT_PART: u64 = 8 * MIB;
const MAX_PARTS: u32 = 10_000;
const MAX_UPLOAD_TOKEN: usize = 1024;
const S3_NAMESPACE: &str = "http://s3.amazonaws.com/doc/2006-03-01/";
const MAX_RESERVE: u64 = XML_CAP;
const FIRST_READ: u64 = 8 * 1024;
const COMPARE_CHUNK: usize = 64 * 1024;
const UNBLOCK_SIZE: usize = 1024 * 1024;
pub struct Bucket {
fetcher: Fetcher,
location: Location,
max_retries: u32,
base: Option<String>,
}
impl std::fmt::Debug for Bucket {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Bucket")
.field("location", &self.location)
.field("fetcher", &self.fetcher)
.finish_non_exhaustive()
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Object {
pub bytes: Vec<u8>,
pub etag: Option<String>,
}
#[derive(Debug)]
pub struct ObjectStream {
body: Body,
etag: Option<String>,
}
impl ObjectStream {
pub fn etag(&self) -> Option<&str> {
self.etag.as_deref()
}
pub fn content_length(&self) -> Option<u64> {
self.body.content_length()
}
}
impl AsyncRead for ObjectStream {
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<std::io::Result<usize>> {
Pin::new(&mut self.body).poll_read(cx, buf)
}
}
#[cfg(feature = "tokio")]
impl ostrya_rt::tokio_io::AsyncRead for ObjectStream {
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ostrya_rt::tokio_io::ReadBuf<'_>,
) -> Poll<std::io::Result<()>> {
ostrya_rt::tokio_io::AsyncRead::poll_read(Pin::new(&mut self.body), cx, buf)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum PutIfAbsent {
Created {
etag: Option<String>,
},
Present,
Matches {
etag: Option<String>,
},
Refused {
etag: Option<String>,
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum DeleteIfMatch {
Deleted,
NotMatched,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Listing {
pub objects: Vec<Listed>,
pub common_prefixes: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Listed {
pub key: String,
pub size: u64,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Upload {
pub key: String,
pub upload_id: String,
pub initiated: String,
}
struct Reply {
status: u16,
etag: Option<String>,
region: Option<String>,
body: Option<Vec<u8>>,
}
enum Sent {
Reply(Reply),
Interrupted(ostrya_fetch::Error),
}
enum Compared {
Same(Option<String>),
Other,
Absent,
}
impl Bucket {
pub async fn new(endpoint: &S3Endpoint) -> Result<Bucket> {
let location = endpoint.location.clone();
let options = endpoint.signed_options(location.bucket_url())?;
let fetcher = Fetcher::new(options).await.map_err(Error::Fetch)?;
Ok(Bucket {
fetcher,
location,
max_retries: endpoint.http.max_retries,
base: None,
})
}
pub fn from_fetcher(endpoint: &S3Endpoint, fetcher: Fetcher) -> Bucket {
Bucket {
fetcher,
location: endpoint.location.clone(),
max_retries: endpoint.http.max_retries,
base: Some(endpoint.location.bucket_url()),
}
}
pub fn counted(&self, received: Vec<Arc<AtomicU64>>) -> Bucket {
Bucket {
fetcher: self.fetcher.counted(received),
location: self.location.clone(),
max_retries: self.max_retries,
base: self.base.clone(),
}
}
pub fn location(&self) -> &Location {
&self.location
}
pub async fn get(&self, key: &str, max_size: u64) -> Result<Option<Object>> {
self.get_whole(key, max_size, is_absent).await
}
pub async fn get_strict(&self, key: &str, max_size: u64) -> Result<Option<Object>> {
self.get_whole(key, max_size, is_no_such_key).await
}
async fn get_whole(
&self,
key: &str,
max_size: u64,
absent: fn(u16, Option<&[u8]>) -> bool,
) -> Result<Option<Object>> {
check_key(key)?;
let full = self.full_key(key);
let path = encode_path(&full);
let target = self.target(&path, "");
let mut refetch = self.fetcher.refetching(FetchRequest {
max_size: Some(max_size),
max_error_body: Some(XML_CAP),
..target.fetch()
});
loop {
let mut body = match refetch.fetch().await {
Ok(Fetched::Body(body)) => body,
Ok(Fetched::NotModified) => return Err(not_modified(&full)),
Err(e) => {
self.absent_or_error(e, &full, max_size, absent)?;
return Ok(None);
}
};
let etag = body.validators().etag.clone();
let declared = body.content_length();
match read_whole(&mut body, declared, max_size, max_size).await {
Ok(bytes) => return Ok(Some(Object { bytes, etag })),
Err(e) if e.kind() == ErrorKind::FileTooLarge => {
return Err(too_large(&full, max_size));
}
Err(e) => {
drop(body);
refetch.retry(e).await?;
}
}
}
}
pub async fn get_stream(&self, key: &str) -> Result<Option<ObjectStream>> {
self.open_stream(key, is_absent).await
}
pub async fn get_stream_strict(&self, key: &str) -> Result<Option<ObjectStream>> {
self.open_stream(key, is_no_such_key).await
}
async fn open_stream(
&self,
key: &str,
absent: fn(u16, Option<&[u8]>) -> bool,
) -> Result<Option<ObjectStream>> {
check_key(key)?;
let full = self.full_key(key);
let path = encode_path(&full);
let target = self.target(&path, "");
let fetched = self
.fetcher
.fetch(FetchRequest {
max_error_body: Some(XML_CAP),
..target.fetch()
})
.await;
match fetched {
Ok(Fetched::Body(body)) => {
let etag = body.validators().etag.clone();
Ok(Some(ObjectStream { body, etag }))
}
Ok(Fetched::NotModified) => Err(not_modified(&full)),
Err(e) => {
self.absent_or_error(e, &full, u64::MAX, absent)?;
Ok(None)
}
}
}
pub async fn exists(&self, key: &str) -> Result<bool> {
self.probe(key, is_absent).await
}
pub async fn exists_strict(&self, key: &str) -> Result<bool> {
self.probe(key, is_no_such_key).await
}
async fn probe(&self, key: &str, absent: fn(u16, Option<&[u8]>) -> bool) -> Result<bool> {
check_key(key)?;
let full = self.full_key(key);
let path = encode_path(&full);
let target = self.target(&path, "");
let range = [("Range".to_owned(), "bytes=0-0".to_owned())];
let fetched = self
.fetcher
.fetch(FetchRequest {
headers: &range,
max_size: Some(1),
max_error_body: Some(XML_CAP),
..target.fetch()
})
.await;
match fetched {
Ok(Fetched::Body(mut body)) => {
if body.content_length().is_some_and(|length| length <= 1) {
let mut bytes = [0u8; 8];
while let Ok(1..) = body.read(&mut bytes).await {}
}
Ok(true)
}
Ok(Fetched::NotModified) => Err(not_modified(&full)),
Err(ostrya_fetch::Error::FetchTooLarge { .. }) => Ok(true),
Err(ostrya_fetch::Error::HttpStatus { status: 416, .. }) => Ok(true),
Err(e) => {
self.absent_or_error(e, &full, 1, absent)?;
Ok(false)
}
}
}
pub async fn put(&self, key: &str, body: Vec<u8>) -> Result<Option<String>> {
check_key(key)?;
check_put_size(key, &body)?;
let full = self.full_key(key);
let path = encode_path(&full);
self.put_body(&full, &path, upload_body(body).await).await
}
pub async fn put_stream<R>(&self, key: &str, body: R, part_size: u64) -> Result<Option<String>>
where
R: AsyncRead + Unpin + Send,
{
check_key(key)?;
let size = usize::try_from(part_size)
.ok()
.filter(|_| (MIN_PART..=MAX_PUT).contains(&part_size))
.ok_or_else(|| {
Error::InvalidInput(format!(
"S3: the part size {part_size} of {key} is outside the range of \
{MIN_PART} to {MAX_PUT} bytes of a part"
))
})?;
self.put_parts(key, Parts::new(body, size, MAX_PARTS)).await
}
pub async fn put_if_absent(&self, key: &str, body: Vec<u8>) -> Result<PutIfAbsent> {
check_key(key)?;
check_put_size(key, &body)?;
let full = self.full_key(key);
let path = encode_path(&full);
let body = upload_body(body).await;
let headers = [("If-None-Match".to_owned(), "*".to_owned())];
let mut round = 0;
let mut unsure = false;
let mut digest = body.sha256();
loop {
match self
.send(UploadMethod::Put, &path, "", copy(&body), &headers)
.await?
{
Sent::Reply(reply) if is_success(reply.status) => {
return Ok(PutIfAbsent::Created { etag: reply.etag });
}
Sent::Reply(reply) if reply.status == 412 => {
if !unsure {
return Ok(PutIfAbsent::Present);
}
return Ok(match self.compare(&full, &body, &mut digest).await? {
Compared::Same(etag) => PutIfAbsent::Refused { etag },
Compared::Other | Compared::Absent => PutIfAbsent::Present,
});
}
Sent::Reply(reply)
if reply.status == 409
&& reply_code(&reply).as_deref() == Some("ConditionalRequestConflict")
&& round < self.max_retries => {}
Sent::Reply(reply) if is_retryable(reply.status) && round < self.max_retries => {
unsure = true;
}
Sent::Reply(reply) => return Err(self.reply_error(reply, Some(&full))),
Sent::Interrupted(e) => match self.compare(&full, &body, &mut digest).await? {
Compared::Same(etag) => return Ok(PutIfAbsent::Matches { etag }),
Compared::Other => return Ok(PutIfAbsent::Present),
Compared::Absent if round < self.max_retries => unsure = true,
Compared::Absent => return Err(Error::Fetch(e)),
},
}
round += 1;
ostrya_rt::Timer::after(backoff(round)).await;
}
}
pub async fn delete(&self, key: &str) -> Result<()> {
check_key(key)?;
let full = self.full_key(key);
let path = encode_path(&full);
let mut round = 0;
loop {
let empty = UploadBody::bytes(Vec::new());
match self
.send(UploadMethod::Delete, &path, "", empty, &[])
.await?
{
Sent::Reply(reply) if is_success(reply.status) => return Ok(()),
Sent::Reply(reply) if is_absent(reply.status, reply.body.as_deref()) => {
return Ok(());
}
Sent::Reply(reply) if is_retryable(reply.status) && round < self.max_retries => {}
Sent::Reply(reply) => return Err(self.reply_error(reply, Some(&full))),
Sent::Interrupted(_) if round < self.max_retries => {}
Sent::Interrupted(e) => return Err(Error::Fetch(e)),
}
round += 1;
ostrya_rt::Timer::after(backoff(round)).await;
}
}
pub async fn delete_if_match(&self, key: &str, etag: &str) -> Result<DeleteIfMatch> {
check_key(key)?;
if etag.is_empty() || etag.len() > MAX_UPLOAD_TOKEN {
return Err(Error::InvalidInput(format!(
"S3: the ETag of a conditional delete of {key} is empty or longer than \
{MAX_UPLOAD_TOKEN} bytes"
)));
}
let full = self.full_key(key);
let path = encode_path(&full);
let headers = [("If-Match".to_owned(), etag.to_owned())];
let mut round = 0;
let mut unsure = false;
loop {
let empty = UploadBody::bytes(Vec::new());
match self
.send(UploadMethod::Delete, &path, "", empty, &headers)
.await?
{
Sent::Reply(reply) if is_success(reply.status) => {
return Ok(DeleteIfMatch::Deleted);
}
Sent::Reply(reply)
if reply.status == 412 || is_absent(reply.status, reply.body.as_deref()) =>
{
if !unsure {
return Ok(DeleteIfMatch::NotMatched);
}
return Ok(if self.exists(key).await? {
DeleteIfMatch::NotMatched
} else {
DeleteIfMatch::Deleted
});
}
Sent::Reply(reply) if is_retryable(reply.status) && round < self.max_retries => {
unsure = true;
}
Sent::Reply(reply) => return Err(self.reply_error(reply, Some(&full))),
Sent::Interrupted(_) if round < self.max_retries => unsure = true,
Sent::Interrupted(e) => return Err(Error::Fetch(e)),
}
round += 1;
ostrya_rt::Timer::after(backoff(round)).await;
}
}
pub async fn abort_upload(&self, key: &str, upload_id: &str) -> Result<()> {
check_key(key)?;
if upload_id.is_empty() {
return Err(Error::InvalidInput(format!(
"S3: the upload id of an abort of {key} is empty"
)));
}
let full = self.full_key(key);
let path = encode_path(&full);
let query = upload_query(upload_id);
let empty = UploadBody::bytes(Vec::new());
let reply = self
.send_retrying(UploadMethod::Delete, &path, &query, &empty)
.await?;
if is_success(reply.status) || is_no_such_upload(&reply) {
return Ok(());
}
Err(self.reply_error(reply, Some(&full)))
}
pub async fn list(&self, prefix: &str) -> Result<Listing> {
self.list_pages(prefix, false).await
}
pub async fn list_delimited(&self, prefix: &str) -> Result<Listing> {
self.list_pages(prefix, true).await
}
pub async fn list_uploads(&self) -> Result<Vec<Upload>> {
let repository = self.repository_prefix();
let mut uploads = Vec::new();
let mut markers: Option<(String, String)> = None;
let mut ids: HashSet<String> = HashSet::new();
loop {
let mut query = "uploads".to_owned();
if !repository.is_empty() {
query.push_str("&prefix=");
query.push_str(&encode_query(&repository));
}
query.push_str("&encoding-type=url");
if let Some((key_marker, id_marker)) = &markers {
query.push_str("&key-marker=");
query.push_str(&encode_query(key_marker));
query.push_str("&upload-id-marker=");
query.push_str(&encode_query(id_marker));
}
let body = match self.fetch_listing(&query).await {
Ok(body) => body,
Err(Error::S3 {
status: 404,
code: Some(code),
..
}) if code == "NoSuchUpload" => return Ok(uploads),
Err(e) => return Err(e),
};
let page = match xml::list_uploads(&body).map_err(|why| self.unusable(&why))? {
Doc::Result(page) => page,
Doc::Error(doc) => return Err(self.answer_error(200, None, Some(doc), None)),
};
for (key, upload_id, initiated) in page.uploads {
let key = self.listed(&key, page.encoded, &repository, repository.len())?;
if is_repository_key(&key) {
uploads.push(Upload {
key,
upload_id,
initiated,
});
}
}
if !page.truncated {
return Ok(uploads);
}
let key_marker = page
.next_key_marker
.filter(|marker| !marker.is_empty())
.map(|marker| decode_listed(&marker, page.encoded));
let id_marker = page.next_upload_id_marker.filter(|id| !id.is_empty());
let (Some(key_marker), Some(id_marker)) = (key_marker, id_marker) else {
return Err(
self.unusable("a truncated page has no NextKeyMarker or no NextUploadIdMarker")
);
};
match &markers {
Some((earlier, _)) if key_marker < *earlier => {
return Err(self.unusable(
"the markers of a page do not move past the markers of the page \
before it: its NextKeyMarker comes before the key marker",
));
}
Some((earlier, _)) if key_marker == *earlier => {
if !ids.insert(id_marker.clone()) {
return Err(self.unusable(
"the markers of a page do not move past the markers of the earlier \
pages: an earlier page gave the same NextUploadIdMarker for the \
same NextKeyMarker",
));
}
}
_ => {
ids.clear();
ids.insert(id_marker.clone());
}
}
markers = Some((key_marker, id_marker));
}
}
async fn list_pages(&self, prefix: &str, delimited: bool) -> Result<Listing> {
check_list_prefix(prefix)?;
let strip = self.repository_prefix().len();
let full = self.full_key(prefix);
let mut listing = Listing::default();
let mut token: Option<String> = None;
let mut last: Option<String> = None;
let mut tokens: HashSet<String> = HashSet::new();
let mut empty_run = 0usize;
loop {
let mut query = format!(
"list-type=2&prefix={}&encoding-type=url",
encode_query(&full)
);
if delimited {
query.push_str("&delimiter=%2F");
}
if let Some(token) = &token {
query.push_str("&continuation-token=");
query.push_str(&encode_query(token));
}
let body = self.fetch_listing(&query).await?;
let page = match xml::list_objects(&body).map_err(|why| self.unusable(&why))? {
Doc::Result(page) => page,
Doc::Error(doc) => return Err(self.answer_error(200, None, Some(doc), None)),
};
let (objects, prefixes) = (listing.objects.len(), listing.common_prefixes.len());
for (key, size) in page.contents {
let key = self.listed(&key, page.encoded, &full, strip)?;
listing.objects.push(Listed { key, size });
}
for common in page.prefixes {
let common = self.listed(&common, page.encoded, &full, strip)?;
listing.common_prefixes.push(common);
}
let entries = listing.objects[objects..]
.iter()
.map(|listed| listed.key.as_str())
.chain(
listing.common_prefixes[prefixes..]
.iter()
.map(String::as_str),
);
let (first, page_last) = entries.fold((None, None), |(low, high), entry| {
(
low.filter(|low| low <= &entry).or(Some(entry)),
high.filter(|high| high >= &entry).or(Some(entry)),
)
});
if let (Some(first), Some(last)) = (first, &last)
&& first <= last.as_str()
{
return Err(self.unusable(&format!(
"a page does not move past the keys of the earlier pages: it holds {:?} \
after {:?}",
shown(first),
shown(last)
)));
}
if let Some(page_last) = page_last {
last = Some(page_last.to_owned());
}
if !page.truncated {
return Ok(listing);
}
let Some(next) = page.token.filter(|token| !token.is_empty()) else {
return Err(self.unusable("a truncated page has no NextContinuationToken"));
};
if page_last.is_some() {
tokens.clear();
empty_run = 0;
} else {
empty_run += 1;
if empty_run > MAX_EMPTY_PAGES {
return Err(self.unusable(&format!(
"more than {MAX_EMPTY_PAGES} truncated pages in a row hold no key and \
no common prefix"
)));
}
}
if !tokens.insert(next.clone()) {
return Err(self.unusable(
"a truncated page holds no key and no common prefix, and gives the \
continuation token of an earlier page",
));
}
token = Some(next);
}
}
async fn fetch_listing(&self, query: &str) -> Result<Vec<u8>> {
let target = self.target("", query);
let mut refetch = self.fetcher.refetching(FetchRequest {
max_size: Some(XML_CAP),
max_error_body: Some(XML_CAP),
..target.fetch()
});
loop {
let mut body = match refetch.fetch().await {
Ok(Fetched::Body(body)) => body,
Ok(Fetched::NotModified) => {
return Err(self.unusable("the server answered a list with 304"));
}
Err(ostrya_fetch::Error::FetchTooLarge { .. }) => {
return Err(self.listing_too_large());
}
Err(ostrya_fetch::Error::HttpStatus {
status, response, ..
}) => return Err(self.status_error(status, response.as_deref(), None)),
Err(e) => return Err(Error::Fetch(e)),
};
let declared = body.content_length();
match read_whole(&mut body, declared, XML_CAP, MAX_RESERVE).await {
Ok(bytes) => return Ok(bytes),
Err(e) if e.kind() == ErrorKind::FileTooLarge => {
return Err(self.listing_too_large());
}
Err(e) => {
drop(body);
refetch.retry(e).await?;
}
}
}
}
async fn send(
&self,
method: UploadMethod,
path: &str,
query: &str,
body: UploadBody,
headers: &[(String, String)],
) -> Result<Sent> {
let target = self.target(path, query);
let request = UploadRequest {
method,
max_response: XML_CAP,
headers,
..target.upload(body)
};
match self.fetcher.upload(request).await {
Ok(uploaded) => Ok(Sent::Reply(read_reply(uploaded).await)),
Err(e) if !e.is_unsent() => Ok(Sent::Interrupted(e)),
Err(e) => Err(Error::Fetch(e)),
}
}
async fn send_retrying(
&self,
method: UploadMethod,
path: &str,
query: &str,
body: &UploadBody,
) -> Result<Reply> {
let mut round = 0;
loop {
match self.send(method, path, query, copy(body), &[]).await? {
Sent::Reply(reply) if is_retryable(reply.status) && round < self.max_retries => {}
Sent::Reply(reply) => return Ok(reply),
Sent::Interrupted(_) if round < self.max_retries => {}
Sent::Interrupted(e) => return Err(Error::Fetch(e)),
}
round += 1;
ostrya_rt::Timer::after(backoff(round)).await;
}
}
async fn put_body(&self, full: &str, path: &str, body: UploadBody) -> Result<Option<String>> {
let reply = self
.send_retrying(UploadMethod::Put, path, "", &body)
.await?;
if is_success(reply.status) {
return Ok(reply.etag);
}
Err(self.reply_error(reply, Some(full)))
}
async fn put_parts<R: AsyncRead + Unpin>(
&self,
key: &str,
mut parts: Parts<R>,
) -> Result<Option<String>> {
let full = self.full_key(key);
let path = encode_path(&full);
let first = parts.next().await.map_err(|stop| stop.error(&full))?;
if first.last {
return self
.put_body(&full, &path, upload_body(first.bytes).await)
.await;
}
let upload_id = self.create_upload(&full, &path).await?;
let query = upload_query(&upload_id);
match self
.send_parts(key, &full, &path, &query, first, parts)
.await
{
Ok(etag) => Ok(etag),
Err(Failed { error, gone: true }) => Err(error),
Err(Failed { error, gone: false }) => {
let empty = UploadBody::bytes(Vec::new());
let _ = self
.send(UploadMethod::Delete, &path, &query, empty, &[])
.await;
Err(error)
}
}
}
async fn send_parts<R: AsyncRead + Unpin>(
&self,
key: &str,
full: &str,
path: &str,
query: &str,
first: Part,
mut parts: Parts<R>,
) -> std::result::Result<Option<String>, Failed> {
let mut etags = Vec::new();
let mut sent = 0u64;
let mut part = first;
loop {
sent += part.bytes.len() as u64;
let last = part.last;
let (etag, body) = self.upload_part(full, path, query, part).await?;
etags.push(etag);
if last {
break;
}
parts.recycle(body);
part = parts.next().await.map_err(|stop| stop.error(full))?;
}
let body = upload_body(complete_body(&etags)).await;
drop(etags);
self.complete_upload(key, full, path, query, body, sent)
.await
}
async fn create_upload(&self, full: &str, path: &str) -> Result<String> {
let unusable = |why: &str| {
self.unusable(&format!(
"the answer that starts the multipart upload of {full}: {why}"
))
};
let mut round = 0;
loop {
let empty = UploadBody::bytes(Vec::new());
let failure = match self
.send(UploadMethod::Post, path, "uploads", empty, &[])
.await?
{
Sent::Reply(reply) if is_success(reply.status) => match reply.body.as_deref() {
None => unusable("the body did not arrive"),
Some(body) => {
return match xml::initiate(body).map_err(|why| unusable(&why))? {
Doc::Result(upload_id) if upload_id.len() > MAX_UPLOAD_TOKEN => {
Err(unusable(&format!(
"the UploadId has more than {MAX_UPLOAD_TOKEN} bytes"
)))
}
Doc::Result(upload_id) => Ok(upload_id),
Doc::Error(doc) => Err(self.answer_error(
reply.status,
reply.region.as_deref(),
Some(doc),
Some(full),
)),
};
}
},
Sent::Reply(reply) if is_retryable(reply.status) => {
self.reply_error(reply, Some(full))
}
Sent::Reply(reply) => return Err(self.reply_error(reply, Some(full))),
Sent::Interrupted(e) => Error::Fetch(e),
};
if round >= self.max_retries {
return Err(failure);
}
round += 1;
ostrya_rt::Timer::after(backoff(round)).await;
}
}
async fn upload_part(
&self,
full: &str,
path: &str,
query: &str,
part: Part,
) -> std::result::Result<(String, UploadBody), Failed> {
let number = part.number;
let query = format!("partNumber={number}&{query}");
let body = upload_body(part.bytes).await;
let reply = self
.send_retrying(UploadMethod::Put, path, &query, &body)
.await?;
if !is_success(reply.status) {
return Err(self.upload_failed(reply, full));
}
let why = match reply.etag {
Some(etag) if etag.len() <= MAX_UPLOAD_TOKEN => return Ok((etag, body)),
Some(_) => format!("an ETag of more than {MAX_UPLOAD_TOKEN} bytes"),
None => "no ETag".to_owned(),
};
Err(self
.unusable(&format!("the answer to part {number} of {full} has {why}"))
.into())
}
async fn complete_upload(
&self,
key: &str,
full: &str,
path: &str,
query: &str,
body: UploadBody,
sent: u64,
) -> std::result::Result<Option<String>, Failed> {
let mut round = 0;
let mut unsure = false;
loop {
let failure = match self
.send(UploadMethod::Post, path, query, copy(&body), &[])
.await?
{
Sent::Reply(reply) if is_success(reply.status) => {
unsure = true;
match reply.body.as_deref().map(xml::complete) {
Some(Ok(Doc::Result(etag))) => return Ok(etag.or(reply.etag)),
Some(Ok(Doc::Error(doc))) => self.answer_error(
reply.status,
reply.region.as_deref(),
Some(doc),
Some(full),
),
Some(Err(why)) => self.unusable(&format!(
"the answer that completes the multipart upload of {full}: {why}"
)),
None => self.unusable(&format!(
"the answer that completes the multipart upload of {full}: the \
body did not arrive"
)),
}
}
Sent::Reply(reply) if unsure && is_no_such_upload(&reply) => {
return self
.completed_object(key, full, sent)
.await
.map_err(|error| Failed { error, gone: true });
}
Sent::Reply(reply) if is_retryable(reply.status) => {
unsure = true;
self.reply_error(reply, Some(full))
}
Sent::Reply(reply) => return Err(self.upload_failed(reply, full)),
Sent::Interrupted(e) => {
unsure = true;
Error::Fetch(e)
}
};
if round >= self.max_retries {
return Err(failure.into());
}
round += 1;
ostrya_rt::Timer::after(backoff(round)).await;
}
}
async fn completed_object(&self, key: &str, full: &str, sent: u64) -> Result<Option<String>> {
let held = match self.get_stream(key).await? {
Some(stream) => match stream.content_length() {
Some(length) if length == sent => return Ok(stream.etag),
Some(length) => format!("an object of {length} bytes"),
None => "an object of no declared length".to_owned(),
},
None => "no object".to_owned(),
};
Err(self.unusable(&format!(
"the answer that completes the multipart upload of {full} is 404 NoSuchUpload \
after a request with no known outcome, and the key holds {held}, not the \
{sent} bytes of the parts"
)))
}
fn upload_failed(&self, reply: Reply, full: &str) -> Failed {
let gone = is_no_such_upload(&reply);
Failed {
error: self.reply_error(reply, Some(full)),
gone,
}
}
async fn compare(
&self,
full: &str,
body: &UploadBody,
digest: &mut Option<[u8; 32]>,
) -> Result<Compared> {
let size = body.as_bytes().map_or(0, <[u8]>::len) as u64;
let path = encode_path(full);
let target = self.target(&path, "");
let mut refetch = self.fetcher.refetching(FetchRequest {
max_error_body: Some(XML_CAP),
..target.fetch()
});
let (stored, etag) = loop {
let mut stream = match refetch.fetch().await {
Ok(Fetched::Body(stream)) => stream,
Ok(Fetched::NotModified) => return Err(not_modified(full)),
Err(e) => {
self.absent_or_error(e, full, u64::MAX, is_absent)?;
return Ok(Compared::Absent);
}
};
if stream.content_length().is_some_and(|length| length != size) {
return Ok(Compared::Other);
}
let etag = stream.validators().etag.clone();
match hash_exact(&mut stream, size).await {
Ok(Some(stored)) => break (stored, etag),
Ok(None) => return Ok(Compared::Other),
Err(e) => {
drop(stream);
refetch.retry(e).await?;
}
}
};
let ours = match *digest {
Some(ours) => ours,
None => {
let copy = copy(body);
let ours: [u8; 32] = ostrya_rt::unblock(move || {
Sha256::digest(copy.as_bytes().unwrap_or_default()).into()
})
.await;
*digest = Some(ours);
ours
}
};
Ok(if stored == ours {
Compared::Same(etag)
} else {
Compared::Other
})
}
fn absent_or_error(
&self,
e: ostrya_fetch::Error,
full: &str,
max_size: u64,
absent: fn(u16, Option<&[u8]>) -> bool,
) -> Result<()> {
match e {
ostrya_fetch::Error::FetchTooLarge { .. } => Err(too_large(full, max_size)),
ostrya_fetch::Error::HttpStatus {
status, response, ..
} => {
let response = response.as_deref();
if absent(status, response.and_then(ErrorResponse::body)) {
Ok(())
} else {
Err(self.status_error(status, response, Some(full)))
}
}
other => Err(Error::Fetch(other)),
}
}
fn status_error(
&self,
status: u16,
response: Option<&ErrorResponse>,
key: Option<&str>,
) -> Error {
let region = response
.and_then(|response| response.headers().get("x-amz-bucket-region"))
.and_then(|value| value.to_str().ok());
let doc = response.and_then(ErrorResponse::body).and_then(xml::error);
self.answer_error(status, region, doc, key)
}
fn reply_error(&self, reply: Reply, key: Option<&str>) -> Error {
let doc = reply.body.as_deref().and_then(xml::error);
self.answer_error(reply.status, reply.region.as_deref(), doc, key)
}
fn answer_error(
&self,
status: u16,
region: Option<&str>,
doc: Option<ErrorDoc>,
key: Option<&str>,
) -> Error {
let doc = doc.unwrap_or_default();
let bucket_region = region
.map(str::trim)
.filter(|region| valid_region(region))
.or_else(|| {
doc.region
.as_deref()
.map(str::trim)
.filter(|region| valid_region(region))
});
if let Some(bucket_region) = bucket_region
&& bucket_region != self.location.region()
{
return Error::S3Region {
bucket: self.location.address().bucket().to_owned(),
region: self.location.region().to_owned(),
bucket_region: bucket_region.to_owned(),
};
}
Error::S3 {
status,
code: doc.code.as_deref().map(str::trim).map(shown),
message: doc.message.as_deref().map(shown),
key: key.map(str::to_owned),
}
}
fn listed(&self, text: &str, encoded: bool, requested: &str, strip: usize) -> Result<String> {
let mut decoded = decode_listed(text, encoded);
if !decoded.starts_with(requested) {
return Err(self.unusable(&format!(
"the listing holds the key {:?}, which is outside the prefix {requested:?}",
shown(&decoded)
)));
}
decoded.drain(..strip);
Ok(decoded)
}
fn target<'a>(&self, path: &'a str, query: &'a str) -> RequestTarget<'a> {
match &self.base {
None => RequestTarget::Mirror { path, query },
Some(base) if query.is_empty() => RequestTarget::Url(format!("{base}/{path}")),
Some(base) => RequestTarget::Url(format!("{base}/{path}?{query}")),
}
}
fn repository_prefix(&self) -> String {
match self.location.address().prefix() {
"" => String::new(),
prefix => format!("{prefix}/"),
}
}
fn full_key(&self, key: &str) -> String {
format!("{}{key}", self.repository_prefix())
}
fn unusable(&self, why: &str) -> Error {
Error::Transport(format!(
"S3: the answer of {} cannot be used: {why}",
self.location.address()
))
}
fn listing_too_large(&self) -> Error {
Error::LimitExceeded(format!(
"S3: a listing page of {} is larger than {XML_CAP} bytes",
self.location.address()
))
}
}
enum RequestTarget<'a> {
Mirror {
path: &'a str,
query: &'a str,
},
Url(String),
}
impl RequestTarget<'_> {
fn fetch(&self) -> FetchRequest<'_> {
match self {
RequestTarget::Mirror { path, query: "" } => FetchRequest::path(path),
RequestTarget::Mirror { path, query } => FetchRequest::path_query(path, query),
RequestTarget::Url(url) => FetchRequest::url(url),
}
}
fn upload(&self, body: UploadBody) -> UploadRequest<'_> {
match self {
RequestTarget::Mirror { path, query: "" } => UploadRequest::path(path, body),
RequestTarget::Mirror { path, query } => UploadRequest {
target: Target::PathQuery { path, query },
..UploadRequest::path(path, body)
},
RequestTarget::Url(url) => UploadRequest::url(url, body),
}
}
}
pub fn part_size(size: u64) -> Result<u64> {
let too_large = || {
Error::LimitExceeded(format!(
"S3: an object of {size} bytes needs parts of more than {MAX_PUT} bytes, the limit \
of a part"
))
};
let span = size
.checked_mul(2)
.and_then(|span| span.checked_add(MIB))
.ok_or_else(too_large)?;
let part = span
.div_ceil(u64::from(MAX_PARTS) * MIB)
.checked_mul(MIB)
.ok_or_else(too_large)?
.max(DEFAULT_PART);
if part > MAX_PUT {
return Err(too_large());
}
Ok(part)
}
struct Part {
number: u32,
bytes: Vec<u8>,
last: bool,
}
struct Failed {
error: Error,
gone: bool,
}
impl From<Error> for Failed {
fn from(error: Error) -> Failed {
Failed { error, gone: false }
}
}
enum Stop {
Io(std::io::Error),
TooMany {
max_parts: u32,
part_size: usize,
},
}
impl Stop {
fn error(self, full: &str) -> Error {
match self {
Stop::Io(e) => Error::Io(e),
Stop::TooMany {
max_parts,
part_size,
} => Error::LimitExceeded(format!(
"S3: the body of {full} is longer than {max_parts} parts of {part_size} bytes"
)),
}
}
}
struct Parts<R> {
body: R,
part_size: usize,
max_parts: u32,
number: u32,
carry: Option<u8>,
spare: Option<Vec<u8>>,
}
impl<R: AsyncRead + Unpin> Parts<R> {
fn new(body: R, part_size: usize, max_parts: u32) -> Parts<R> {
Parts {
body,
part_size,
max_parts,
number: 0,
carry: None,
spare: None,
}
}
async fn next(&mut self) -> std::result::Result<Part, Stop> {
let mut bytes = self.spare.take().unwrap_or_default();
let mut filled = 0;
if let Some(byte) = self.carry.take() {
match bytes.first_mut() {
Some(first) => *first = byte,
None => {
bytes.reserve_exact(self.part_size);
bytes.push(byte);
}
}
filled = 1;
}
let filled = fill(&mut self.body, &mut bytes, filled, self.part_size)
.await
.map_err(Stop::Io)?;
bytes.truncate(filled);
self.number += 1;
let mut last = true;
if bytes.len() == self.part_size {
let mut probe = [0u8; 1];
if self.body.read(&mut probe).await.map_err(Stop::Io)? == 1 {
if self.number >= self.max_parts {
return Err(Stop::TooMany {
max_parts: self.max_parts,
part_size: self.part_size,
});
}
self.carry = Some(probe[0]);
last = false;
}
}
Ok(Part {
number: self.number,
bytes,
last,
})
}
fn recycle(&mut self, body: UploadBody) {
self.spare = body.into_vec().ok();
}
}
async fn fill(
body: &mut (impl AsyncRead + Unpin),
buffer: &mut Vec<u8>,
mut filled: usize,
limit: usize,
) -> std::io::Result<usize> {
loop {
if filled == limit {
return Ok(filled);
}
if filled == buffer.len() {
let grown = filled.saturating_mul(2).max(FIRST_READ as usize).min(limit);
buffer.reserve_exact(grown - filled);
buffer.resize(grown, 0);
}
match body.read(&mut buffer[filled..]).await? {
0 => return Ok(filled),
n => filled += n,
}
}
}
fn upload_query(upload_id: &str) -> String {
format!("uploadId={}", encode_query(upload_id))
}
fn complete_body(etags: &[String]) -> Vec<u8> {
let mut body = format!("<CompleteMultipartUpload xmlns=\"{S3_NAMESPACE}\">");
for (number, etag) in (1u32..).zip(etags) {
body.push_str(&format!(
"<Part><PartNumber>{number}</PartNumber><ETag>{}</ETag></Part>",
partial_escape(etag.as_str())
));
}
body.push_str("</CompleteMultipartUpload>");
body.into_bytes()
}
async fn upload_body(bytes: Vec<u8>) -> UploadBody {
if bytes.len() <= UNBLOCK_SIZE {
return UploadBody::bytes(bytes);
}
ostrya_rt::unblock(move || {
let sha256 = Sha256::digest(&bytes).into();
UploadBody::bytes_with_sha256(bytes, sha256)
})
.await
}
fn copy(body: &UploadBody) -> UploadBody {
body.try_clone()
.expect("a body of bytes has a copy that shares its bytes")
}
fn check_put_size(key: &str, body: &[u8]) -> Result<()> {
if body.len() as u64 > MAX_PUT {
return Err(Error::InvalidInput(format!(
"S3: the body of {key} has {} bytes, more than the {MAX_PUT}-byte limit of one PUT",
body.len()
)));
}
Ok(())
}
async fn read_reply(uploaded: Uploaded) -> Reply {
let header = |name: &str| {
uploaded
.headers()
.get(name)
.and_then(|value| value.to_str().ok())
.map(str::to_owned)
};
let status = uploaded.status();
let etag = header("etag");
let region = header("x-amz-bucket-region");
let withheld = uploaded.body_withheld();
let mut body = uploaded.into_body();
let declared = body.content_length();
let body = if withheld {
None
} else {
read_whole(&mut body, declared, XML_CAP, MAX_RESERVE)
.await
.ok()
};
Reply {
status,
etag,
region,
body,
}
}
fn reply_code(reply: &Reply) -> Option<String> {
reply.body.as_deref().and_then(xml::error)?.code
}
fn is_no_such_upload(reply: &Reply) -> bool {
reply.status == 404 && reply_code(reply).is_some_and(|code| code.trim() == "NoSuchUpload")
}
fn is_success(status: u16) -> bool {
(200..300).contains(&status)
}
fn is_retryable(status: u16) -> bool {
status == 408 || status == 429 || (500..600).contains(&status)
}
fn is_absent(status: u16, body: Option<&[u8]>) -> bool {
status == 404
&& body.is_some_and(|body| {
xml::error(body)
.and_then(|doc| doc.code)
.is_none_or(|code| code.trim() == "NoSuchKey")
})
}
fn is_no_such_key(status: u16, body: Option<&[u8]>) -> bool {
status == 404
&& body
.and_then(xml::error)
.and_then(|doc| doc.code)
.is_some_and(|code| code.trim() == "NoSuchKey")
}
async fn read_whole(
body: &mut (impl AsyncRead + Unpin),
declared: Option<u64>,
limit: u64,
reserve: u64,
) -> std::io::Result<Vec<u8>> {
let most = declared.map_or(limit, |declared| declared.min(limit));
let ceiling = usize::try_from(most.saturating_add(1)).unwrap_or(usize::MAX);
let first = usize::try_from(declared.unwrap_or(FIRST_READ).min(most).min(reserve))
.unwrap_or(0)
.saturating_add(1);
let mut bytes = vec![0u8; first];
let mut filled = 0;
loop {
if filled == bytes.len() {
if bytes.len() >= ceiling {
return Err(std::io::Error::new(
ErrorKind::FileTooLarge,
format!("the body is larger than {limit} bytes"),
));
}
let grown = bytes.len().saturating_mul(2).min(ceiling);
bytes.reserve_exact(grown - bytes.len());
bytes.resize(grown, 0);
}
let n = body.read(&mut bytes[filled..]).await?;
if n == 0 {
bytes.truncate(filled);
return Ok(bytes);
}
filled += n;
}
}
async fn hash_exact(
body: &mut (impl AsyncRead + Unpin),
size: u64,
) -> std::io::Result<Option<[u8; 32]>> {
let chunk =
usize::try_from(size.saturating_add(1)).map_or(COMPARE_CHUNK, |len| len.min(COMPARE_CHUNK));
let mut buf = vec![0u8; chunk];
let mut hasher = Sha256::new();
let mut read = 0u64;
loop {
let n = body.read(&mut buf).await?;
if n == 0 {
return Ok((read == size).then(|| hasher.finalize().into()));
}
read += n as u64;
if read > size {
return Ok(None);
}
hasher.update(&buf[..n]);
}
}
fn backoff(round: u32) -> Duration {
Duration::from_millis(250u64 << round.saturating_sub(1).min(3))
}
fn too_large(key: &str, max_size: u64) -> Error {
Error::LimitExceeded(format!(
"S3: the object {key} is larger than the limit of {max_size} bytes"
))
}
fn not_modified(key: &str) -> Error {
Error::Transport(format!(
"S3: the server answered the read of {key}, which sent no validators, with 304"
))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_backoff_doubles_and_stops_at_two_seconds() {
let delays: Vec<u64> = (1..=6)
.map(|round| backoff(round).as_millis() as u64)
.collect();
assert_eq!(delays, [250, 500, 1000, 2000, 2000, 2000]);
}
#[test]
fn the_retryable_statuses_are_408_429_and_5xx() {
for status in [408, 429, 500, 503, 599] {
assert!(is_retryable(status), "{status}");
}
for status in [200, 301, 400, 403, 404, 409, 412] {
assert!(!is_retryable(status), "{status}");
}
}
#[test]
fn an_absent_key_is_a_404_whose_body_has_no_code_or_no_such_key() {
let coded = |code: &str| format!("<Error><Code>{code}</Code></Error>").into_bytes();
assert!(is_absent(404, Some(b"")));
assert!(is_absent(404, Some(b"not found")));
assert!(is_absent(404, Some(b"<Error><Message>m</Message></Error>")));
assert!(is_absent(404, Some(&coded("NoSuchKey"))));
assert!(!is_absent(404, Some(&coded("NoSuchBucket"))));
assert!(!is_absent(404, None));
assert!(!is_absent(403, Some(b"")));
}
#[test]
fn a_strict_absent_key_is_a_404_whose_body_has_no_such_key() {
let coded = |code: &str| format!("<Error><Code>{code}</Code></Error>").into_bytes();
assert!(is_no_such_key(404, Some(&coded("NoSuchKey"))));
assert!(is_no_such_key(404, Some(&coded(" NoSuchKey\n"))));
assert!(!is_no_such_key(404, Some(b"")));
assert!(!is_no_such_key(404, Some(b"<html>Not Found</html>")));
assert!(!is_no_such_key(
404,
Some(b"<Error><Message>m</Message></Error>")
));
assert!(!is_no_such_key(404, Some(&coded("NoSuchBucket"))));
assert!(!is_no_such_key(404, None));
assert!(!is_no_such_key(403, Some(&coded("NoSuchKey"))));
}
#[test]
fn a_whole_read_holds_no_capacity_past_its_limit() {
ostrya_rt::block_on(async {
let data = vec![b'x'; XML_CAP as usize];
let mut reader = futures_lite::io::Cursor::new(data.clone());
let bytes = read_whole(&mut reader, None, XML_CAP, MAX_RESERVE)
.await
.unwrap();
assert_eq!(bytes.len(), data.len());
assert!(bytes.capacity() <= data.len() + 1, "{}", bytes.capacity());
let mut reader = futures_lite::io::Cursor::new(data[..3000].to_vec());
let bytes = read_whole(&mut reader, Some(3000), XML_CAP, MAX_RESERVE)
.await
.unwrap();
assert_eq!(bytes.len(), 3000);
assert!(bytes.capacity() <= 3001, "{}", bytes.capacity());
let mut reader = futures_lite::io::Cursor::new(vec![b'x'; 11]);
let err = read_whole(&mut reader, None, 10, MAX_RESERVE)
.await
.unwrap_err();
assert_eq!(err.kind(), ErrorKind::FileTooLarge);
});
}
#[test]
fn a_whole_read_reserves_a_declared_length_at_once() {
ostrya_rt::block_on(async {
let size = 2 * XML_CAP as usize + 5;
let limit = 4 * XML_CAP;
struct First {
data: futures_lite::io::Cursor<Vec<u8>>,
first: Option<usize>,
}
impl AsyncRead for First {
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<std::io::Result<usize>> {
self.first.get_or_insert(buf.len());
Pin::new(&mut self.data).poll_read(cx, buf)
}
}
let mut reader = First {
data: futures_lite::io::Cursor::new(vec![b'x'; size]),
first: None,
};
let bytes = read_whole(&mut reader, Some(size as u64), limit, limit)
.await
.unwrap();
assert_eq!(bytes.len(), size);
assert_eq!(reader.first, Some(size + 1));
assert!(bytes.capacity() <= size + 1, "{}", bytes.capacity());
let mut reader = First {
data: futures_lite::io::Cursor::new(vec![b'x'; size]),
first: None,
};
read_whole(&mut reader, Some(size as u64), limit, MAX_RESERVE)
.await
.unwrap();
assert_eq!(reader.first, Some(XML_CAP as usize + 1));
let mut reader = First {
data: futures_lite::io::Cursor::new(vec![b'x'; size]),
first: None,
};
read_whole(&mut reader, None, limit, limit).await.unwrap();
assert_eq!(reader.first, Some(FIRST_READ as usize + 1));
});
}
#[test]
fn the_part_size_grows_by_whole_mib_past_8_mib() {
assert_eq!(part_size(0).unwrap(), 8 * MIB);
assert_eq!(part_size(41_942_515_712).unwrap(), 8 * MIB);
assert_eq!(part_size(41_942_515_713).unwrap(), 9 * MIB);
assert_eq!(part_size(26_843_545_075_712).unwrap(), MAX_PUT);
for size in [26_843_545_075_713, u64::MAX / 2, u64::MAX] {
let err = part_size(size).unwrap_err();
assert!(matches!(err, Error::LimitExceeded(_)), "{size}: {err}");
}
}
#[test]
fn the_complete_document_lists_each_part_with_its_escaped_etag() {
let etags = [
"\"5d41402abc4b2a76b9719d911017c592\"".to_owned(),
"\"a&b<c>\"".to_owned(),
];
assert_eq!(
String::from_utf8(complete_body(&etags)).unwrap(),
"<CompleteMultipartUpload xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">\
<Part><PartNumber>1</PartNumber>\
<ETag>\"5d41402abc4b2a76b9719d911017c592\"</ETag></Part>\
<Part><PartNumber>2</PartNumber><ETag>\"a&b<c>\"</ETag></Part>\
</CompleteMultipartUpload>"
);
}
fn read_parts(
data: &[u8],
part_size: usize,
max_parts: u32,
) -> std::result::Result<Vec<Part>, Stop> {
ostrya_rt::block_on(async {
let mut parts = Parts::new(futures_lite::io::Cursor::new(data), part_size, max_parts);
let mut read = Vec::new();
loop {
let part = parts.next().await?;
let last = part.last;
read.push(part);
if last {
return Ok(read);
}
}
})
}
#[test]
fn a_body_reads_as_numbered_parts_with_a_probe_byte_between_them() {
let data: Vec<u8> = (0..10u8).collect();
let Ok(parts) = read_parts(&data, 4, 3) else {
panic!("three parts of four bytes hold ten bytes");
};
let found: Vec<(u32, &[u8], bool)> = parts
.iter()
.map(|part| (part.number, part.bytes.as_slice(), part.last))
.collect();
assert_eq!(
found,
[
(1, &data[..4], false),
(2, &data[4..8], false),
(3, &data[8..], true)
]
);
let parts = read_parts(&data[..8], 4, 3).ok().unwrap();
assert_eq!(parts.len(), 2);
assert!(parts[1].last && parts[1].bytes == data[4..8]);
let parts = read_parts(&[], 4, 3).ok().unwrap();
assert_eq!(parts.len(), 1);
assert!(parts[0].last && parts[0].bytes.is_empty());
}
#[test]
fn a_body_past_the_last_part_stops_at_the_probe_byte() {
assert!(read_parts(&[7u8; 12], 4, 3).is_ok());
match read_parts(&[7u8; 13], 4, 3) {
Err(Stop::TooMany {
max_parts: 3,
part_size: 4,
}) => {}
Err(Stop::TooMany { .. }) => panic!("another limit"),
Err(Stop::Io(e)) => panic!("{e}"),
Ok(parts) => panic!("{} parts", parts.len()),
}
let err = Stop::TooMany {
max_parts: 3,
part_size: 4,
}
.error("repo/config");
assert!(matches!(err, Error::LimitExceeded(_)), "{err}");
let text = err.to_string();
assert!(
text.contains("repo/config") && text.contains("3 parts of 4 bytes"),
"{text}"
);
}
#[test]
fn a_part_holds_no_capacity_past_the_part_size() {
let small = read_parts(&[1u8; 100], 1 << 20, 3).ok().unwrap();
assert_eq!(small[0].bytes.len(), 100);
assert_eq!(small[0].bytes.capacity(), FIRST_READ as usize);
let size = 3 * FIRST_READ as usize + 5;
let data = vec![2u8; 2 * size + 1];
let parts = read_parts(&data, size, 3).ok().unwrap();
assert_eq!(parts.len(), 3);
for part in &parts[..2] {
assert_eq!(part.bytes.len(), size);
assert_eq!(part.bytes.capacity(), size);
}
assert_eq!(parts[2].bytes, [2u8]);
assert_eq!(parts[2].bytes.capacity(), size);
}
#[test]
fn a_later_part_reads_into_the_buffer_that_came_back() {
struct Counting {
data: futures_lite::io::Cursor<Vec<u8>>,
zeros: usize,
}
impl AsyncRead for Counting {
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<std::io::Result<usize>> {
if buf.len() > 1 {
self.zeros += buf.iter().filter(|byte| **byte == 0).count();
}
Pin::new(&mut self.data).poll_read(cx, buf)
}
}
let size = 3 * FIRST_READ as usize + 5;
let data: Vec<u8> = (0..3 * size + 1).map(|at| (at % 255) as u8 + 1).collect();
ostrya_rt::block_on(async {
let mut parts = Parts::new(
Counting {
data: futures_lite::io::Cursor::new(data.clone()),
zeros: 0,
},
size,
4,
);
let first = parts.next().await.ok().unwrap();
let zeros = parts.body.zeros;
assert!(zeros > 0);
let address = first.bytes.as_ptr();
parts.recycle(UploadBody::bytes(first.bytes));
let second = parts.next().await.ok().unwrap();
assert_eq!(second.bytes, data[size..2 * size]);
assert_eq!(second.bytes.as_ptr(), address);
assert_eq!(second.bytes.capacity(), size);
assert_eq!(parts.body.zeros, zeros);
let body = UploadBody::bytes(second.bytes);
let shared = body.try_clone().unwrap();
parts.recycle(body);
let third = parts.next().await.ok().unwrap();
assert_eq!(third.bytes, data[2 * size..3 * size]);
assert_ne!(third.bytes.as_ptr(), address);
assert_eq!(third.bytes.capacity(), size);
assert_eq!(shared.as_bytes(), Some(&data[size..2 * size]));
let zeros = parts.body.zeros;
let address = third.bytes.as_ptr();
parts.recycle(UploadBody::bytes(third.bytes));
let last = parts.next().await.ok().unwrap();
assert!(last.last);
assert_eq!(last.bytes, data[3 * size..]);
assert_eq!(last.bytes.as_ptr(), address);
assert_eq!(last.bytes.capacity(), size);
assert_eq!(parts.body.zeros, zeros);
});
}
#[test]
fn a_body_over_the_limit_comes_back_from_the_pool_with_its_digest() {
ostrya_rt::block_on(async {
let small = upload_body(vec![1; UNBLOCK_SIZE]).await;
assert_eq!(small.sha256(), None);
assert_eq!(small.as_bytes().map(<[u8]>::len), Some(UNBLOCK_SIZE));
let mut bytes = Vec::with_capacity(UNBLOCK_SIZE + 8);
bytes.resize(UNBLOCK_SIZE + 1, 2);
let digest: [u8; 32] = Sha256::digest(&bytes).into();
let (address, capacity) = (bytes.as_ptr(), bytes.capacity());
let body = upload_body(bytes).await;
assert_eq!(body.sha256(), Some(digest));
assert_eq!(body.as_bytes().map(<[u8]>::as_ptr), Some(address));
let mut parts = Parts::new(&[][..], UNBLOCK_SIZE + 1, 2);
parts.recycle(body);
let spare = parts.spare.take().expect("the buffer comes back");
assert_eq!(spare.as_ptr(), address);
assert_eq!(spare.capacity(), capacity);
});
}
#[test]
fn a_failed_read_of_the_body_stops_the_parts() {
struct Failing {
given: bool,
}
impl AsyncRead for Failing {
fn poll_read(
mut self: Pin<&mut Self>,
_: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<std::io::Result<usize>> {
if self.given {
return Poll::Ready(Err(std::io::Error::other("the source failed")));
}
self.given = true;
let n = buf.len().min(4);
buf[..n].fill(9);
Poll::Ready(Ok(n))
}
}
ostrya_rt::block_on(async {
let mut parts = Parts::new(Failing { given: false }, 4, 3);
let Err(Stop::Io(e)) = parts.next().await else {
panic!("a failed read stops the parts");
};
assert_eq!(e.to_string(), "the source failed");
assert!(matches!(Stop::Io(e).error("k"), Error::Io(_)));
});
}
#[test]
fn a_stream_hashes_only_at_its_exact_length() {
ostrya_rt::block_on(async {
let data = vec![b'h'; 3 * COMPARE_CHUNK + 7];
let size = data.len() as u64;
let digest: [u8; 32] = Sha256::digest(&data).into();
let mut reader = futures_lite::io::Cursor::new(data.clone());
assert_eq!(hash_exact(&mut reader, size).await.unwrap(), Some(digest));
let mut reader = futures_lite::io::Cursor::new(data.clone());
assert_eq!(hash_exact(&mut reader, size - 1).await.unwrap(), None);
let mut reader = futures_lite::io::Cursor::new(data);
assert_eq!(hash_exact(&mut reader, size + 1).await.unwrap(), None);
});
}
}