use std::io::SeekFrom;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use bytes::{Bytes, BytesMut};
use futures_util::stream;
use reqwest::Method;
use serde_json::json;
use sha2::{Digest, Sha256};
use tokio::io::{AsyncRead, AsyncReadExt, AsyncSeekExt};
use crate::client::{json_body, BodyFuture, Request, RequestBody, RequestOptions, Wellfriend};
use crate::error::{Error, Result};
use crate::file_input::{FileInput, Source};
use crate::generated::models::{Upload, UploadPart, UploadStatus};
use crate::models::{Document, UploadCompletion, VersionRef};
pub const SINGLE_REQUEST_MAX_BYTES: u64 = 100 * 1024 * 1024;
pub const CHECKSUM_REQUIRED_ABOVE_BYTES: u64 = 50 * 1024 * 1024;
const READ_CHUNK: usize = 64 * 1024;
pub(crate) struct Uploaded {
pub(crate) reference: VersionRef,
pub(crate) document: Option<Document>,
}
pub(crate) async fn ensure_stored(
client: &Wellfriend,
options: &RequestOptions,
input: FileInput,
key: Option<String>,
) -> Result<Uploaded> {
if let Source::Document(reference) = input.source {
return Ok(Uploaded {
reference,
document: None,
});
}
upload(client, options, input, key).await
}
pub(crate) async fn upload(
client: &Wellfriend,
options: &RequestOptions,
input: FileInput,
key: Option<String>,
) -> Result<Uploaded> {
let filename = input.resolved_filename();
let content_type = input.resolved_content_type();
let declared_sha = input.sha256.clone();
let key = key.unwrap_or_else(|| options.key());
let content = Content::open(input.source).await?;
let size = content.size();
if size == 0 {
return Err(Error::InvalidInput(format!("{filename} is empty")));
}
if size <= client.inner.upload_threshold {
let document = direct(
client,
options,
content,
&filename,
&content_type,
declared_sha.as_deref(),
&key,
)
.await?;
let reference = VersionRef {
document_id: document.id.clone(),
version_id: document.current_version_id().map(str::to_owned),
};
return Ok(Uploaded {
reference,
document: Some(document),
});
}
let reference = multipart(
client,
options,
content,
&filename,
&content_type,
declared_sha,
&key,
)
.await?;
Ok(Uploaded {
reference,
document: None,
})
}
pub(crate) async fn upload_document(
client: &Wellfriend,
options: &RequestOptions,
input: FileInput,
) -> Result<Document> {
let uploaded = upload(client, options, input, None).await?;
match uploaded.document {
Some(document) => Ok(document),
None => {
let request = Request::new(
Method::GET,
["documents", uploaded.reference.document_id.as_str()],
);
client
.json_field(&options.without_key(), request, "document")
.await
}
}
}
pub(crate) async fn file_body(input: FileInput, content_type: &str) -> Result<RequestBody> {
let content = Content::open(input.source).await?;
Ok(content.into_body(content_type.to_owned()))
}
async fn direct(
client: &Wellfriend,
options: &RequestOptions,
content: Content,
filename: &str,
content_type: &str,
sha256: Option<&str>,
key: &str,
) -> Result<Document> {
let size = content.size();
let replayable = content.replayable();
let body = content.into_body(content_type.to_owned());
let mut request = Request::new(Method::POST, ["documents"])
.body(body)
.header("x-wellfriend-filename", &header_safe(filename))
.idempotency_key(key);
if let Some(sha) = sha256 {
request = request.header("x-content-sha256", sha);
}
debug_assert!(size <= client.inner.upload_threshold);
let options = if replayable {
options.clone()
} else {
options.clone().max_retries(0)
};
client.json_field(&options, request, "document").await
}
async fn multipart(
client: &Wellfriend,
options: &RequestOptions,
mut content: Content,
filename: &str,
content_type: &str,
declared_sha: Option<String>,
key: &str,
) -> Result<VersionRef> {
let size = content.size();
let sha256 = match declared_sha {
Some(sha) => Some(sha),
None if size > CHECKSUM_REQUIRED_ABOVE_BYTES => Some(content.sha256().await?),
None => None,
};
let mut create =
json!({ "filename": filename, "contentType": content_type, "sizeBytes": size });
if let Some(sha) = &sha256 {
create["sha256"] = json!(sha);
}
let request = Request::new(Method::POST, ["uploads"])
.json(json_body(&create, None)?)
.idempotency_key(key);
let upload: Upload = client.json(options, request).await?;
let reads = options.without_key();
if let Some(reference) = finished(&upload)? {
return Ok(reference);
}
let part_size = u64::try_from(upload.part_size_bytes)
.ok()
.filter(|size| *size > 0)
.ok_or_else(|| Error::Decode("the upload has no part size".into()))?;
let part_count = size.div_ceil(part_size);
for index in 0..part_count {
let length = part_size.min(size - index * part_size);
let already = upload
.received_parts
.iter()
.any(|received| u64::try_from(*received) == Ok(index));
let part = content.part(index * part_size, length, already).await?;
let Some(part) = part else { continue };
let digest = crate::util::hex(&Sha256::digest(&part));
let request = Request::new(
Method::PUT,
[
"uploads".to_owned(),
upload.upload_id.clone(),
"parts".to_owned(),
index.to_string(),
],
)
.body(RequestBody::Bytes {
data: part,
content_type: "application/octet-stream".into(),
})
.header("x-part-sha256", &digest)
.retry_always();
let _: UploadPart = client.json(&reads, request).await?;
}
let request = Request::new(
Method::POST,
[
"uploads".to_owned(),
upload.upload_id.clone(),
"complete".to_owned(),
],
)
.json(Bytes::from_static(b"{}"))
.retry_always();
match client.json::<UploadCompletion>(&reads, request).await? {
UploadCompletion::Document { document, .. } => {
let version_id = document.current_version_id().map(str::to_owned);
Ok(VersionRef {
document_id: document.id,
version_id,
})
}
UploadCompletion::Pending(pending) => wait_for_upload(client, &reads, pending).await,
}
}
fn finished(upload: &Upload) -> Result<Option<VersionRef>> {
match &upload.status {
UploadStatus::Completed => match &upload.document_id {
Some(document_id) => Ok(Some(VersionRef {
document_id: document_id.clone(),
version_id: upload.version_id.clone(),
})),
None => Err(Error::Decode(
"the upload completed without a document".into(),
)),
},
UploadStatus::Failed | UploadStatus::Cancelled | UploadStatus::Expired => {
let code = upload
.error
.as_ref()
.and_then(|error| error.get("code"))
.and_then(|code| code.as_str())
.unwrap_or("UPLOAD_FAILED")
.to_owned();
let message = upload
.error
.as_ref()
.and_then(|error| error.get("message"))
.and_then(|m| m.as_str())
.unwrap_or_default()
.to_owned();
Err(Error::OperationFailed(Box::new(
crate::error::OperationFailure {
code,
message: if message.is_empty() {
format!("the upload is {}", upload.status)
} else {
message
},
id: upload.upload_id.clone(),
step: None,
operation: None,
run: None,
},
)))
}
_ => Ok(None),
}
}
async fn wait_for_upload(
client: &Wellfriend,
options: &RequestOptions,
mut upload: Upload,
) -> Result<VersionRef> {
let started = Instant::now();
let limit = options.wait_limit(client);
let mut delay = Duration::from_millis(500);
loop {
if let Some(reference) = finished(&upload)? {
return Ok(reference);
}
if started.elapsed() >= limit {
return Err(Error::WaitTimeout {
kind: "upload",
id: upload.upload_id,
waited: started.elapsed(),
});
}
tokio::time::sleep(delay).await;
delay = (delay.mul_f64(1.5)).min(Duration::from_secs(5));
upload = client
.json(
options,
Request::new(
Method::GET,
["uploads".to_owned(), upload.upload_id.clone()],
),
)
.await?;
}
}
fn header_safe(name: &str) -> String {
let mut out = String::with_capacity(name.len());
for byte in name.bytes() {
if (0x20..0x7f).contains(&byte) && byte != b'%' {
out.push(byte as char);
} else {
out.push_str(&format!("%{byte:02X}"));
}
}
out
}
enum Content {
Path {
path: PathBuf,
size: u64,
file: Option<tokio::fs::File>,
},
Bytes(Bytes),
File {
file: tokio::fs::File,
start: u64,
size: u64,
},
Reader {
reader: Box<dyn AsyncRead + Send + Unpin>,
size: u64,
position: u64,
},
}
impl Content {
async fn open(source: Source) -> Result<Self> {
Ok(match source {
Source::Path(path) => {
let file = tokio::fs::File::open(&path)
.await
.map_err(|error| io_context(error, &path))?;
let size = file.metadata().await?.len();
Content::Path {
path,
size,
file: Some(file),
}
}
Source::Bytes(bytes) => Content::Bytes(bytes),
Source::File { mut file, size } => {
let start = file.stream_position().await?;
let size = match size {
Some(size) => size,
None => file.metadata().await?.len().saturating_sub(start),
};
Content::File { file, start, size }
}
Source::Reader { reader, size } => Content::Reader {
reader,
size,
position: 0,
},
Source::Document(_) => {
return Err(Error::InvalidInput(
"a stored document is not uploaded again".into(),
))
}
})
}
fn size(&self) -> u64 {
match self {
Content::Path { size, .. }
| Content::File { size, .. }
| Content::Reader { size, .. } => *size,
Content::Bytes(bytes) => bytes.len() as u64,
}
}
fn replayable(&self) -> bool {
!matches!(self, Content::Reader { .. })
}
fn into_body(self, content_type: String) -> RequestBody {
match self {
Content::Bytes(data) => RequestBody::Bytes { data, content_type },
Content::Path { path, size, .. } => {
let open = Arc::new(move || -> BodyFuture {
let path = path.clone();
Box::pin(async move {
let file = tokio::fs::File::open(&path).await?;
Ok(reqwest::Body::wrap_stream(read_stream(file, size)))
})
});
RequestBody::Stream {
open,
length: size,
content_type,
}
}
Content::File { file, start, size } => {
let shared = Arc::new(tokio::sync::Mutex::new(file));
let open = Arc::new(move || -> BodyFuture {
let shared = shared.clone();
Box::pin(async move {
let mut file = shared.lock().await.try_clone().await?;
file.seek(SeekFrom::Start(start)).await?;
Ok(reqwest::Body::wrap_stream(read_stream(file, size)))
})
});
RequestBody::Stream {
open,
length: size,
content_type,
}
}
Content::Reader { reader, size, .. } => {
let slot = Arc::new(Mutex::new(Some(reader)));
let open = Arc::new(move || -> BodyFuture {
let taken = slot.lock().ok().and_then(|mut slot| slot.take());
Box::pin(async move {
match taken {
Some(reader) => {
Ok(reqwest::Body::wrap_stream(read_stream(reader, size)))
}
None => Err(std::io::Error::other(
"a reader input can be sent only once",
)),
}
})
});
RequestBody::Stream {
open,
length: size,
content_type,
}
}
}
}
async fn sha256(&mut self) -> Result<String> {
let mut hasher = Sha256::new();
let mut buffer = vec![0u8; READ_CHUNK];
match self {
Content::Bytes(bytes) => hasher.update(bytes),
Content::Path { path, .. } => {
let mut file = tokio::fs::File::open(&*path).await?;
loop {
let read = file.read(&mut buffer).await?;
if read == 0 {
break;
}
hasher.update(&buffer[..read]);
}
}
Content::File { file, start, size } => {
file.seek(SeekFrom::Start(*start)).await?;
let mut remaining = *size;
while remaining > 0 {
let want = buffer.len().min(remaining as usize);
let read = file.read(&mut buffer[..want]).await?;
if read == 0 {
return Err(Error::InvalidInput("the file ended before its declared size".into()));
}
hasher.update(&buffer[..read]);
remaining -= read as u64;
}
}
Content::Reader { .. } => {
return Err(Error::InvalidInput(
"a reader input above 50 MiB needs its SHA-256: use FileInput::with_sha256, or pass a path".into(),
))
}
}
Ok(crate::util::hex(&hasher.finalize()))
}
async fn part(&mut self, offset: u64, length: u64, skip: bool) -> Result<Option<Bytes>> {
let length = usize::try_from(length)
.map_err(|_| Error::InvalidInput("the part size does not fit in memory".into()))?;
match self {
Content::Bytes(bytes) => {
if skip {
return Ok(None);
}
let start = usize::try_from(offset)
.map_err(|_| Error::InvalidInput("offset out of range".into()))?;
Ok(Some(bytes.slice(start..start + length)))
}
Content::Path { path, file, .. } => {
if skip {
return Ok(None);
}
if file.is_none() {
*file = Some(tokio::fs::File::open(&*path).await?);
}
let handle = file
.as_mut()
.ok_or_else(|| Error::InvalidInput("the file could not be opened".into()))?;
handle.seek(SeekFrom::Start(offset)).await?;
read_exact(handle, length).await.map(Some)
}
Content::File { file, start, .. } => {
if skip {
return Ok(None);
}
file.seek(SeekFrom::Start(*start + offset)).await?;
read_exact(file, length).await.map(Some)
}
Content::Reader {
reader, position, ..
} => {
if *position != offset {
return Err(Error::InvalidInput(
"reader parts must be read in order".into(),
));
}
let part = read_exact(reader, length).await?;
*position += length as u64;
Ok(if skip { None } else { Some(part) })
}
}
}
}
async fn read_exact<R: AsyncRead + Unpin + ?Sized>(reader: &mut R, length: usize) -> Result<Bytes> {
let mut buffer = BytesMut::zeroed(length);
reader
.read_exact(&mut buffer)
.await
.map_err(|error| match error.kind() {
std::io::ErrorKind::UnexpectedEof => {
Error::InvalidInput("the input ended before its declared size".into())
}
_ => Error::Io(error),
})?;
Ok(buffer.freeze())
}
fn read_stream<R>(
reader: R,
size: u64,
) -> impl futures_util::Stream<Item = std::io::Result<Bytes>> + Send + 'static
where
R: AsyncRead + Send + Unpin + 'static,
{
stream::try_unfold((reader, size), |(mut reader, remaining)| async move {
if remaining == 0 {
return Ok(None);
}
let want = READ_CHUNK.min(usize::try_from(remaining).unwrap_or(READ_CHUNK));
let mut buffer = BytesMut::zeroed(want);
let read = reader.read(&mut buffer).await?;
if read == 0 {
return Err(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
"the input ended before its declared size",
));
}
buffer.truncate(read);
Ok(Some((buffer.freeze(), (reader, remaining - read as u64))))
})
}
fn io_context(error: std::io::Error, path: &std::path::Path) -> Error {
Error::Io(std::io::Error::new(
error.kind(),
format!("{}: {error}", path.display()),
))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn header_safe_keeps_ascii_and_encodes_the_rest() {
assert_eq!(header_safe("report 2026.pdf"), "report 2026.pdf");
assert_eq!(header_safe("résumé.pdf"), "r%C3%A9sum%C3%A9.pdf");
}
}