Skip to main content

tilo_content/
lib.rs

1//! `tilo-content` — binary content by address.
2//!
3//! Apps keep their data as versioned resources: a log of the actions performed on them, replayed
4//! into state. That is the default. Some bytes are not a resource, though: the photograph a photo
5//! library was imported from, an image placed in a document, a mail attachment. Those are
6//! *binary inputs*. A resource refers to one by its content hash, and the bytes live here, once,
7//! however many documents and versions refer to them.
8
9use std::borrow::Cow;
10use std::collections::{BTreeMap, BTreeSet};
11use std::io::{Read, Seek, Write};
12#[cfg(feature = "dir")]
13use std::path::PathBuf;
14use std::sync::Arc;
15
16#[cfg(feature = "dir")]
17mod dir;
18#[cfg(feature = "dir")]
19mod files;
20mod list;
21mod memory;
22mod reference;
23#[cfg(feature = "dir")]
24mod workspaces;
25
26#[cfg(feature = "dir")]
27pub use dir::DirBackend;
28#[cfg(feature = "dir")]
29pub use files::FilesBackend;
30pub use list::PART_BYTES;
31pub use memory::MemoryBackend;
32pub use reference::{ContentRef, content_address, is_sealed, valid_reference};
33pub use tilo_content_types::{
34    BLOB_SCHEME, ContentMeta, DocumentFormat, FACTS_SCAN_BYTES, ImageFormat, MediaFacts, RECORDING,
35    RECORDING_MAGIC, document_format, facts, has_facts, image_format, image_size, opened_as,
36    opened_by, sniff, valid_hash,
37};
38#[cfg(feature = "dir")]
39pub use workspaces::WorkspaceStores;
40
41#[cfg(feature = "dir")]
42const PAGE_STORE_OWNER: &str = "so.tilo.content";
43/// A page's largest content item: the largest a device keeps of a record's
44/// content, which a page holds whole while it stores it.
45#[cfg(feature = "dir")]
46const PAGE_MAX_ITEM_BYTES: usize = 64 * 1024 * 1024;
47#[cfg(feature = "dir")]
48const PAGE_MAX_TOTAL_BYTES: usize = 256 * 1024 * 1024;
49
50/// The environment variable naming a content directory shared by every app of one session (the
51/// shell sets it for the apps it hosts), so content one app stores another can open.
52pub const SHARED_STORE_ENV: &str = "TILO_BLOB_STORE";
53
54/// The media type sealed content is stored as: its bytes say nothing of what they hold.
55const SEALED_MIME: &str = "application/octet-stream";
56
57/// The address `reference` names, or `reference` itself when it is none (a backend refuses it).
58fn address_of(reference: &str) -> String {
59    content_address(reference).unwrap_or_else(|| reference.to_owned())
60}
61
62/// Hash `bytes` the way every content address in the system is derived: BLAKE3, lower-case hex.
63pub fn hash_bytes(bytes: &[u8]) -> String {
64    blake3::hash(bytes).to_hex().to_string()
65}
66
67/// Whether `bytes` are the content `reference` names: the bytes its address hashes, or for a
68/// sealed reference the bytes whose sealing under its key that address hashes.
69pub fn names(reference: &str, bytes: &[u8]) -> bool {
70    let Some(parsed) = ContentRef::parse(reference) else {
71        return false;
72    };
73    match parsed.key() {
74        None => verify(parsed.address(), bytes),
75        Some(key) => tilo_seal::content::seal(key, bytes)
76            .is_ok_and(|sealed| verify(parsed.address(), &sealed)),
77    }
78}
79
80/// The hash the members' items are keyed by: BLAKE3, keyed by a key derived from the content
81/// secret ([`ContentBackend::content_secret`]).
82fn convergent_hasher(secret: &tilo_seal::SymmetricKey) -> blake3::Hasher {
83    blake3::Hasher::new_keyed(&blake3::derive_key(
84        "tilo record content key v1",
85        secret.expose_secret(),
86    ))
87}
88
89/// The key `bytes` are sealed under by whoever holds the members' content `secret`: the same
90/// bytes take the same key, so they are one item under one reference however often they are kept
91/// ([`ContentBackend::content_secret`]).
92#[must_use]
93pub fn part_key(secret: &tilo_seal::SymmetricKey, bytes: &[u8]) -> tilo_seal::SymmetricKey {
94    let mut hasher = convergent_hasher(secret);
95    hasher.update(bytes);
96    tilo_seal::SymmetricKey::from_bytes(*hasher.finalize().as_bytes())
97}
98
99const KEEP_PLAINTEXT: usize = 1024 * 1024;
100
101/// A file a sealing write keeps the plaintext it hashes in once it no longer fits memory: one
102/// the store makes beside its own content ([`ContentBackend::spill`]), removed when it is
103/// dropped.
104pub trait SpillFile: Read + Write + Seek + Send {}
105
106impl<T: Read + Write + Seek + Send> SpillFile for T {}
107
108/// The plaintext a sealing store hashes before it seals it: in memory while it is small, and
109/// past [`KEEP_PLAINTEXT`] bytes in the store's spill file, so a large item costs disk while it
110/// is sealed rather than the memory to hold it whole. A store with no directory of its own
111/// ([`ContentBackend::spill`]) keeps all of it in memory.
112struct Gathered {
113    kept: Vec<u8>,
114    spill: Option<Box<dyn SpillFile>>,
115    /// Whether the store was asked for a spill file and had none.
116    unspillable: bool,
117}
118
119impl Gathered {
120    const fn new() -> Self {
121        Self {
122            kept: Vec::new(),
123            spill: None,
124            unspillable: false,
125        }
126    }
127
128    /// Keep `chunk`, moving what is kept so far and the rest to `backend`'s spill file once the
129    /// plaintext no longer fits memory.
130    fn keep(&mut self, chunk: &[u8], backend: &dyn ContentBackend) -> Result<(), ContentError> {
131        if self.spill.is_none()
132            && !self.unspillable
133            && self.kept.len().saturating_add(chunk.len()) > KEEP_PLAINTEXT
134        {
135            match backend.spill()? {
136                Some(mut file) => {
137                    file.write_all(&self.kept)?;
138                    self.spill = Some(file);
139                    self.kept = Vec::new();
140                }
141                None => self.unspillable = true,
142            }
143        }
144        if let Some(spill) = &mut self.spill {
145            spill.write_all(chunk)?;
146            return Ok(());
147        }
148        self.kept.extend_from_slice(chunk);
149        Ok(())
150    }
151
152    fn source(&mut self) -> Result<Box<dyn Read + '_>, ContentError> {
153        if let Some(spill) = &mut self.spill {
154            spill.rewind()?;
155            return Ok(Box::new(spill));
156        }
157        Ok(Box::new(self.kept.as_slice()))
158    }
159}
160
161/// A reader whose first read fails as reading the content did.
162struct Failed(Option<std::io::Error>);
163
164impl Read for Failed {
165    fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
166        self.0.take().map_or(Ok(0), Err)
167    }
168}
169
170/// True when `bytes` really are the content named by `hash`.
171pub fn verify(hash: &str, bytes: &[u8]) -> bool {
172    hash_bytes(bytes) == hash
173}
174
175/// Where the content behind an address has got to.
176///
177/// A renderer that only knows "the bytes are not here" draws the same grey box for a transfer in
178/// flight and one that will never complete; the two must be distinguishable.
179#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
180pub enum ContentState {
181    Resolved,
182    Pending,
183    /// Not here, and none of the devices that could hand it over is connected right now. It is
184    /// fetched the moment one connects; nothing waits on a timer.
185    Waiting,
186    /// Not here, and nothing this store can reach is going to provide it: every device that could
187    /// hold it said it does not.
188    Unavailable,
189}
190
191/// Hard limits for a store. They cover both payload and metadata: a document that names millions
192/// of tiny items must not be able to turn a bounded byte budget into an unbounded index.
193#[derive(Debug, Clone, Copy, PartialEq, Eq)]
194pub struct ContentLimits {
195    pub max_item_bytes: usize,
196    /// Largest aggregate payload retained.
197    pub max_total_bytes: usize,
198    /// Largest number of retained items.
199    pub max_entries: usize,
200    /// Largest number of directory entries inspected while building an on-disk index; past it,
201    /// writes are refused rather than scanning without bound.
202    pub max_scan_entries: usize,
203}
204
205impl Default for ContentLimits {
206    fn default() -> Self {
207        Self {
208            max_item_bytes: 64 * 1024 * 1024,
209            max_total_bytes: 1024 * 1024 * 1024,
210            max_entries: 65_536,
211            max_scan_entries: 131_072,
212        }
213    }
214}
215
216/// Why a store refused a write or could not complete a read or collection.
217#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
218pub enum ContentError {
219    #[error("content does not match the address it was stored under")]
220    HashMismatch,
221    #[error("{0:?} is not a content address")]
222    InvalidHash(String),
223    #[error("content is {actual} bytes; per-item limit is {limit} bytes")]
224    ItemTooLarge { actual: usize, limit: usize },
225    #[error("store total would be {attempted} bytes; limit is {limit} bytes")]
226    TotalQuotaExceeded { attempted: usize, limit: usize },
227    #[error("store would contain more than {limit} items")]
228    EntryLimitExceeded { limit: usize },
229    #[error("store index exceeded its {limit}-entry scan bound")]
230    ScanLimitExceeded { limit: usize },
231    #[error("this store cannot collect unreferenced content")]
232    CollectionUnsupported,
233    #[error(
234        "the disk holding this content has {free} bytes free, under the {keep_free} it keeps \
235         for the host's own state: nothing new is kept until there is room"
236    )]
237    DiskLow { free: u64, keep_free: u64 },
238    #[error("content store I/O: {0}")]
239    Io(String),
240}
241
242impl From<std::io::Error> for ContentError {
243    fn from(error: std::io::Error) -> Self {
244        Self::Io(error.to_string())
245    }
246}
247
248#[derive(Debug, Clone, PartialEq, Eq)]
249pub struct Stored {
250    pub hash: String,
251    pub len: u64,
252}
253
254#[derive(Debug, Clone, Default, PartialEq, Eq)]
255pub struct Collected {
256    pub hashes: Vec<String>,
257    pub bytes: u64,
258}
259
260/// A streaming read of stored content. It fails with [`std::io::ErrorKind::InvalidData`] at the
261/// end if the bytes turn out not to match their address, so a consumer that reads to the end has
262/// read verified content.
263pub type ContentReader = Box<dyn Read + Send>;
264
265/// What a [`ContentStore`] runs on. Implementations treat the address as authoritative and verify
266/// content against it; a store that trusts the key would let one peer poison every replica that
267/// later reads that address.
268pub trait ContentBackend: Send + Sync {
269    /// Store everything `reader` yields, returning its address. Storing content already present
270    /// is a no-op that succeeds. `mime` is advisory (a backend may index or serve by it).
271    ///
272    /// # Errors
273    /// Quota, integrity or I/O failures. Nothing is stored on error.
274    fn put(&self, reader: &mut dyn Read, mime: &str) -> Result<Stored, ContentError>;
275
276    /// Store many items, answering each address in order: what [`Self::put`]
277    /// does for each, done together where a backend can (one index update, one
278    /// flush), so a folder of small files costs its bytes rather than its
279    /// calls. A failing item leaves the others' answers in place.
280    fn put_many(&self, items: &[(&[u8], &str)]) -> Vec<Result<Stored, ContentError>> {
281        items
282            .iter()
283            .map(|(bytes, mime)| self.put(&mut &bytes[..], mime))
284            .collect()
285    }
286
287    fn open(&self, hash: &str) -> Result<Option<ContentReader>, ContentError>;
288
289    /// The content at `hash` read from `offset` on: a backend that keeps it in a file seeks
290    /// there, so serving one piece of a large item reads only that piece. Bytes read so are not
291    /// checked against the address (that takes the whole item); sealed content is still
292    /// checked chunk by chunk as it opens.
293    ///
294    /// # Errors
295    /// What [`Self::open`] answers.
296    fn open_at(&self, hash: &str, offset: u64) -> Result<Option<ContentReader>, ContentError> {
297        let Some(mut reader) = self.open(hash)? else {
298            return Ok(None);
299        };
300        std::io::copy(&mut reader.by_ref().take(offset), &mut std::io::sink())?;
301        Ok(Some(reader))
302    }
303
304    fn has(&self, hash: &str) -> bool;
305
306    /// The length of the content at `hash`, when the store knows it without
307    /// reading the bytes: what a reader serving one piece of a large file
308    /// asks before it seeks there.
309    fn size(&self, hash: &str) -> Option<u64> {
310        let _ = hash;
311        None
312    }
313
314    /// Where the content at `hash` has got to. A backend that can fetch from elsewhere reports
315    /// [`ContentState::Pending`] while it does, and may start fetching when asked.
316    fn state(&self, hash: &str) -> ContentState {
317        if self.has(hash) {
318            ContentState::Resolved
319        } else {
320            ContentState::Unavailable
321        }
322    }
323
324    /// Remove every item whose address is not in `live`, which must be complete: the caller
325    /// asserts nothing outside it is referenced by anything it is responsible for.
326    ///
327    /// # Errors
328    /// [`ContentError::CollectionUnsupported`] for backends whose retention another store
329    /// decides (a shared device store), or an I/O failure part-way (retry with the same live set).
330    fn collect_unreferenced(&self, live: &BTreeSet<String>) -> Result<Collected, ContentError> {
331        let _ = live;
332        Err(ContentError::CollectionUnsupported)
333    }
334
335    /// Remove the item `hash`, when the one who keeps it here knows nothing it is responsible
336    /// for references it any longer (a quota letting the oldest item go). Content kept for
337    /// another reason under the same address goes with it, so a caller sharing a store removes
338    /// only what it alone keeps.
339    ///
340    /// # Errors
341    /// [`ContentError::CollectionUnsupported`] for backends whose retention another store
342    /// decides, or an I/O failure.
343    fn release(&self, hash: &str) -> Result<Collected, ContentError> {
344        let _ = hash;
345        Err(ContentError::CollectionUnsupported)
346    }
347
348    /// Whether content stored here reaches beyond this device's own copy: the device content
349    /// store serves it to the app's other devices and members. A document may then refer
350    /// to content by address alone; with a store that is not shared, a member would be left
351    /// holding an address nothing can resolve.
352    fn shared(&self) -> bool {
353        false
354    }
355
356    /// Whether this store answers only for content readable in one workspace: the device content
357    /// store reads through the scope the launcher handed the window, and serves an address only
358    /// when that workspace references it. A caller's content reference is resolved only in such
359    /// a store, so naming a hash never reaches content from elsewhere on this machine.
360    fn workspace_scoped(&self) -> bool {
361        false
362    }
363
364    /// The secret the members who read what this store keeps hold, when it is at hand: a
365    /// sealing store ([`ContentStore::sealing`]) then seals each item under a key derived from
366    /// it and the item's bytes, rather than a fresh one, so the same bytes stored twice are the
367    /// same ciphertext under the same reference, kept and carried once.
368    ///
369    /// Whoever holds the secret learns which items are the same bytes, and can tell whether a
370    /// given item is among them; the members can tell that anyway, by opening both. Whoever does
371    /// not hold it (the hosts that keep and carry the ciphertext, a device removed before the
372    /// secret was derived) learns nothing: without the secret no key, and no address, follows
373    /// from any bytes. The key never leaves the reference, which travels inside the sealed
374    /// record, so a reader who joins later opens the item as before, and a reference sealed
375    /// under a fresh key opens as it always did.
376    fn content_secret(&self) -> Option<tilo_seal::SymmetricKey> {
377        None
378    }
379
380    /// Seal and keep what `reader` yields, when the store behind this backend seals what it is
381    /// handed itself, under the members' secret it holds and this backend does not (a session's
382    /// store, whose device's daemon holds the workspace's keys): the sealed reference it answers
383    /// is what a sealing store hands back. `None`, reading nothing, when the backend keeps only
384    /// what is sealed before it reaches it.
385    fn put_sealed(
386        &self,
387        reader: &mut dyn Read,
388        mime: &str,
389    ) -> Option<Result<Stored, ContentError>> {
390        let _ = (reader, mime);
391        None
392    }
393
394    /// The largest item this store accepts: a write that hashes before it seals refuses a larger
395    /// one as it reads it, rather than holding it whole first ([`ContentStore::put_reader`]).
396    fn max_item_bytes(&self) -> usize {
397        ContentLimits::default().max_item_bytes
398    }
399
400    /// A new file beside the content this store keeps, where a sealing write keeps the plaintext
401    /// it hashes rather than in memory, removed when it is dropped. `None` for a store with no
402    /// directory of its own: one that keeps content on a host, or holds it in memory.
403    ///
404    /// # Errors
405    /// The file could not be made.
406    fn spill(&self) -> std::io::Result<Option<Box<dyn SpillFile>>> {
407        Ok(None)
408    }
409}
410
411/// A store a host keeps for one workspace alone
412/// ([`ContentStore::for_one_workspace`]).
413struct OneWorkspace(Arc<dyn ContentBackend>);
414
415impl ContentBackend for OneWorkspace {
416    fn put(&self, reader: &mut dyn Read, mime: &str) -> Result<Stored, ContentError> {
417        self.0.put(reader, mime)
418    }
419
420    fn open(&self, hash: &str) -> Result<Option<ContentReader>, ContentError> {
421        self.0.open(hash)
422    }
423
424    fn open_at(&self, hash: &str, offset: u64) -> Result<Option<ContentReader>, ContentError> {
425        self.0.open_at(hash, offset)
426    }
427
428    fn has(&self, hash: &str) -> bool {
429        self.0.has(hash)
430    }
431
432    fn size(&self, hash: &str) -> Option<u64> {
433        self.0.size(hash)
434    }
435
436    fn state(&self, hash: &str) -> ContentState {
437        self.0.state(hash)
438    }
439
440    fn collect_unreferenced(&self, live: &BTreeSet<String>) -> Result<Collected, ContentError> {
441        self.0.collect_unreferenced(live)
442    }
443
444    fn release(&self, hash: &str) -> Result<Collected, ContentError> {
445        self.0.release(hash)
446    }
447
448    fn shared(&self) -> bool {
449        self.0.shared()
450    }
451
452    fn workspace_scoped(&self) -> bool {
453        true
454    }
455
456    fn content_secret(&self) -> Option<tilo_seal::SymmetricKey> {
457        self.0.content_secret()
458    }
459
460    fn max_item_bytes(&self) -> usize {
461        self.0.max_item_bytes()
462    }
463
464    fn spill(&self) -> std::io::Result<Option<Box<dyn SpillFile>>> {
465        self.0.spill()
466    }
467}
468
469/// An app's handle to binary content: cheap to clone, passed to whatever needs it.
470///
471/// Everything here takes a reference ([`ContentRef`]) where it names content: a plain address, or a
472/// sealed reference, which reads through its key. What a store hands back for what it stored is the
473/// reference to keep: sealed when the store seals ([`Self::sealing`]).
474#[derive(Clone)]
475pub struct ContentStore {
476    backend: Arc<dyn ContentBackend>,
477    seals: bool,
478}
479
480impl std::fmt::Debug for ContentStore {
481    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
482        f.debug_struct("ContentStore").finish_non_exhaustive()
483    }
484}
485
486impl ContentStore {
487    pub fn new(backend: impl ContentBackend + 'static) -> Self {
488        Self::from_backend(Arc::new(backend))
489    }
490
491    pub fn from_backend(backend: Arc<dyn ContentBackend>) -> Self {
492        Self {
493            backend,
494            seals: false,
495        }
496    }
497
498    /// This store, sealing what it stores: each item under a key of its own, kept under the
499    /// address of its ciphertext, and named by a reference that carries the key. The key derives
500    /// from the members' content secret and the bytes when the backend holds one
501    /// ([`ContentBackend::content_secret`]), and is fresh otherwise. The store a record's content
502    /// travels through seals, so the record's readers alone open it.
503    #[must_use]
504    pub fn sealing(self) -> Self {
505        Self {
506            seals: true,
507            ..self
508        }
509    }
510
511    /// This store, keeping what it stores under its own address, unsealed: for code that must name
512    /// content alike wherever it runs (an action applying on every replica). Sealed references
513    /// still read.
514    #[must_use]
515    pub fn unsealed(self) -> Self {
516        Self {
517            seals: false,
518            ..self
519        }
520    }
521
522    pub fn memory() -> Self {
523        Self::new(MemoryBackend::default())
524    }
525
526    #[cfg(feature = "dir")]
527    pub fn in_dir(root: impl Into<PathBuf>) -> Self {
528        Self::new(DirBackend::new(root))
529    }
530
531    /// The store an app keeps on this machine when the launcher handed it no device content
532    /// store (`tilo_content_device::for_app` prefers that one): the session's shared directory
533    /// when the host names one ([`SHARED_STORE_ENV`]), otherwise, where files have no native path
534    /// (a browser page), the profile's app files ([`FilesBackend`]), otherwise `tilo/content` in
535    /// the user's data directory. Content an earlier version kept in the cache directory
536    /// (`tilo/blobs`) still reads. With no usable directory at all, content is kept in memory.
537    #[cfg(feature = "dir")]
538    pub fn local_for_app() -> Self {
539        Self::for_app_with(&|name| std::env::var_os(name))
540    }
541
542    #[cfg(feature = "dir")]
543    fn for_app_with(env: &dyn Fn(&str) -> Option<std::ffi::OsString>) -> Self {
544        if let Some(shared) = env(SHARED_STORE_ENV).filter(|value| !value.is_empty()) {
545            return Self::in_dir(PathBuf::from(shared));
546        }
547        if !tilo_files::available(tilo_files::Feature::NativePaths) {
548            return Self::page_files();
549        }
550        let Some(data) = tilo_paths::data_dir() else {
551            tracing::warn!("no data directory; binary content is kept in memory only");
552            return Self::memory();
553        };
554        let mut backend = DirBackend::new(data.join("tilo").join("content"));
555        if let Some(cache) = tilo_paths::cache_dir() {
556            backend = backend.reading_also(cache.join("tilo").join("blobs"));
557        }
558        Self::new(backend)
559    }
560
561    /// Where files have no native path (a browser page): content in the profile's app files,
562    /// which outlive the page, so an upload a page stored is still here after a reload. Every
563    /// app of the profile shares the one store, as native apps share `tilo/content`. The page
564    /// holds those files in memory, so the store is bounded: an item or store past the bound is
565    /// refused, never dropped, and nothing collects what the page stored on its own. A page whose
566    /// host loaded no app files keeps content in memory, under the same bounds, as a tab alone can.
567    ///
568    /// This is the store a page host lends each window it opens, as the framework's native
569    /// process host lends `tilo_content_device::for_app`'s: a window keeps content in the store
570    /// its host lent it (`cx.content()`), never in one it opens itself.
571    #[cfg(feature = "dir")]
572    #[must_use]
573    pub fn page_files() -> Self {
574        let limits = ContentLimits {
575            max_item_bytes: PAGE_MAX_ITEM_BYTES,
576            max_total_bytes: PAGE_MAX_TOTAL_BYTES,
577            ..ContentLimits::default()
578        };
579        #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
580        let mirrored = tilo_files::web::is_mirrored(&tilo_paths::default_profile());
581        #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
582        let mirrored = true;
583        match tilo_files::VPath::new("content") {
584            Ok(content) if mirrored => Self::new(FilesBackend::new(
585                tilo_paths::AppPaths::for_app(PAGE_STORE_OWNER)
586                    .data()
587                    .join(&content),
588                limits,
589            )),
590            _ => Self::new(MemoryBackend::new(limits)),
591        }
592    }
593
594    /// Whether this store seals what it keeps, so its writes go one at a time.
595    #[must_use]
596    pub const fn seals(&self) -> bool {
597        self.seals
598    }
599
600    /// Store `bytes`, returning the reference to keep: sealed when this store seals. The media
601    /// type is sniffed from the content.
602    ///
603    /// # Errors
604    /// See [`ContentBackend::put`].
605    pub fn put(&self, bytes: &[u8]) -> Result<String, ContentError> {
606        let mime = sniff(bytes).mime;
607        let mut reader = bytes;
608        self.put_reader(&mut reader, &mime)
609            .map(|stored| stored.hash)
610    }
611
612    /// Store `bytes` as they are, under their own address, even in a store that seals: content
613    /// that is public by nature (an app's surface, which whoever decides its changes reads).
614    ///
615    /// # Errors
616    /// See [`ContentBackend::put`].
617    pub fn put_public(&self, bytes: &[u8]) -> Result<String, ContentError> {
618        let mut reader = bytes;
619        self.backend
620            .put(&mut reader, &sniff(bytes).mime)
621            .map(|stored| stored.hash)
622    }
623
624    /// Keep many items, answering each one's address in order: [`Self::put_public`]
625    /// for each, one store write where the backend can make it.
626    ///
627    /// # Errors
628    /// Each item its own, as [`Self::put_public`] refuses it.
629    pub fn put_public_many(&self, items: &[&[u8]]) -> Vec<Result<String, ContentError>> {
630        let mimes: Vec<String> = items.iter().map(|bytes| sniff(bytes).mime).collect();
631        let with_mime: Vec<(&[u8], &str)> = items
632            .iter()
633            .zip(&mimes)
634            .map(|(bytes, mime)| (*bytes, mime.as_str()))
635            .collect();
636        self.backend
637            .put_many(&with_mime)
638            .into_iter()
639            .map(|stored| stored.map(|stored| stored.hash))
640            .collect()
641    }
642
643    /// Keep `bytes` as the content `reference` names: sealed under its key when it carries one, so
644    /// a device that holds the bytes keeps exactly what the writer stored. Refused when `bytes`
645    /// are not that content.
646    ///
647    /// # Errors
648    /// [`ContentError::HashMismatch`] for other bytes, else see [`ContentBackend::put`].
649    pub fn put_as(&self, reference: &str, bytes: &[u8]) -> Result<(), ContentError> {
650        let parsed = ContentRef::parse(reference)
651            .ok_or_else(|| ContentError::InvalidHash(reference.to_owned()))?;
652        let stored = match parsed.key() {
653            None => self.put_public(bytes)?,
654            Some(key) => {
655                let sealed = tilo_seal::content::seal(key, bytes)
656                    .map_err(|error| ContentError::Io(error.to_string()))?;
657                let mut reader = sealed.as_slice();
658                self.backend.put(&mut reader, SEALED_MIME)?.hash
659            }
660        };
661        if stored == parsed.address() {
662            Ok(())
663        } else {
664            Err(ContentError::HashMismatch)
665        }
666    }
667
668    /// Store everything `reader` yields without holding it in memory: the device store sends it
669    /// to the daemon one `runtime_fs::blobs::MAX_PUT_CHUNK` at a time. [`Stored::hash`] is the
670    /// reference to keep, sealed when this store seals.
671    ///
672    /// A sealing store with the members' secret hashes the plaintext in a first pass and seals it
673    /// in a second, and refuses it once it is past [`ContentBackend::max_item_bytes`]: a large
674    /// item waits in a file beside the store's own content
675    /// ([`ContentBackend::scratch_dir`]) rather than whole in memory, and an oversized one is
676    /// refused without being held at all.
677    ///
678    /// # Errors
679    /// See [`ContentBackend::put`], and [`ContentError::ItemTooLarge`] for an item past the
680    /// store's limit.
681    pub fn put_reader(&self, reader: &mut dyn Read, mime: &str) -> Result<Stored, ContentError> {
682        if !self.seals {
683            return self.backend.put(reader, mime);
684        }
685        if let Some(stored) = self.backend.put_sealed(reader, mime) {
686            return stored;
687        }
688        // With the members' secret the key is the bytes' keyed hash, so they are read once to
689        // hash them, kept in memory while they are small and in a file beside the store's own
690        // content past that, then read again to seal them. Such a key seals the one plaintext it
691        // was derived from, as a fresh one does, so the nonces sealing derives from a chunk's
692        // position never repeat under it.
693        let mut gathered = None;
694        let key = match self.backend.content_secret() {
695            Some(secret) => {
696                let mut hasher = convergent_hasher(&secret);
697                gathered = Some(self.gather(reader, &mut hasher)?);
698                tilo_seal::SymmetricKey::from_bytes(*hasher.finalize().as_bytes())
699            }
700            None => tilo_seal::SymmetricKey::generate()
701                .map_err(|error| ContentError::Io(error.to_string()))?,
702        };
703        let source: Box<dyn Read + '_> = match &mut gathered {
704            Some(gathered) => gathered.source()?,
705            None => Box::new(reader),
706        };
707        let mut sealed = tilo_seal::content::SealReader::new(&key, source)
708            .map_err(|error| ContentError::Io(error.to_string()))?;
709        let stored = self.backend.put(&mut sealed, SEALED_MIME)?;
710        Ok(Stored {
711            hash: ContentRef::sealed(&stored.hash, key).to_string(),
712            len: stored.len,
713        })
714    }
715
716    /// Read `reader` to its end, hashing what it yields into `hasher`, and refuse it the moment
717    /// it is past what the store accepts: what it yields waits in memory while it is small, and
718    /// past that in a file beside the store's own content.
719    fn gather(
720        &self,
721        reader: &mut dyn Read,
722        hasher: &mut blake3::Hasher,
723    ) -> Result<Gathered, ContentError> {
724        let limit = self.backend.max_item_bytes();
725        let mut gathered = Gathered::new();
726        let mut buf = vec![0_u8; 64 * 1024];
727        let mut read = 0_usize;
728        loop {
729            // Never ask for more than the byte past the limit that refuses the item.
730            let want = limit.saturating_add(1).saturating_sub(read).min(buf.len());
731            let n = match reader.read(buf.get_mut(..want).unwrap_or_default()) {
732                Ok(0) => return Ok(gathered),
733                Ok(n) => n.min(want),
734                Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
735                Err(error) => return Err(error.into()),
736            };
737            read = read.saturating_add(n);
738            if read > limit {
739                return Err(ContentError::ItemTooLarge {
740                    actual: read,
741                    limit,
742                });
743            }
744            let chunk = buf.get(..n).unwrap_or_default();
745            hasher.update(chunk);
746            gathered.keep(chunk, &*self.backend)?;
747        }
748    }
749
750    /// Store every input `inputs` collected (an import's images, say), answering the reference to
751    /// keep for each input's address: the address itself, or a sealed reference when this store
752    /// seals, which the document naming the input names instead.
753    ///
754    /// # Errors
755    /// The first refusal; inputs stored before it stay stored.
756    pub fn put_inputs(
757        &self,
758        inputs: &ContentInputs,
759    ) -> Result<BTreeMap<String, String>, ContentError> {
760        let mut references = BTreeMap::new();
761        for (hash, bytes) in inputs.iter() {
762            let reference = self.put(bytes)?;
763            if content_address(&reference).as_deref() != Some(hash) && !self.seals {
764                return Err(ContentError::HashMismatch);
765            }
766            references.insert(hash.to_owned(), reference);
767        }
768        Ok(references)
769    }
770
771    /// Store again, sealed, the plain content `reference` names, when this store seals and it is
772    /// here: the sealed reference a record keeps in its place. `None` for a reference already
773    /// sealed, a store that does not seal, or content not here yet. The plain copy stays until
774    /// nothing references it ([`Self::collect_unreferenced`]), so a reader still holding the old
775    /// reference reads it meanwhile.
776    pub fn reseal(&self, reference: &str) -> Option<String> {
777        if !self.seals || is_sealed(reference) {
778            return None;
779        }
780        let bytes = self.read(reference)?;
781        self.put(&bytes)
782            .inspect_err(|error| tracing::warn!(%error, "content could not be sealed"))
783            .ok()
784    }
785
786    /// The verified content `reference` names, opened when sealed, or `None` when it is not here
787    /// (or not intact).
788    pub fn read(&self, reference: &str) -> Option<Vec<u8>> {
789        let mut reader = self.open(reference)?;
790        let mut bytes = Vec::new();
791        match reader.read_to_end(&mut bytes) {
792            Ok(_) => Some(bytes),
793            Err(error) => {
794                tracing::warn!(%error, "content store: unreadable content");
795                None
796            }
797        }
798    }
799
800    /// A streaming, verifying read of the content `reference` names, opened as it streams when
801    /// sealed; see [`ContentReader`]. Content kept in parts ([`Self::put_parts`]) reads as the
802    /// content its parts make, and is `None` until every part is here: each part not here is
803    /// asked for at once.
804    pub fn open(&self, reference: &str) -> Option<ContentReader> {
805        let mut item = self.open_item(reference)?;
806        match list::List::read(&mut item) {
807            Ok(Ok(list)) => {
808                // Every missing part is asked for, not only the first.
809                let mut missing = false;
810                for (_, part) in &list.parts {
811                    if !self.has(part) {
812                        // Opening what is not here asks for it.
813                        let _ = self.backend.open(&address_of(part));
814                        missing = true;
815                    }
816                }
817                if missing {
818                    return None;
819                }
820                let mut left: Vec<String> = list.parts.into_iter().map(|(_, part)| part).collect();
821                left.reverse();
822                Some(Box::new(list::Parts {
823                    store: self.clone(),
824                    left,
825                    current: None,
826                }))
827            }
828            Ok(Err(read)) => Some(Box::new(std::io::Cursor::new(read).chain(item))),
829            // What failed reading the item's start (a check that does not
830            // hold on a short item) fails the reader, as it would have read on.
831            Err(error) => Some(Box::new(Failed(Some(error)))),
832        }
833    }
834
835    /// The one item `reference` names, opened when sealed: a list of parts as the list.
836    fn open_item(&self, reference: &str) -> Option<ContentReader> {
837        let parsed = ContentRef::parse(reference);
838        let address = parsed.as_ref().map_or(reference, ContentRef::address);
839        let reader = self.backend.open(address).ok().flatten()?;
840        match parsed.as_ref().and_then(ContentRef::key) {
841            None => Some(reader),
842            Some(key) => tilo_seal::content::OpenReader::new(key, reader)
843                .ok()
844                .map(|reader| Box::new(reader) as ContentReader),
845        }
846    }
847
848    /// The one item `reference` names, read whole: a list of parts as the list.
849    #[cfg(test)]
850    fn read_item_whole(&self, reference: &str) -> Vec<u8> {
851        let mut bytes = Vec::new();
852        if let Some(mut item) = self.open_item(reference) {
853            let _ = item.read_to_end(&mut bytes);
854        }
855        bytes
856    }
857
858    /// The parts `reference` is kept in, when it is a list of them.
859    fn list(&self, reference: &str) -> Option<list::List> {
860        let mut item = self.open_item(reference)?;
861        list::List::read(&mut item).ok()?.ok()
862    }
863
864    /// Store everything `reader` yields a part at a time ([`list::PART_BYTES`]), never holding
865    /// more than one part: content of any size, kept as items no larger than a part. Content
866    /// that fits in one part is that one item; larger content is its parts and a list naming
867    /// them, whose reference reads as the whole ([`Self::open`]). Each is sealed when this store
868    /// seals.
869    ///
870    /// # Errors
871    /// What storing a part or the list refused, or reading `reader` failed with.
872    pub fn put_parts(&self, reader: &mut dyn Read) -> Result<Stored, ContentError> {
873        let mut parts = Vec::new();
874        let mut part = Vec::with_capacity(list::PART_BYTES);
875        loop {
876            part.clear();
877            (&mut *reader)
878                .take(list::PART_BYTES as u64)
879                .read_to_end(&mut part)?;
880            if part.is_empty() && !parts.is_empty() {
881                break;
882            }
883            let len = part.len() as u64;
884            parts.push((len, self.put(&part)?));
885            if part.len() < list::PART_BYTES {
886                break;
887            }
888        }
889        if let [(len, only)] = parts.as_slice() {
890            return Ok(Stored {
891                hash: only.clone(),
892                len: *len,
893            });
894        }
895        let list = list::List { parts };
896        let len = list.total();
897        Ok(Stored {
898            hash: self.put(&list.encode())?,
899            len,
900        })
901    }
902
903    /// The length of the content `reference` names, when the store knows it
904    /// without reading it: for sealed content, the plaintext its sealed
905    /// bytes hold; for content kept in parts, what its parts make.
906    pub fn size(&self, reference: &str) -> Option<u64> {
907        if let Some(list) = self.list(reference) {
908            return Some(list.total());
909        }
910        self.item_size(reference)
911    }
912
913    fn item_size(&self, reference: &str) -> Option<u64> {
914        let parsed = ContentRef::parse(reference);
915        let address = parsed.as_ref().map_or(reference, ContentRef::address);
916        let stored = self.backend.size(address)?;
917        match parsed.as_ref().and_then(ContentRef::key) {
918            None => Some(stored),
919            Some(_) => tilo_seal::content::plain_len(stored),
920        }
921    }
922
923    /// `length` bytes of the content `reference` names, from `offset`: the
924    /// bytes read, and the content's length. Reads only what it answers, so
925    /// serving one piece of a large file does not read the file: sealed
926    /// content opens from the chunk the piece begins in, and content kept in
927    /// parts reads only the parts the piece is in.
928    ///
929    /// # Errors
930    /// The content is not here, or cannot be read.
931    pub fn read_range(
932        &self,
933        reference: &str,
934        offset: u64,
935        length: u64,
936    ) -> Result<(u64, Vec<u8>), ContentError> {
937        let Some(list) = self.list(reference) else {
938            return self.read_item_range(reference, offset, length);
939        };
940        let size = list.total();
941        let end = offset.saturating_add(length).min(size);
942        let mut bytes = Vec::new();
943        let mut start = 0_u64;
944        for (len, part) in &list.parts {
945            let stop = start.saturating_add(*len);
946            if stop > offset && start < end {
947                let from = offset.max(start).saturating_sub(start);
948                let to = end.min(stop).saturating_sub(start);
949                let (_, piece) = self.read_item_range(part, from, to.saturating_sub(from))?;
950                bytes.extend_from_slice(&piece);
951            }
952            start = stop;
953        }
954        Ok((size, bytes))
955    }
956
957    fn read_item_range(
958        &self,
959        reference: &str,
960        offset: u64,
961        length: u64,
962    ) -> Result<(u64, Vec<u8>), ContentError> {
963        let missing = || ContentError::InvalidHash(reference.to_owned());
964        let size = self.item_size(reference).ok_or_else(missing)?;
965        let offset = offset.min(size);
966        let length = length.min(size.saturating_sub(offset));
967        let parsed = ContentRef::parse(reference);
968        let address = parsed.as_ref().map_or(reference, ContentRef::address);
969        let (mut reader, skip): (ContentReader, u64) =
970            match parsed.as_ref().and_then(ContentRef::key) {
971                None => (
972                    self.backend.open_at(address, offset)?.ok_or_else(missing)?,
973                    0,
974                ),
975                Some(key) => {
976                    let chunk = tilo_seal::content::CHUNK as u64;
977                    let index = offset.checked_div(chunk).unwrap_or(0);
978                    let sealed = self
979                        .backend
980                        .open_at(address, tilo_seal::content::sealed_offset(index))?
981                        .ok_or_else(missing)?;
982                    let opened = tilo_seal::content::OpenReader::at_chunk(key, sealed, index)
983                        .map_err(|error| ContentError::Io(error.to_string()))?;
984                    (
985                        Box::new(opened),
986                        offset.saturating_sub(index.saturating_mul(chunk)),
987                    )
988                }
989            };
990        let unreadable = |error: std::io::Error| ContentError::Io(error.to_string());
991        std::io::copy(&mut reader.by_ref().take(skip), &mut std::io::sink()).map_err(unreadable)?;
992        let mut bytes = Vec::with_capacity(usize::try_from(length).unwrap_or(0));
993        reader
994            .take(length)
995            .read_to_end(&mut bytes)
996            .map_err(unreadable)?;
997        if (bytes.len() as u64) < length {
998            return Err(ContentError::Io(format!(
999                "{reference} ended {} bytes short of the piece asked for",
1000                length.saturating_sub(bytes.len() as u64)
1001            )));
1002        }
1003        Ok((size, bytes))
1004    }
1005
1006    pub fn has(&self, reference: &str) -> bool {
1007        self.backend.has(&address_of(reference))
1008    }
1009
1010    pub fn state(&self, reference: &str) -> ContentState {
1011        self.backend.state(&address_of(reference))
1012    }
1013
1014    /// Whether content stored here reaches the app's other devices and members; see
1015    /// [`ContentBackend::shared`].
1016    pub fn shared(&self) -> bool {
1017        self.backend.shared()
1018    }
1019
1020    /// Whether this store answers only for content readable in one workspace;
1021    /// see [`ContentBackend::workspace_scoped`].
1022    pub fn workspace_scoped(&self) -> bool {
1023        self.backend.workspace_scoped()
1024    }
1025
1026    /// A new file beside the content this store keeps, where a sealing write keeps the plaintext
1027    /// it hashes; see [`ContentBackend::spill`].
1028    ///
1029    /// # Errors
1030    /// The file could not be made.
1031    pub fn spill(&self) -> std::io::Result<Option<Box<dyn SpillFile>>> {
1032        self.backend.spill()
1033    }
1034
1035    /// This store, declared as one workspace's ([`Self::workspace_scoped`]): for a host that
1036    /// keeps a store for one workspace alone, so everything in it is that workspace's (a
1037    /// test's profile, one workspace's headless drive).
1038    #[must_use]
1039    pub fn for_one_workspace(self) -> Self {
1040        Self {
1041            backend: Arc::new(OneWorkspace(self.backend)),
1042            seals: self.seals,
1043        }
1044    }
1045
1046    /// Content in memory, as one workspace's store
1047    /// ([`Self::for_one_workspace`]): for tests of what a
1048    /// caller may name by reference.
1049    pub fn memory_in_workspace() -> Self {
1050        Self::memory().for_one_workspace()
1051    }
1052
1053    /// Remove every item not named in `live`, references or addresses; see
1054    /// [`ContentBackend::collect_unreferenced`].
1055    ///
1056    /// # Errors
1057    /// See [`ContentBackend::collect_unreferenced`].
1058    pub fn collect_unreferenced(&self, live: &BTreeSet<String>) -> Result<Collected, ContentError> {
1059        let addresses = live.iter().map(|reference| address_of(reference)).collect();
1060        self.backend.collect_unreferenced(&addresses)
1061    }
1062
1063    /// Remove the item `reference` names ([`ContentBackend::release`]).
1064    ///
1065    /// # Errors
1066    /// As [`ContentBackend::release`].
1067    pub fn release(&self, reference: &str) -> Result<Collected, ContentError> {
1068        self.backend.release(&address_of(reference))
1069    }
1070}
1071
1072/// Read access to content by address, for code that turns documents into something else (an
1073/// exporter embedding images, a renderer) without doing I/O of its own.
1074pub trait ContentSource {
1075    /// The bytes at `hash`, if this source has them.
1076    fn content(&self, hash: &str) -> Option<Cow<'_, [u8]>>;
1077}
1078
1079impl ContentSource for ContentStore {
1080    fn content(&self, hash: &str) -> Option<Cow<'_, [u8]>> {
1081        self.read(hash).map(Cow::Owned)
1082    }
1083}
1084
1085impl ContentSource for BTreeMap<String, Vec<u8>> {
1086    fn content(&self, hash: &str) -> Option<Cow<'_, [u8]>> {
1087        self.get(hash).map(|bytes| Cow::Borrowed(bytes.as_slice()))
1088    }
1089}
1090
1091impl<T: ContentSource + ?Sized> ContentSource for &T {
1092    fn content(&self, hash: &str) -> Option<Cow<'_, [u8]>> {
1093        (**self).content(hash)
1094    }
1095}
1096
1097impl<A: ContentSource, B: ContentSource> ContentSource for (A, B) {
1098    fn content(&self, hash: &str) -> Option<Cow<'_, [u8]>> {
1099        self.0.content(hash).or_else(|| self.1.content(hash))
1100    }
1101}
1102
1103#[derive(Debug, Clone, Copy, Default)]
1104pub struct NoContent;
1105
1106impl ContentSource for NoContent {
1107    fn content(&self, _hash: &str) -> Option<Cow<'_, [u8]>> {
1108        None
1109    }
1110}
1111
1112/// Binary inputs found by pure code — the images an importer met — keyed by address, for the
1113/// caller to persist ([`ContentStore::put_inputs`]) before the document naming them is kept.
1114#[derive(Debug, Clone, Default, PartialEq, Eq)]
1115pub struct ContentInputs {
1116    entries: BTreeMap<String, Vec<u8>>,
1117}
1118
1119impl ContentInputs {
1120    pub fn new() -> Self {
1121        Self::default()
1122    }
1123
1124    /// Take `bytes` as an input, returning their address. The same bytes added twice are kept once.
1125    pub fn add(&mut self, bytes: impl Into<Vec<u8>>) -> String {
1126        let bytes = bytes.into();
1127        let hash = hash_bytes(&bytes);
1128        self.entries.entry(hash.clone()).or_insert(bytes);
1129        hash
1130    }
1131
1132    pub fn get(&self, hash: &str) -> Option<&[u8]> {
1133        self.entries.get(hash).map(Vec::as_slice)
1134    }
1135
1136    pub fn len(&self) -> usize {
1137        self.entries.len()
1138    }
1139
1140    pub fn is_empty(&self) -> bool {
1141        self.entries.is_empty()
1142    }
1143
1144    pub fn iter(&self) -> impl Iterator<Item = (&str, &[u8])> {
1145        self.entries
1146            .iter()
1147            .map(|(hash, bytes)| (hash.as_str(), bytes.as_slice()))
1148    }
1149
1150    pub fn append(&mut self, other: &mut Self) {
1151        self.entries.append(&mut other.entries);
1152    }
1153}
1154
1155impl IntoIterator for ContentInputs {
1156    type Item = (String, Vec<u8>);
1157    type IntoIter = std::collections::btree_map::IntoIter<String, Vec<u8>>;
1158
1159    fn into_iter(self) -> Self::IntoIter {
1160        self.entries.into_iter()
1161    }
1162}
1163
1164impl ContentSource for ContentInputs {
1165    fn content(&self, hash: &str) -> Option<Cow<'_, [u8]>> {
1166        self.get(hash).map(Cow::Borrowed)
1167    }
1168}
1169
1170/// A reader that hashes what passes through and fails at the end if it was not `expected`: what
1171/// a backend wraps a read from storage it does not trust in, so it returns a [`ContentReader`].
1172#[cfg(feature = "dir")]
1173pub struct Verifying<R> {
1174    inner: R,
1175    hasher: blake3::Hasher,
1176    expected: String,
1177    done: bool,
1178}
1179
1180#[cfg(feature = "dir")]
1181impl<R> Verifying<R> {
1182    pub fn new(inner: R, expected: &str) -> Self {
1183        Self {
1184            inner,
1185            hasher: blake3::Hasher::new(),
1186            expected: expected.to_ascii_lowercase(),
1187            done: false,
1188        }
1189    }
1190}
1191
1192#[cfg(feature = "dir")]
1193impl<R: Read> Read for Verifying<R> {
1194    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
1195        if self.done {
1196            return Ok(0);
1197        }
1198        let n = self.inner.read(buf)?;
1199        if n == 0 {
1200            self.done = true;
1201            if self.hasher.finalize().to_hex().as_str() != self.expected {
1202                return Err(std::io::Error::new(
1203                    std::io::ErrorKind::InvalidData,
1204                    "content does not match its address",
1205                ));
1206            }
1207            return Ok(0);
1208        }
1209        self.hasher.update(buf.get(..n).unwrap_or_default());
1210        Ok(n)
1211    }
1212}
1213
1214#[cfg(test)]
1215#[cfg(feature = "dir")]
1216mod tests;