Skip to main content

tilo_actions/remote/
content_put.rs

1//! Content puts: how a session client hands bytes to its workspace's content
2//! store, chunk by chunk, and gets back a reference to them.
3//!
4//! Actions carry intent and references; bytes travel by session transport
5//! into the content store. A client (an AI agent through MCP, first) puts
6//! the bytes, receives `tilo.content:<hash>` ([`crate::content_resource`])
7//! and passes that reference to an action, which resolves it in the workspace.
8//!
9//! A put is invisible to everyone until an action at its own node
10//! references it: storing content is never authority over any document.
11
12use std::sync::Arc;
13
14use super::{ActionCallError, Caller, RemoteActionTarget};
15
16/// The most raw bytes one append carries. MCP requests are bounded at
17/// 1 MiB; 512 KiB is about 683 KiB of base64, leaving room for the rest of
18/// the request.
19pub const MAX_CONTENT_PUT_CHUNK: usize = 512 * 1024;
20
21/// How far ahead of the bytes accepted so far one append may land: a client
22/// sends a group of [`MAX_CONTENT_PUT_CHUNK`]-sized chunks at once and a slow
23/// link then costs one round trip per group rather than per chunk. The
24/// receiver holds the early ones and appends them as the gap before them
25/// fills; the `written` an answer carries is the bytes held contiguously from
26/// the start. Eight chunks is as many as a client sends in a group.
27///
28/// The frames a chunk is split into travel the same way
29/// ([`super::ContentPut`]): a session hands a device every frame of an upload
30/// before it waits for the first answer, so an upload costs a round trip per
31/// window of frames, not one per frame.
32pub const MAX_CONTENT_PUT_AHEAD: usize = 8 * MAX_CONTENT_PUT_CHUNK;
33
34/// The most raw bytes one many-files step carries (hex doubles them, staying
35/// within [`super::MAX_CONTENT_FRAME_BYTES`]).
36pub const MAX_PUT_MANY_BYTES: usize = 384 * 1024;
37
38/// The most files one many-files step carries: every one is a store write,
39/// and a step answers within the peer's reply deadline.
40pub const MAX_PUT_MANY_FILES: usize = 256;
41
42/// The most hashes one step asks about at once. Every hash costs the store a
43/// look, and one step must answer within the peer's reply deadline: a few
44/// thousand is minutes of looking on a loaded disk, so a caller asks in
45/// steps this size instead.
46pub const MAX_HAVE_HASHES: usize = 1_024;
47
48/// Uploads one session keeps open at once: a client putting a folder keeps
49/// one open per file until it finishes, so it may hold as many as a workspace
50/// keeps for all its callers ([`super::MAX_HOSTED_CONTENT_PUTS`]).
51pub const MAX_OPEN_CONTENT_PUTS: usize = 64;
52
53/// What a provider without a content store answers.
54pub const CONTENT_PUTS_UNAVAILABLE: &str = "content uploads are not available here";
55
56/// The scheme of a content reference: what a put answers for the content it stored.
57pub const CONTENT_REFERENCE: &str = "tilo.content:";
58
59/// The content hash (lowercase BLAKE3 hex) `address` names: a reference as a put answers it
60/// (`tilo.content:<hash>`), or the bare hash of bytes a caller hashed itself. `None` for
61/// anything else.
62#[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
72/// A provider's API for content puts.
73pub trait ContentPuts: Send + Sync {
74    /// Open an upload of exactly `size` bytes into the content store of
75    /// `caller`'s workspace.
76    fn begin(&self, caller: &Caller, size: u64) -> Result<Box<dyn ContentPut>, ActionCallError>;
77
78    /// Store `files` whole, answering each one's reference in order: what a
79    /// folder of small files needs, one call instead of three a file.
80    ///
81    /// # Errors
82    /// What [`Self::begin`] or a file's store refused.
83    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    /// Which of `hashes` the content store of `caller`'s workspace already
95    /// holds, in order: each a reference a put answered, or a bare hash
96    /// ([`content_hash`]). One that names no content is not held.
97    ///
98    /// # Errors
99    /// A store that cannot be asked, or content `caller` may not read.
100    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    /// Store `put`, which `caller` may have begun on a connection that has since ended, and
108    /// answer its reference.
109    ///
110    /// # Errors
111    /// What the put refused ([`ContentPut::finish_as`]).
112    fn finish(&self, caller: &Caller, put: Box<dyn ContentPut>) -> Result<String, ActionCallError> {
113        put.finish_as(caller)
114    }
115}
116
117/// One upload in progress, owned by the session that began it: dropped
118/// unfinished (the session ended), it stores nothing.
119pub trait ContentPut: Send {
120    /// The size the upload began with.
121    fn size(&self) -> u64;
122
123    /// Bytes accepted so far. An upload that reaches another device over a
124    /// session hands its pieces over without waiting for each answer, so it
125    /// answers the bytes handed over: what a piece may land after, and what
126    /// its finish verifies every piece of.
127    fn written(&self) -> u64;
128
129    /// Accept `chunk` at `offset`, answering the bytes accepted so far.
130    /// `offset` must be exactly what was accepted so far, so a chunk sent
131    /// again is refused, never stored twice; the refusal names the offset
132    /// to resume at.
133    fn append(&mut self, offset: u64, chunk: &[u8]) -> Result<u64, ActionCallError>;
134
135    /// Store the content and answer its reference, `tilo.content:<hash>`.
136    fn finish(self: Box<Self>) -> Result<String, ActionCallError>;
137
138    /// [`Self::finish`], decided as `caller`: the same person or app as began the upload,
139    /// finishing it on a later connection of theirs.
140    ///
141    /// # Errors
142    /// What [`Self::finish`] refuses, or a caller other than the one that began the upload.
143    fn finish_as(self: Box<Self>, caller: &Caller) -> Result<String, ActionCallError> {
144        let _ = caller;
145        self.finish()
146    }
147}
148
149/// Open uploads one provider keeps for all its callers at once; past it, the
150/// upload left untouched longest is dropped and stores nothing.
151pub const MAX_HOSTED_CONTENT_PUTS: usize = 64;
152
153/// One step of an upload asked of another device over a session
154/// ([`super::RemoteActionMessage::ContentPutRequest`]): the same begin,
155/// append and finish a local [`ContentPuts`] takes.
156#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
157#[serde(rename_all = "snake_case", deny_unknown_fields)]
158pub enum ContentPutStep {
159    /// Open an upload of exactly `size` bytes, `target` being the action their arguments are for
160    /// when the caller knows it: an action of the caller's own device keeps what it reads on that
161    /// device, and everything else a workspace's store.
162    Begin {
163        size: u64,
164        #[serde(default)]
165        target: Option<RemoteActionTarget>,
166    },
167    /// Accept the next bytes at `offset`, hex-encoded so the frame stays
168    /// self-describing text.
169    Append {
170        upload: u64,
171        offset: u64,
172        bytes: String,
173    },
174    /// Store what the upload holds.
175    Finish { upload: u64 },
176    /// Store several whole files at once, each hex-encoded: the answer names
177    /// each one's reference in order ([`ContentPutAnswer::Many`]), `target`
178    /// naming the action they are for as [`Self::Begin`] does.
179    Many {
180        files: Vec<String>,
181        #[serde(default)]
182        target: Option<RemoteActionTarget>,
183    },
184    /// Ask which of these hashes (lowercase BLAKE3 hex) the store already
185    /// holds ([`ContentPutAnswer::Have`]).
186    Have { hashes: Vec<String> },
187    /// Where the upload stands: answered with the bytes accepted so far
188    /// ([`ContentPutAnswer::Appended`]), so a client whose append failed on
189    /// the way resumes from there.
190    Progress { upload: u64 },
191}
192
193impl ContentPutStep {
194    /// The append of `chunk` at `offset` to `upload`.
195    #[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/// What a device answers a [`ContentPutStep`].
206#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
207#[serde(rename_all = "snake_case", deny_unknown_fields)]
208pub enum ContentPutAnswer {
209    /// The upload is open under `upload`, for the caller who began it.
210    Begun { upload: u64 },
211    /// The bytes accepted so far.
212    Appended { written: u64 },
213    /// The content's reference, `tilo.content:<hash>`.
214    Finished { content: String },
215    /// The reference of each file stored, in the order asked.
216    Many { contents: Vec<String> },
217    /// Whether each hash asked about is held, in the order asked.
218    Have { present: Vec<bool> },
219}
220
221/// The uploads a provider keeps open for the callers that began them over a
222/// session, each answerable only to its own caller.
223#[derive(Default)]
224pub struct HostedContentPuts {
225    open: std::sync::Mutex<HostedOpen>,
226}
227
228#[derive(Default)]
229struct HostedOpen {
230    last: u64,
231    /// By id: who began it, when it was last touched, the upload, and the store it was begun in,
232    /// which finishes it.
233    uploads: std::collections::BTreeMap<u64, OpenUpload>,
234    touched: u64,
235}
236
237/// Where a step's bytes go: the store the action its arguments are for reads, or the caller's own
238/// when it names none.
239pub type PutsFor<'a> =
240    dyn Fn(Option<&RemoteActionTarget>) -> Option<Arc<dyn ContentPuts>> + Send + Sync + 'a;
241
242/// One upload a provider keeps open, and the store it was begun in.
243struct OpenUpload {
244    caller: Caller,
245    touched: u64,
246    put: Box<dyn ContentPut>,
247    store: Arc<dyn ContentPuts>,
248}
249
250impl HostedContentPuts {
251    /// Where `caller`'s open upload `upload` stands, if they have one so called.
252    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    /// Open `size` bytes of `caller`'s in `store`, answering its id here.
265    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    /// Store the files of a [`ContentPutStep::Many`].
314    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    /// Answer which of a [`ContentPutStep::Have`]'s addresses the store holds.
353    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    /// Answer `step` from `caller`, putting into the store `store_for` answers for the action the
378    /// step names, or the one it names for none.
379    ///
380    /// # Errors
381    ///
382    /// What the store refused, an upload the caller has no such open, or bytes
383    /// that are not hex.
384    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                    // The store refused the bytes: the upload is over.
430                    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                // Short of its size, the upload stays open to be completed.
454                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    /// Puts kept in memory, finished as the bytes' length.
480    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    /// The store every step of these tests goes to.
512    #[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    /// An upload over a session answers only the caller that began it,
521    /// finishes only once whole, and is gone once finished.
522    #[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    /// A many-files step takes at most [`MAX_PUT_MANY_FILES`] files, so it
588    /// answers within the peer's reply deadline however small they are.
589    #[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}