1use 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#[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
50pub const SHARED_STORE_ENV: &str = "TILO_BLOB_STORE";
53
54const SEALED_MIME: &str = "application/octet-stream";
56
57fn address_of(reference: &str) -> String {
59 content_address(reference).unwrap_or_else(|| reference.to_owned())
60}
61
62pub fn hash_bytes(bytes: &[u8]) -> String {
64 blake3::hash(bytes).to_hex().to_string()
65}
66
67pub 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
80fn 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#[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
101pub trait SpillFile: Read + Write + Seek + Send {}
105
106impl<T: Read + Write + Seek + Send> SpillFile for T {}
107
108struct Gathered {
113 kept: Vec<u8>,
114 spill: Option<Box<dyn SpillFile>>,
115 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 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
161struct 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
170pub fn verify(hash: &str, bytes: &[u8]) -> bool {
172 hash_bytes(bytes) == hash
173}
174
175#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
180pub enum ContentState {
181 Resolved,
182 Pending,
183 Waiting,
186 Unavailable,
189}
190
191#[derive(Debug, Clone, Copy, PartialEq, Eq)]
194pub struct ContentLimits {
195 pub max_item_bytes: usize,
196 pub max_total_bytes: usize,
198 pub max_entries: usize,
200 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#[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
260pub type ContentReader = Box<dyn Read + Send>;
264
265pub trait ContentBackend: Send + Sync {
269 fn put(&self, reader: &mut dyn Read, mime: &str) -> Result<Stored, ContentError>;
275
276 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 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 fn size(&self, hash: &str) -> Option<u64> {
310 let _ = hash;
311 None
312 }
313
314 fn state(&self, hash: &str) -> ContentState {
317 if self.has(hash) {
318 ContentState::Resolved
319 } else {
320 ContentState::Unavailable
321 }
322 }
323
324 fn collect_unreferenced(&self, live: &BTreeSet<String>) -> Result<Collected, ContentError> {
331 let _ = live;
332 Err(ContentError::CollectionUnsupported)
333 }
334
335 fn release(&self, hash: &str) -> Result<Collected, ContentError> {
344 let _ = hash;
345 Err(ContentError::CollectionUnsupported)
346 }
347
348 fn shared(&self) -> bool {
353 false
354 }
355
356 fn workspace_scoped(&self) -> bool {
361 false
362 }
363
364 fn content_secret(&self) -> Option<tilo_seal::SymmetricKey> {
377 None
378 }
379
380 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 fn max_item_bytes(&self) -> usize {
397 ContentLimits::default().max_item_bytes
398 }
399
400 fn spill(&self) -> std::io::Result<Option<Box<dyn SpillFile>>> {
407 Ok(None)
408 }
409}
410
411struct 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#[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 #[must_use]
504 pub fn sealing(self) -> Self {
505 Self {
506 seals: true,
507 ..self
508 }
509 }
510
511 #[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 #[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 #[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 #[must_use]
596 pub const fn seals(&self) -> bool {
597 self.seals
598 }
599
600 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 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 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 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 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 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 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 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 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 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 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 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 let mut missing = false;
810 for (_, part) in &list.parts {
811 if !self.has(part) {
812 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 Err(error) => Some(Box::new(Failed(Some(error)))),
832 }
833 }
834
835 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 #[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 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 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 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 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 pub fn shared(&self) -> bool {
1017 self.backend.shared()
1018 }
1019
1020 pub fn workspace_scoped(&self) -> bool {
1023 self.backend.workspace_scoped()
1024 }
1025
1026 pub fn spill(&self) -> std::io::Result<Option<Box<dyn SpillFile>>> {
1032 self.backend.spill()
1033 }
1034
1035 #[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 pub fn memory_in_workspace() -> Self {
1050 Self::memory().for_one_workspace()
1051 }
1052
1053 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 pub fn release(&self, reference: &str) -> Result<Collected, ContentError> {
1068 self.backend.release(&address_of(reference))
1069 }
1070}
1071
1072pub trait ContentSource {
1075 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#[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 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#[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;