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