pub mod sigv4;
#[cfg(test)]
pub mod fake;
use std::collections::BTreeMap;
use std::fs::File;
use std::io::{Read as _, Seek as _, SeekFrom};
use std::path::Path;
use std::time::Duration;
use anyhow::{Context, Result, bail};
use md5::{Digest as _, Md5};
use rayon::prelude::*;
use sigv4::{Credentials, SignableRequest, amz_date, empty_payload_sha256, sha256, sign};
pub const MULTIPART_THRESHOLD: u64 = 32 * 1024 * 1024;
pub const PART_SIZE: usize = 8 * 1024 * 1024;
const PART_CONCURRENCY: usize = 4;
const ATTEMPTS: u32 = 3;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ObjectFacts {
pub bytes: u64,
pub md5: Option<[u8; 16]>,
pub sha256: Option<[u8; 32]>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum PutOutcome {
Copied {
bytes: u64,
},
Skipped,
Refused(String),
}
#[derive(Debug)]
struct Response {
status: u16,
headers: Vec<(String, String)>,
body: Vec<u8>,
}
enum Body {
Empty,
Bytes(Vec<u8>),
File(std::path::PathBuf),
}
#[derive(Debug)]
pub struct S3 {
agent: ureq::Agent,
endpoint: String,
host: String,
region: String,
bucket: String,
credentials: Credentials,
}
impl S3 {
pub fn new(
endpoint: &str,
region: &str,
bucket: &str,
credentials: Credentials,
) -> Result<Self> {
let rest = endpoint
.split_once("://")
.map_or(endpoint, |(_, rest)| rest);
let host = rest.split('/').next().unwrap_or_default();
if host.is_empty() {
bail!("endpoint {endpoint} is not a URL");
}
let agent: ureq::Agent = ureq::Agent::config_builder()
.timeout_global(Some(Duration::from_secs(60)))
.http_status_as_error(false)
.build()
.into();
Ok(Self {
agent,
endpoint: endpoint.trim_end_matches('/').to_owned(),
host: host.to_owned(),
region: region.to_owned(),
bucket: bucket.to_owned(),
credentials,
})
}
#[must_use]
pub fn bucket(&self) -> &str {
&self.bucket
}
#[must_use]
pub fn host(&self) -> &str {
&self.host
}
fn url(&self, key: &str) -> String {
if key.is_empty() {
format!("{}/{}", self.endpoint, self.bucket)
} else {
format!("{}/{}/{}", self.endpoint, self.bucket, key)
}
}
fn path(&self, key: &str) -> String {
if key.is_empty() {
format!("/{}", self.bucket)
} else {
format!("/{}/{}", self.bucket, key)
}
}
fn request(
&self,
method: &str,
key: &str,
query: Vec<(String, String)>,
headers: Vec<(String, String)>,
payload: &[u8; 32],
body: &Body,
) -> Result<Response> {
let mut attempt = 0;
let mut delay = Duration::from_millis(500);
loop {
attempt += 1;
match self.request_once(method, key, &query, &headers, payload, body) {
Ok(response) if (500..600).contains(&response.status) || response.status == 429 => {
if attempt >= ATTEMPTS {
bail!(
"{method} {key} failed with {} after {attempt} attempts",
response.status
);
}
}
Ok(response) => return Ok(response),
Err(error) if attempt < ATTEMPTS => {
tracing::warn!(%error, method, key, "retrying the request");
}
Err(error) => return Err(error),
}
std::thread::sleep(delay);
delay = delay.saturating_mul(2).min(Duration::from_secs(8));
}
}
fn request_once(
&self,
method: &str,
key: &str,
query: &[(String, String)],
headers: &[(String, String)],
payload: &[u8; 32],
body: &Body,
) -> Result<Response> {
let request = SignableRequest {
method,
host: &self.host,
path: &self.path(key),
query: query.to_vec(),
headers: headers.to_vec(),
payload_sha256: *payload,
};
let signed = sign(&request, &self.credentials, &self.region, &amz_date(now()))?;
let mut builder_url = self.url(key);
if !query.is_empty() {
builder_url.push('?');
builder_url.push_str(&sigv4::canonical_query(query));
}
let url = builder_url;
macro_rules! signed_headers {
($builder:expr) => {{
let mut builder = $builder;
for (name, value) in signed.iter().chain(headers.iter()) {
builder = builder.header(name.as_str(), value.as_str());
}
builder
}};
}
let mut response = match (method, body) {
("GET", _) => signed_headers!(self.agent.get(&url)).call(),
("HEAD", _) => signed_headers!(self.agent.head(&url)).call(),
("DELETE", _) => signed_headers!(self.agent.delete(&url)).call(),
("PUT", Body::Empty) => signed_headers!(self.agent.put(&url)).send(()),
("POST", Body::Empty) => signed_headers!(self.agent.post(&url)).send(()),
("PUT", Body::Bytes(bytes)) => {
signed_headers!(self.agent.put(&url)).send(bytes.as_slice())
}
("POST", Body::Bytes(bytes)) => {
signed_headers!(self.agent.post(&url)).send(bytes.as_slice())
}
("PUT", Body::File(path)) => {
let file =
File::open(path).with_context(|| format!("opening {}", path.display()))?;
signed_headers!(self.agent.put(&url)).send(file)
}
(other, _) => bail!("method {other} with this body is not supported"),
}
.with_context(|| format!("{method} {url}"))?;
let status = response.status().as_u16();
let headers: Vec<(String, String)> = response
.headers()
.iter()
.map(|(name, value)| {
(
name.as_str().to_ascii_lowercase(),
value.to_str().unwrap_or_default().to_owned(),
)
})
.collect();
let body = if method == "HEAD" {
Vec::new()
} else {
response
.body_mut()
.with_config()
.limit(16 * 1024 * 1024)
.read_to_vec()
.with_context(|| format!("reading the body of {method} {url}"))?
};
Ok(Response {
status,
headers,
body,
})
}
pub fn head(&self, key: &str) -> Result<Option<ObjectFacts>> {
let response = self.request(
"HEAD",
key,
Vec::new(),
Vec::new(),
&empty_payload_sha256(),
&Body::Empty,
)?;
match response.status {
200 => match header(&response.headers, "content-length")
.and_then(|text| text.parse::<u64>().ok())
{
Some(bytes) => Ok(Some(ObjectFacts {
bytes,
md5: header(&response.headers, "etag").and_then(etag_md5),
sha256: header(&response.headers, "x-amz-meta-sha256").and_then(hex32::<32>),
})),
None => self.facts_from_range(key),
},
404 | 403 => Ok(None),
other => bail!("HEAD {key} failed with {other}"),
}
}
fn facts_from_range(&self, key: &str) -> Result<Option<ObjectFacts>> {
let response = self.request(
"GET",
key,
Vec::new(),
vec![("range".to_owned(), "bytes=0-0".to_owned())],
&empty_payload_sha256(),
&Body::Empty,
)?;
if response.status == 404 || response.status == 403 {
return Ok(None);
}
if response.status != 206 && response.status != 200 {
bail!("GET {key} range 0-0 failed with {}", response.status);
}
let total = header(&response.headers, "content-range")
.and_then(|value| value.rsplit('/').next())
.and_then(|value| value.parse::<u64>().ok())
.with_context(|| format!("{key}: no content-range"))?;
Ok(Some(ObjectFacts {
bytes: total,
md5: header(&response.headers, "etag").and_then(etag_md5),
sha256: None,
}))
}
pub fn get_range(&self, key: &str, start: u64, end: u64) -> Result<Vec<u8>> {
if end < start {
bail!("range {start}-{end} of {key} is empty");
}
let response = self.request(
"GET",
key,
Vec::new(),
vec![("range".to_owned(), format!("bytes={start}-{end}"))],
&empty_payload_sha256(),
&Body::Empty,
)?;
if response.status != 206 && response.status != 200 {
bail!(
"GET {key} range {start}-{end} failed with {}",
response.status
);
}
Ok(response.body)
}
pub fn get(&self, key: &str) -> Result<Vec<u8>> {
let response = self.request(
"GET",
key,
Vec::new(),
Vec::new(),
&empty_payload_sha256(),
&Body::Empty,
)?;
if response.status != 200 {
bail!("GET {key} failed with {}", response.status);
}
Ok(response.body)
}
pub fn put_new(&self, key: &str, file: &Path) -> Result<PutOutcome> {
let local_bytes = std::fs::metadata(file)
.with_context(|| format!("reading {}", file.display()))?
.len();
let local_md5 = md5_file(file)?;
if let Some(facts) = self.head(key)? {
let same_bytes = facts.bytes == local_bytes;
let same_md5 = facts.md5 == Some(local_md5);
return Ok(if same_bytes && same_md5 {
PutOutcome::Skipped
} else if same_bytes {
PutOutcome::Refused(format!(
"{key} is in {} with other bytes of the same size: never overwritten",
self.bucket
))
} else {
PutOutcome::Refused(format!(
"{key} is in {} with {} bytes, the stage has {local_bytes}: never overwritten",
self.bucket, facts.bytes
))
});
}
if local_bytes >= MULTIPART_THRESHOLD {
self.put_multipart(key, file, local_bytes)?;
} else {
let digest = sha256_file(file)?;
let response = self.request(
"PUT",
key,
Vec::new(),
vec![("x-amz-meta-sha256".to_owned(), crate::layout::hex(&digest))],
&digest,
&Body::File(file.to_path_buf()),
)?;
if response.status != 200 {
bail!("PUT {key} failed with {}", response.status);
}
}
match self.head(key)? {
Some(facts) if facts.bytes == local_bytes => {
Ok(PutOutcome::Copied { bytes: local_bytes })
}
other => bail!(
"{key} has {} bytes in {} after copy, the stage has {local_bytes}",
other.map_or_else(|| "no".to_owned(), |facts| facts.bytes.to_string()),
self.bucket
),
}
}
pub fn put_overwrite(&self, key: &str, bytes: &[u8]) -> Result<()> {
let digest = sha256(bytes);
let response = self.request(
"PUT",
key,
Vec::new(),
Vec::new(),
&digest,
&Body::Bytes(bytes.to_vec()),
)?;
if response.status != 200 {
bail!("PUT {key} failed with {}", response.status);
}
match self.head(key)? {
Some(facts) if facts.bytes == bytes.len() as u64 => Ok(()),
other => bail!(
"{key} has {} bytes in {} after copy, the stage has {}",
other.map_or_else(|| "no".to_owned(), |facts| facts.bytes.to_string()),
self.bucket,
bytes.len()
),
}
}
pub fn list(&self, prefix: &str) -> Result<Vec<(String, u64)>> {
let response = self.request(
"GET",
"",
vec![
("list-type".to_owned(), "2".to_owned()),
("prefix".to_owned(), prefix.to_owned()),
],
Vec::new(),
&empty_payload_sha256(),
&Body::Empty,
)?;
if response.status != 200 {
bail!("listing {prefix} failed with {}", response.status);
}
let text = String::from_utf8_lossy(&response.body);
let mut out = Vec::new();
for contents in text.split("<Contents>").skip(1) {
let Some(key) = between(contents, "<Key>", "</Key>") else {
continue;
};
let bytes = between(contents, "<Size>", "</Size>")
.and_then(|size| size.parse::<u64>().ok())
.unwrap_or_default();
out.push((key.to_owned(), bytes));
}
Ok(out)
}
fn put_multipart(&self, key: &str, file: &Path, bytes: u64) -> Result<()> {
let response = self.request(
"POST",
key,
vec![("uploads".to_owned(), String::new())],
Vec::new(),
&empty_payload_sha256(),
&Body::Empty,
)?;
if response.status != 200 {
bail!(
"creating the multipart upload of {key} failed with {}",
response.status
);
}
let upload_id = between(
&String::from_utf8_lossy(&response.body),
"<UploadId>",
"</UploadId>",
)
.with_context(|| format!("{key}: the upload id is missing"))?
.to_owned();
let count = usize::try_from(bytes.div_ceil(PART_SIZE as u64)).unwrap_or(1);
let parts = self.upload_parts(key, file, &upload_id, count);
let parts = match parts {
Ok(parts) => parts,
Err(error) => {
let _ = self.abort(key, &upload_id);
return Err(error);
}
};
let mut xml = String::from("<CompleteMultipartUpload>");
for (number, etag) in &parts {
xml.push_str(&format!(
"<Part><PartNumber>{number}</PartNumber><ETag>{etag}</ETag></Part>"
));
}
xml.push_str("</CompleteMultipartUpload>");
let response = self.request(
"POST",
key,
vec![("uploadId".to_owned(), upload_id.clone())],
vec![("content-type".to_owned(), "application/xml".to_owned())],
&sha256(xml.as_bytes()),
&Body::Bytes(xml.into_bytes()),
)?;
if response.status != 200 {
let _ = self.abort(key, &upload_id);
bail!(
"completing the multipart upload of {key} failed with {}",
response.status
);
}
Ok(())
}
fn upload_parts(
&self,
key: &str,
file: &Path,
upload_id: &str,
count: usize,
) -> Result<Vec<(u32, String)>> {
let pool = rayon::ThreadPoolBuilder::new()
.num_threads(PART_CONCURRENCY)
.build()
.context("building the part pool")?;
let mut parts = pool.install(|| {
(0..count)
.into_par_iter()
.map(|index| -> Result<(u32, String)> {
let mut handle =
File::open(file).with_context(|| format!("opening {}", file.display()))?;
handle
.seek(SeekFrom::Start((index * PART_SIZE) as u64))
.with_context(|| format!("seeking in {}", file.display()))?;
let mut buffer = vec![0_u8; PART_SIZE];
let mut filled = 0;
while filled < PART_SIZE {
let read = handle
.read(&mut buffer[filled..])
.with_context(|| format!("reading {}", file.display()))?;
if read == 0 {
break;
}
filled += read;
}
buffer.truncate(filled);
let number = u32::try_from(index + 1).context("part number")?;
let digest = sha256(&buffer);
let response = self.request(
"PUT",
key,
vec![
("partNumber".to_owned(), number.to_string()),
("uploadId".to_owned(), upload_id.to_owned()),
],
Vec::new(),
&digest,
&Body::Bytes(buffer),
)?;
if response.status != 200 {
bail!("part {number} of {key} failed with {}", response.status);
}
let etag = header(&response.headers, "etag")
.with_context(|| format!("part {number} of {key} has no ETag"))?
.to_owned();
Ok((number, etag))
})
.collect::<Result<Vec<_>>>()
})?;
parts.sort_unstable_by_key(|(number, _)| *number);
Ok(parts)
}
fn abort(&self, key: &str, upload_id: &str) -> Result<()> {
let response = self.request(
"DELETE",
key,
vec![("uploadId".to_owned(), upload_id.to_owned())],
Vec::new(),
&empty_payload_sha256(),
&Body::Empty,
)?;
if response.status != 204 && response.status != 200 {
bail!(
"aborting the upload of {key} failed with {}",
response.status
);
}
Ok(())
}
}
fn header<'a>(headers: &'a [(String, String)], name: &str) -> Option<&'a str> {
headers
.iter()
.find(|(key, _)| key == name)
.map(|(_, value)| value.as_str())
}
fn etag_md5(value: &str) -> Option<[u8; 16]> {
let text = value.trim_matches('"');
if text.len() != 32 || !text.bytes().all(|byte| byte.is_ascii_hexdigit()) {
return None;
}
hex32::<16>(text)
}
fn hex32<const N: usize>(text: &str) -> Option<[u8; N]> {
if text.len() != N * 2 {
return None;
}
let mut out = [0_u8; N];
for (index, chunk) in text.as_bytes().as_chunks::<2>().0.iter().enumerate() {
let text = std::str::from_utf8(chunk).ok()?;
out[index] = u8::from_str_radix(text, 16).ok()?;
}
Some(out)
}
fn md5_file(path: &Path) -> Result<[u8; 16]> {
let mut file = File::open(path).with_context(|| format!("opening {}", path.display()))?;
let mut hasher = Md5::new();
let mut buffer = vec![0_u8; 1 << 16];
loop {
let read = file
.read(&mut buffer)
.with_context(|| format!("reading {}", path.display()))?;
if read == 0 {
break;
}
hasher.update(&buffer[..read]);
}
Ok(hasher.finalize().into())
}
fn sha256_file(path: &Path) -> Result<[u8; 32]> {
crate::layout::sha256_file(path)
}
fn between<'a>(text: &'a str, open: &str, close: &str) -> Option<&'a str> {
let start = text.find(open)? + open.len();
let rest = &text[start..];
let end = rest.find(close)?;
Some(&rest[..end])
}
fn now() -> i64 {
crate::layout::unix_seconds()
}
pub(crate) fn md5_of(path: &Path) -> Result<[u8; 16]> {
md5_file(path)
}
pub fn listing_map(client: &S3, prefix: &str) -> Result<BTreeMap<String, u64>> {
Ok(client.list(prefix)?.into_iter().collect())
}
#[cfg(test)]
mod tests {
use super::fake::FakeS3;
use super::*;
fn write_temp(bytes: &[u8]) -> (tempfile::TempDir, std::path::PathBuf) {
let dir = tempfile::tempdir().expect("a temp dir");
let path = dir.path().join("payload");
std::fs::write(&path, bytes).expect("write");
(dir, path)
}
#[test]
fn put_new_skips_an_object_with_equal_bytes_and_refuses_a_different_one() {
let fake = FakeS3::start();
let client = fake.client();
let (_dir, file) = write_temp(b"payload");
assert!(matches!(
client.put_new("datasets/x", &file).expect("put"),
PutOutcome::Copied { bytes: 7 }
));
assert!(matches!(
client.put_new("datasets/x", &file).expect("put"),
PutOutcome::Skipped
));
let (_other, different) = write_temp(b"different");
let refusal = client.put_new("datasets/x", &different).expect("put");
assert!(matches!(refusal, PutOutcome::Refused(_)), "{refusal:?}");
assert_eq!(
fake.objects().get("datasets/x").map(Vec::as_slice),
Some(&b"payload"[..])
);
}
#[test]
fn a_refused_write_sends_no_put() {
let fake = FakeS3::start();
let client = fake.client();
let (_dir, file) = write_temp(b"first");
client.put_new("datasets/y", &file).expect("put");
let before = fake.writes();
let (_other, different) = write_temp(b"second");
let _ = client.put_new("datasets/y", &different).expect("put");
assert_eq!(fake.writes(), before);
}
#[test]
fn a_multipart_upload_round_trips_and_an_abort_leaves_no_object() {
let fake = FakeS3::start();
let big = vec![7_u8; 40 * 1024 * 1024];
let (dir, file) = write_temp(&big);
assert!(matches!(
fake.client().put_new("big", &file).expect("put"),
PutOutcome::Copied { .. }
));
assert!(fake.multipart_parts_seen() > 1);
assert_eq!(
fake.client()
.head("big")
.expect("head")
.expect("object")
.bytes,
40 * 1024 * 1024
);
let stored = fake.objects();
assert_eq!(stored.get("big").map(Vec::len), Some(big.len()));
assert_eq!(stored.get("big"), Some(&big));
drop(dir);
}
#[test]
fn a_range_read_returns_the_slice() {
let fake = FakeS3::start();
let client = fake.client();
let (_dir, file) = write_temp(b"0123456789");
client.put_new("range", &file).expect("put");
assert_eq!(
client.get_range("range", 2, 5).expect("range"),
b"2345".to_vec()
);
assert_eq!(client.get("range").expect("get"), b"0123456789".to_vec());
}
#[test]
fn an_overwrite_replaces_the_pointer_and_a_listing_names_it() {
let fake = FakeS3::start();
let client = fake.client();
client
.put_overwrite("datasets/a/current.json", b"one")
.expect("put");
client
.put_overwrite("datasets/a/current.json", b"two")
.expect("put");
assert_eq!(
client.get("datasets/a/current.json").expect("get"),
b"two".to_vec()
);
client
.put_overwrite("datasets/a/b/c.json", b"x")
.expect("put");
let mut listed = client.list("datasets/a/").expect("list");
listed.sort();
assert_eq!(
listed,
vec![
("datasets/a/b/c.json".to_owned(), 1_u64),
("datasets/a/current.json".to_owned(), 3),
]
);
}
}