use std::sync::Arc;
use super::{ActionCallError, Caller, RemoteActionTarget};
pub const MAX_CONTENT_PUT_CHUNK: usize = 512 * 1024;
pub const MAX_CONTENT_PUT_AHEAD: usize = 8 * MAX_CONTENT_PUT_CHUNK;
pub const MAX_PUT_MANY_BYTES: usize = 384 * 1024;
pub const MAX_PUT_MANY_FILES: usize = 256;
pub const MAX_HAVE_HASHES: usize = 1_024;
pub const MAX_OPEN_CONTENT_PUTS: usize = 64;
pub const CONTENT_PUTS_UNAVAILABLE: &str = "content uploads are not available here";
pub const CONTENT_REFERENCE: &str = "tilo.content:";
#[must_use]
pub fn content_hash(address: &str) -> Option<&str> {
let hash = address.strip_prefix(CONTENT_REFERENCE).unwrap_or(address);
(hash.len() == 64
&& hash
.bytes()
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)))
.then_some(hash)
}
pub trait ContentPuts: Send + Sync {
fn begin(&self, caller: &Caller, size: u64) -> Result<Box<dyn ContentPut>, ActionCallError>;
fn put_many(&self, caller: &Caller, files: &[Vec<u8>]) -> Result<Vec<String>, ActionCallError> {
let mut contents = Vec::with_capacity(files.len());
for bytes in files {
let size = u64::try_from(bytes.len()).unwrap_or(u64::MAX);
let mut put = self.begin(caller, size)?;
put.append(0, bytes)?;
contents.push(put.finish()?);
}
Ok(contents)
}
fn have(&self, caller: &Caller, hashes: &[String]) -> Result<Vec<bool>, ActionCallError> {
let _ = (caller, hashes);
Err(ActionCallError::Unavailable {
reason: "this workspace's content cannot be asked what it holds".into(),
})
}
fn finish(&self, caller: &Caller, put: Box<dyn ContentPut>) -> Result<String, ActionCallError> {
put.finish_as(caller)
}
}
pub trait ContentPut: Send {
fn size(&self) -> u64;
fn written(&self) -> u64;
fn append(&mut self, offset: u64, chunk: &[u8]) -> Result<u64, ActionCallError>;
fn finish(self: Box<Self>) -> Result<String, ActionCallError>;
fn finish_as(self: Box<Self>, caller: &Caller) -> Result<String, ActionCallError> {
let _ = caller;
self.finish()
}
}
pub const MAX_HOSTED_CONTENT_PUTS: usize = 64;
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case", deny_unknown_fields)]
pub enum ContentPutStep {
Begin {
size: u64,
#[serde(default)]
target: Option<RemoteActionTarget>,
},
Append {
upload: u64,
offset: u64,
bytes: String,
},
Finish { upload: u64 },
Many {
files: Vec<String>,
#[serde(default)]
target: Option<RemoteActionTarget>,
},
Have { hashes: Vec<String> },
Progress { upload: u64 },
}
impl ContentPutStep {
#[must_use]
pub fn append(upload: u64, offset: u64, chunk: &[u8]) -> Self {
Self::Append {
upload,
offset,
bytes: hex::encode(chunk),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case", deny_unknown_fields)]
pub enum ContentPutAnswer {
Begun { upload: u64 },
Appended { written: u64 },
Finished { content: String },
Many { contents: Vec<String> },
Have { present: Vec<bool> },
}
#[derive(Default)]
pub struct HostedContentPuts {
open: std::sync::Mutex<HostedOpen>,
}
#[derive(Default)]
struct HostedOpen {
last: u64,
uploads: std::collections::BTreeMap<u64, OpenUpload>,
touched: u64,
}
pub type PutsFor<'a> =
dyn Fn(Option<&RemoteActionTarget>) -> Option<Arc<dyn ContentPuts>> + Send + Sync + 'a;
struct OpenUpload {
caller: Caller,
touched: u64,
put: Box<dyn ContentPut>,
store: Arc<dyn ContentPuts>,
}
impl HostedContentPuts {
fn progress(&self, caller: &Caller, upload: u64) -> Option<ContentPutAnswer> {
use tilo_lock::MutexRecover as _;
self.open
.lock_recover()
.uploads
.get(&upload)
.filter(|open| open.caller == *caller)
.map(|open| ContentPutAnswer::Appended {
written: open.put.written(),
})
}
fn begin(
&self,
store: Arc<dyn ContentPuts>,
caller: &Caller,
size: u64,
) -> Result<ContentPutAnswer, ActionCallError> {
use tilo_lock::MutexRecover as _;
let mut open = self.open.lock_recover();
let mine = open
.uploads
.values()
.filter(|open| open.caller == *caller)
.count();
if mine >= MAX_OPEN_CONTENT_PUTS {
return Err(ActionCallError::InvalidRequest {
reason: format!(
"this session already has {MAX_OPEN_CONTENT_PUTS} uploads open: finish one first"
),
});
}
let put = store.begin(caller, size)?;
while open.uploads.len() >= MAX_HOSTED_CONTENT_PUTS {
let Some(stalest) = open
.uploads
.iter()
.min_by_key(|(_, open)| open.touched)
.map(|(id, _)| *id)
else {
break;
};
open.uploads.remove(&stalest);
}
open.last = open.last.saturating_add(1);
open.touched = open.touched.saturating_add(1);
let (upload, touched) = (open.last, open.touched);
open.uploads.insert(
upload,
OpenUpload {
caller: caller.clone(),
touched,
put,
store,
},
);
drop(open);
Ok(ContentPutAnswer::Begun { upload })
}
fn many(
puts: &dyn ContentPuts,
caller: &Caller,
files: &[String],
) -> Result<ContentPutAnswer, ActionCallError> {
if files.is_empty() {
return Err(ActionCallError::InvalidRequest {
reason: "store at least one file".into(),
});
}
if files.len() > MAX_PUT_MANY_FILES {
return Err(ActionCallError::InvalidRequest {
reason: format!("one call carries at most {MAX_PUT_MANY_FILES} files"),
});
}
let mut decoded = Vec::with_capacity(files.len());
let mut total = 0usize;
for file in files {
if file.len() > MAX_PUT_MANY_BYTES.saturating_mul(2) {
return Err(ActionCallError::InvalidRequest {
reason: format!("one file carries at most {MAX_PUT_MANY_BYTES} bytes"),
});
}
let bytes = hex::decode(file).map_err(|_| ActionCallError::InvalidRequest {
reason: "a file's bytes must be hex".into(),
})?;
total = total.saturating_add(bytes.len());
decoded.push(bytes);
}
if total > MAX_PUT_MANY_BYTES {
return Err(ActionCallError::InvalidRequest {
reason: format!("one call carries at most {MAX_PUT_MANY_BYTES} bytes of files"),
});
}
puts.put_many(caller, &decoded)
.map(|contents| ContentPutAnswer::Many { contents })
}
fn have(
puts: &dyn ContentPuts,
caller: &Caller,
hashes: &[String],
) -> Result<ContentPutAnswer, ActionCallError> {
if hashes.len() > MAX_HAVE_HASHES {
return Err(ActionCallError::InvalidRequest {
reason: format!("one call asks about at most {MAX_HAVE_HASHES} hashes"),
});
}
let mut named = Vec::with_capacity(hashes.len());
for address in hashes {
let hash = content_hash(address).ok_or_else(|| ActionCallError::InvalidRequest {
reason: format!(
"{address} names no content: neither a {CONTENT_REFERENCE} reference nor a \
lowercase BLAKE3 hash"
),
})?;
named.push(hash.to_owned());
}
puts.have(caller, &named)
.map(|present| ContentPutAnswer::Have { present })
}
pub fn step(
&self,
store_for: &PutsFor<'_>,
caller: &Caller,
step: ContentPutStep,
) -> Result<ContentPutAnswer, ActionCallError> {
use tilo_lock::MutexRecover as _;
let gone = |upload: u64| ActionCallError::InvalidRequest {
reason: format!("no upload {upload} is open in this session"),
};
let no_store = || ActionCallError::Unavailable {
reason: "no content store is open here".into(),
};
match step {
ContentPutStep::Begin { size, target } => {
let store = store_for(target.as_ref()).ok_or_else(no_store)?;
self.begin(store, caller, size)
}
ContentPutStep::Append {
upload,
offset,
bytes,
} => {
if bytes.len() > super::MAX_CONTENT_FRAME_BYTES.saturating_mul(2) {
return Err(ActionCallError::InvalidRequest {
reason: format!(
"a piece carries at most {} bytes",
super::MAX_CONTENT_FRAME_BYTES
),
});
}
let chunk = hex::decode(bytes).map_err(|_| ActionCallError::InvalidRequest {
reason: "a piece's bytes must be hex".into(),
})?;
let mut open = self.open.lock_recover();
open.touched = open.touched.saturating_add(1);
let now = open.touched;
let entry = open
.uploads
.get_mut(&upload)
.filter(|open| open.caller == *caller)
.ok_or_else(|| gone(upload))?;
entry.touched = now;
let appended = entry.put.append(offset, &chunk);
if matches!(appended, Err(ActionCallError::Refused { .. })) {
open.uploads.remove(&upload);
}
drop(open);
appended.map(|written| ContentPutAnswer::Appended { written })
}
ContentPutStep::Progress { upload } => {
self.progress(caller, upload).ok_or_else(|| gone(upload))
}
ContentPutStep::Many { files, target } => {
let puts = store_for(target.as_ref()).ok_or_else(no_store)?;
Self::many(puts.as_ref(), caller, &files)
}
ContentPutStep::Have { hashes } => {
let puts = store_for(None).ok_or_else(no_store)?;
Self::have(puts.as_ref(), caller, &hashes)
}
ContentPutStep::Finish { upload } => {
let mut open = self.open.lock_recover();
let found = open
.uploads
.get(&upload)
.filter(|open| open.caller == *caller)
.ok_or_else(|| gone(upload))?;
let (written, size) = (found.put.written(), found.put.size());
if written != size {
return Err(ActionCallError::InvalidRequest {
reason: format!(
"the upload has {written} of {size} bytes: append the rest at offset \
{written}"
),
});
}
let OpenUpload { put, store, .. } =
open.uploads.remove(&upload).ok_or_else(|| gone(upload))?;
drop(open);
store
.finish(caller, put)
.map(|content| ContentPutAnswer::Finished { content })
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
struct Memory;
struct Held(u64, Vec<u8>);
impl ContentPuts for Memory {
fn begin(&self, _: &Caller, size: u64) -> Result<Box<dyn ContentPut>, ActionCallError> {
Ok(Box::new(Held(size, Vec::new())))
}
}
impl ContentPut for Held {
fn size(&self) -> u64 {
self.0
}
fn written(&self) -> u64 {
u64::try_from(self.1.len()).unwrap()
}
fn append(&mut self, offset: u64, chunk: &[u8]) -> Result<u64, ActionCallError> {
if offset != self.written() {
return Err(ActionCallError::InvalidRequest {
reason: "offset".into(),
});
}
self.1.extend_from_slice(chunk);
Ok(self.written())
}
fn finish(self: Box<Self>) -> Result<String, ActionCallError> {
Ok(format!("{} bytes", self.1.len()))
}
}
#[expect(
clippy::unnecessary_wraps,
reason = "a step asks where its bytes go, and this store is always there"
)]
fn store(_: Option<&RemoteActionTarget>) -> Option<Arc<dyn ContentPuts>> {
Some(Arc::new(Memory))
}
#[test]
fn an_upload_is_its_callers_and_finishes_whole() {
let puts = HostedContentPuts::default();
let (ada, eve) = (Caller::local_person("ada"), Caller::local_person("eve"));
let ContentPutAnswer::Begun { upload } = puts
.step(
&store,
&ada,
ContentPutStep::Begin {
size: 4,
target: None,
},
)
.unwrap()
else {
panic!("begun")
};
assert!(
puts.step(&store, &eve, ContentPutStep::append(upload, 0, b"ab"))
.is_err(),
"another caller's upload is not there for it"
);
assert_eq!(
puts.step(&store, &ada, ContentPutStep::append(upload, 0, b"ab"))
.unwrap(),
ContentPutAnswer::Appended { written: 2 }
);
assert!(
puts.step(&store, &ada, ContentPutStep::Finish { upload })
.is_err(),
"half an upload does not finish"
);
assert_eq!(
puts.step(&store, &ada, ContentPutStep::append(upload, 0, b"ab"))
.ok(),
None,
"a piece sent again is refused"
);
assert_eq!(
puts.step(&store, &ada, ContentPutStep::Progress { upload })
.unwrap(),
ContentPutAnswer::Appended { written: 2 },
"the upload says where to resume"
);
assert!(
puts.step(&store, &eve, ContentPutStep::Progress { upload })
.is_err(),
"nobody else learns where it stands"
);
puts.step(&store, &ada, ContentPutStep::append(upload, 2, b"cd"))
.unwrap();
assert_eq!(
puts.step(&store, &ada, ContentPutStep::Finish { upload })
.unwrap(),
ContentPutAnswer::Finished {
content: "4 bytes".into()
}
);
assert!(
puts.step(&store, &ada, ContentPutStep::Finish { upload })
.is_err(),
"a finished upload is closed"
);
}
#[test]
fn a_many_files_step_takes_at_most_its_files() {
let puts = HostedContentPuts::default();
let ada = Caller::local_person("ada");
let whole = vec![String::new(); MAX_PUT_MANY_FILES];
let ContentPutAnswer::Many { contents } = puts
.step(
&store,
&ada,
ContentPutStep::Many {
files: whole,
target: None,
},
)
.unwrap()
else {
panic!("many")
};
assert_eq!(contents.len(), MAX_PUT_MANY_FILES);
let past = vec![String::new(); MAX_PUT_MANY_FILES.saturating_add(1)];
assert!(
puts.step(
&store,
&ada,
ContentPutStep::Many {
files: past,
target: None
}
)
.is_err(),
"a step of more files is refused rather than made to wait"
);
}
}