1use std::sync::Arc;
13
14use super::{ActionCallError, Caller, RemoteActionTarget};
15
16pub const MAX_CONTENT_PUT_CHUNK: usize = 512 * 1024;
20
21pub const MAX_CONTENT_PUT_AHEAD: usize = 8 * MAX_CONTENT_PUT_CHUNK;
33
34pub const MAX_PUT_MANY_BYTES: usize = 384 * 1024;
37
38pub const MAX_PUT_MANY_FILES: usize = 256;
41
42pub const MAX_HAVE_HASHES: usize = 1_024;
47
48pub const MAX_OPEN_CONTENT_PUTS: usize = 64;
52
53pub const CONTENT_PUTS_UNAVAILABLE: &str = "content uploads are not available here";
55
56pub const CONTENT_REFERENCE: &str = "tilo.content:";
58
59#[must_use]
63pub fn content_hash(address: &str) -> Option<&str> {
64 let hash = address.strip_prefix(CONTENT_REFERENCE).unwrap_or(address);
65 (hash.len() == 64
66 && hash
67 .bytes()
68 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)))
69 .then_some(hash)
70}
71
72pub trait ContentPuts: Send + Sync {
74 fn begin(&self, caller: &Caller, size: u64) -> Result<Box<dyn ContentPut>, ActionCallError>;
77
78 fn put_many(&self, caller: &Caller, files: &[Vec<u8>]) -> Result<Vec<String>, ActionCallError> {
84 let mut contents = Vec::with_capacity(files.len());
85 for bytes in files {
86 let size = u64::try_from(bytes.len()).unwrap_or(u64::MAX);
87 let mut put = self.begin(caller, size)?;
88 put.append(0, bytes)?;
89 contents.push(put.finish()?);
90 }
91 Ok(contents)
92 }
93
94 fn have(&self, caller: &Caller, hashes: &[String]) -> Result<Vec<bool>, ActionCallError> {
101 let _ = (caller, hashes);
102 Err(ActionCallError::Unavailable {
103 reason: "this workspace's content cannot be asked what it holds".into(),
104 })
105 }
106
107 fn finish(&self, caller: &Caller, put: Box<dyn ContentPut>) -> Result<String, ActionCallError> {
113 put.finish_as(caller)
114 }
115}
116
117pub trait ContentPut: Send {
120 fn size(&self) -> u64;
122
123 fn written(&self) -> u64;
128
129 fn append(&mut self, offset: u64, chunk: &[u8]) -> Result<u64, ActionCallError>;
134
135 fn finish(self: Box<Self>) -> Result<String, ActionCallError>;
137
138 fn finish_as(self: Box<Self>, caller: &Caller) -> Result<String, ActionCallError> {
144 let _ = caller;
145 self.finish()
146 }
147}
148
149pub const MAX_HOSTED_CONTENT_PUTS: usize = 64;
152
153#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
157#[serde(rename_all = "snake_case", deny_unknown_fields)]
158pub enum ContentPutStep {
159 Begin {
163 size: u64,
164 #[serde(default)]
165 target: Option<RemoteActionTarget>,
166 },
167 Append {
170 upload: u64,
171 offset: u64,
172 bytes: String,
173 },
174 Finish { upload: u64 },
176 Many {
180 files: Vec<String>,
181 #[serde(default)]
182 target: Option<RemoteActionTarget>,
183 },
184 Have { hashes: Vec<String> },
187 Progress { upload: u64 },
191}
192
193impl ContentPutStep {
194 #[must_use]
196 pub fn append(upload: u64, offset: u64, chunk: &[u8]) -> Self {
197 Self::Append {
198 upload,
199 offset,
200 bytes: hex::encode(chunk),
201 }
202 }
203}
204
205#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
207#[serde(rename_all = "snake_case", deny_unknown_fields)]
208pub enum ContentPutAnswer {
209 Begun { upload: u64 },
211 Appended { written: u64 },
213 Finished { content: String },
215 Many { contents: Vec<String> },
217 Have { present: Vec<bool> },
219}
220
221#[derive(Default)]
224pub struct HostedContentPuts {
225 open: std::sync::Mutex<HostedOpen>,
226}
227
228#[derive(Default)]
229struct HostedOpen {
230 last: u64,
231 uploads: std::collections::BTreeMap<u64, OpenUpload>,
234 touched: u64,
235}
236
237pub type PutsFor<'a> =
240 dyn Fn(Option<&RemoteActionTarget>) -> Option<Arc<dyn ContentPuts>> + Send + Sync + 'a;
241
242struct OpenUpload {
244 caller: Caller,
245 touched: u64,
246 put: Box<dyn ContentPut>,
247 store: Arc<dyn ContentPuts>,
248}
249
250impl HostedContentPuts {
251 fn progress(&self, caller: &Caller, upload: u64) -> Option<ContentPutAnswer> {
253 use tilo_lock::MutexRecover as _;
254 self.open
255 .lock_recover()
256 .uploads
257 .get(&upload)
258 .filter(|open| open.caller == *caller)
259 .map(|open| ContentPutAnswer::Appended {
260 written: open.put.written(),
261 })
262 }
263
264 fn begin(
266 &self,
267 store: Arc<dyn ContentPuts>,
268 caller: &Caller,
269 size: u64,
270 ) -> Result<ContentPutAnswer, ActionCallError> {
271 use tilo_lock::MutexRecover as _;
272 let mut open = self.open.lock_recover();
273 let mine = open
274 .uploads
275 .values()
276 .filter(|open| open.caller == *caller)
277 .count();
278 if mine >= MAX_OPEN_CONTENT_PUTS {
279 return Err(ActionCallError::InvalidRequest {
280 reason: format!(
281 "this session already has {MAX_OPEN_CONTENT_PUTS} uploads open: finish one first"
282 ),
283 });
284 }
285 let put = store.begin(caller, size)?;
286 while open.uploads.len() >= MAX_HOSTED_CONTENT_PUTS {
287 let Some(stalest) = open
288 .uploads
289 .iter()
290 .min_by_key(|(_, open)| open.touched)
291 .map(|(id, _)| *id)
292 else {
293 break;
294 };
295 open.uploads.remove(&stalest);
296 }
297 open.last = open.last.saturating_add(1);
298 open.touched = open.touched.saturating_add(1);
299 let (upload, touched) = (open.last, open.touched);
300 open.uploads.insert(
301 upload,
302 OpenUpload {
303 caller: caller.clone(),
304 touched,
305 put,
306 store,
307 },
308 );
309 drop(open);
310 Ok(ContentPutAnswer::Begun { upload })
311 }
312
313 fn many(
315 puts: &dyn ContentPuts,
316 caller: &Caller,
317 files: &[String],
318 ) -> Result<ContentPutAnswer, ActionCallError> {
319 if files.is_empty() {
320 return Err(ActionCallError::InvalidRequest {
321 reason: "store at least one file".into(),
322 });
323 }
324 if files.len() > MAX_PUT_MANY_FILES {
325 return Err(ActionCallError::InvalidRequest {
326 reason: format!("one call carries at most {MAX_PUT_MANY_FILES} files"),
327 });
328 }
329 let mut decoded = Vec::with_capacity(files.len());
330 let mut total = 0usize;
331 for file in files {
332 if file.len() > MAX_PUT_MANY_BYTES.saturating_mul(2) {
333 return Err(ActionCallError::InvalidRequest {
334 reason: format!("one file carries at most {MAX_PUT_MANY_BYTES} bytes"),
335 });
336 }
337 let bytes = hex::decode(file).map_err(|_| ActionCallError::InvalidRequest {
338 reason: "a file's bytes must be hex".into(),
339 })?;
340 total = total.saturating_add(bytes.len());
341 decoded.push(bytes);
342 }
343 if total > MAX_PUT_MANY_BYTES {
344 return Err(ActionCallError::InvalidRequest {
345 reason: format!("one call carries at most {MAX_PUT_MANY_BYTES} bytes of files"),
346 });
347 }
348 puts.put_many(caller, &decoded)
349 .map(|contents| ContentPutAnswer::Many { contents })
350 }
351
352 fn have(
354 puts: &dyn ContentPuts,
355 caller: &Caller,
356 hashes: &[String],
357 ) -> Result<ContentPutAnswer, ActionCallError> {
358 if hashes.len() > MAX_HAVE_HASHES {
359 return Err(ActionCallError::InvalidRequest {
360 reason: format!("one call asks about at most {MAX_HAVE_HASHES} hashes"),
361 });
362 }
363 let mut named = Vec::with_capacity(hashes.len());
364 for address in hashes {
365 let hash = content_hash(address).ok_or_else(|| ActionCallError::InvalidRequest {
366 reason: format!(
367 "{address} names no content: neither a {CONTENT_REFERENCE} reference nor a \
368 lowercase BLAKE3 hash"
369 ),
370 })?;
371 named.push(hash.to_owned());
372 }
373 puts.have(caller, &named)
374 .map(|present| ContentPutAnswer::Have { present })
375 }
376
377 pub fn step(
385 &self,
386 store_for: &PutsFor<'_>,
387 caller: &Caller,
388 step: ContentPutStep,
389 ) -> Result<ContentPutAnswer, ActionCallError> {
390 use tilo_lock::MutexRecover as _;
391 let gone = |upload: u64| ActionCallError::InvalidRequest {
392 reason: format!("no upload {upload} is open in this session"),
393 };
394 let no_store = || ActionCallError::Unavailable {
395 reason: "no content store is open here".into(),
396 };
397 match step {
398 ContentPutStep::Begin { size, target } => {
399 let store = store_for(target.as_ref()).ok_or_else(no_store)?;
400 self.begin(store, caller, size)
401 }
402 ContentPutStep::Append {
403 upload,
404 offset,
405 bytes,
406 } => {
407 if bytes.len() > super::MAX_CONTENT_FRAME_BYTES.saturating_mul(2) {
408 return Err(ActionCallError::InvalidRequest {
409 reason: format!(
410 "a piece carries at most {} bytes",
411 super::MAX_CONTENT_FRAME_BYTES
412 ),
413 });
414 }
415 let chunk = hex::decode(bytes).map_err(|_| ActionCallError::InvalidRequest {
416 reason: "a piece's bytes must be hex".into(),
417 })?;
418 let mut open = self.open.lock_recover();
419 open.touched = open.touched.saturating_add(1);
420 let now = open.touched;
421 let entry = open
422 .uploads
423 .get_mut(&upload)
424 .filter(|open| open.caller == *caller)
425 .ok_or_else(|| gone(upload))?;
426 entry.touched = now;
427 let appended = entry.put.append(offset, &chunk);
428 if matches!(appended, Err(ActionCallError::Refused { .. })) {
429 open.uploads.remove(&upload);
431 }
432 drop(open);
433 appended.map(|written| ContentPutAnswer::Appended { written })
434 }
435 ContentPutStep::Progress { upload } => {
436 self.progress(caller, upload).ok_or_else(|| gone(upload))
437 }
438 ContentPutStep::Many { files, target } => {
439 let puts = store_for(target.as_ref()).ok_or_else(no_store)?;
440 Self::many(puts.as_ref(), caller, &files)
441 }
442 ContentPutStep::Have { hashes } => {
443 let puts = store_for(None).ok_or_else(no_store)?;
444 Self::have(puts.as_ref(), caller, &hashes)
445 }
446 ContentPutStep::Finish { upload } => {
447 let mut open = self.open.lock_recover();
448 let found = open
449 .uploads
450 .get(&upload)
451 .filter(|open| open.caller == *caller)
452 .ok_or_else(|| gone(upload))?;
453 let (written, size) = (found.put.written(), found.put.size());
455 if written != size {
456 return Err(ActionCallError::InvalidRequest {
457 reason: format!(
458 "the upload has {written} of {size} bytes: append the rest at offset \
459 {written}"
460 ),
461 });
462 }
463 let OpenUpload { put, store, .. } =
464 open.uploads.remove(&upload).ok_or_else(|| gone(upload))?;
465 drop(open);
466 store
467 .finish(caller, put)
468 .map(|content| ContentPutAnswer::Finished { content })
469 }
470 }
471 }
472}
473
474#[cfg(test)]
475mod tests {
476
477 use super::*;
478
479 struct Memory;
481
482 struct Held(u64, Vec<u8>);
483
484 impl ContentPuts for Memory {
485 fn begin(&self, _: &Caller, size: u64) -> Result<Box<dyn ContentPut>, ActionCallError> {
486 Ok(Box::new(Held(size, Vec::new())))
487 }
488 }
489
490 impl ContentPut for Held {
491 fn size(&self) -> u64 {
492 self.0
493 }
494 fn written(&self) -> u64 {
495 u64::try_from(self.1.len()).unwrap()
496 }
497 fn append(&mut self, offset: u64, chunk: &[u8]) -> Result<u64, ActionCallError> {
498 if offset != self.written() {
499 return Err(ActionCallError::InvalidRequest {
500 reason: "offset".into(),
501 });
502 }
503 self.1.extend_from_slice(chunk);
504 Ok(self.written())
505 }
506 fn finish(self: Box<Self>) -> Result<String, ActionCallError> {
507 Ok(format!("{} bytes", self.1.len()))
508 }
509 }
510
511 #[expect(
513 clippy::unnecessary_wraps,
514 reason = "a step asks where its bytes go, and this store is always there"
515 )]
516 fn store(_: Option<&RemoteActionTarget>) -> Option<Arc<dyn ContentPuts>> {
517 Some(Arc::new(Memory))
518 }
519
520 #[test]
523 fn an_upload_is_its_callers_and_finishes_whole() {
524 let puts = HostedContentPuts::default();
525 let (ada, eve) = (Caller::local_person("ada"), Caller::local_person("eve"));
526 let ContentPutAnswer::Begun { upload } = puts
527 .step(
528 &store,
529 &ada,
530 ContentPutStep::Begin {
531 size: 4,
532 target: None,
533 },
534 )
535 .unwrap()
536 else {
537 panic!("begun")
538 };
539 assert!(
540 puts.step(&store, &eve, ContentPutStep::append(upload, 0, b"ab"))
541 .is_err(),
542 "another caller's upload is not there for it"
543 );
544 assert_eq!(
545 puts.step(&store, &ada, ContentPutStep::append(upload, 0, b"ab"))
546 .unwrap(),
547 ContentPutAnswer::Appended { written: 2 }
548 );
549 assert!(
550 puts.step(&store, &ada, ContentPutStep::Finish { upload })
551 .is_err(),
552 "half an upload does not finish"
553 );
554 assert_eq!(
555 puts.step(&store, &ada, ContentPutStep::append(upload, 0, b"ab"))
556 .ok(),
557 None,
558 "a piece sent again is refused"
559 );
560 assert_eq!(
561 puts.step(&store, &ada, ContentPutStep::Progress { upload })
562 .unwrap(),
563 ContentPutAnswer::Appended { written: 2 },
564 "the upload says where to resume"
565 );
566 assert!(
567 puts.step(&store, &eve, ContentPutStep::Progress { upload })
568 .is_err(),
569 "nobody else learns where it stands"
570 );
571 puts.step(&store, &ada, ContentPutStep::append(upload, 2, b"cd"))
572 .unwrap();
573 assert_eq!(
574 puts.step(&store, &ada, ContentPutStep::Finish { upload })
575 .unwrap(),
576 ContentPutAnswer::Finished {
577 content: "4 bytes".into()
578 }
579 );
580 assert!(
581 puts.step(&store, &ada, ContentPutStep::Finish { upload })
582 .is_err(),
583 "a finished upload is closed"
584 );
585 }
586
587 #[test]
590 fn a_many_files_step_takes_at_most_its_files() {
591 let puts = HostedContentPuts::default();
592 let ada = Caller::local_person("ada");
593 let whole = vec![String::new(); MAX_PUT_MANY_FILES];
594 let ContentPutAnswer::Many { contents } = puts
595 .step(
596 &store,
597 &ada,
598 ContentPutStep::Many {
599 files: whole,
600 target: None,
601 },
602 )
603 .unwrap()
604 else {
605 panic!("many")
606 };
607 assert_eq!(contents.len(), MAX_PUT_MANY_FILES);
608 let past = vec![String::new(); MAX_PUT_MANY_FILES.saturating_add(1)];
609 assert!(
610 puts.step(
611 &store,
612 &ada,
613 ContentPutStep::Many {
614 files: past,
615 target: None
616 }
617 )
618 .is_err(),
619 "a step of more files is refused rather than made to wait"
620 );
621 }
622}