1use 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#[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
101static SPILL_COUNTER: AtomicU64 = AtomicU64::new(0);
102
103struct 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 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
145struct 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
185struct 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
194pub fn verify(hash: &str, bytes: &[u8]) -> bool {
196 hash_bytes(bytes) == hash
197}
198
199#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
204pub enum ContentState {
205 Resolved,
206 Pending,
207 Waiting,
210 Unavailable,
213}
214
215#[derive(Debug, Clone, Copy, PartialEq, Eq)]
218pub struct ContentLimits {
219 pub max_item_bytes: usize,
220 pub max_total_bytes: usize,
222 pub max_entries: usize,
224 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#[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
284pub type ContentReader = Box<dyn Read + Send>;
288
289pub trait ContentBackend: Send + Sync {
293 fn put(&self, reader: &mut dyn Read, mime: &str) -> Result<Stored, ContentError>;
299
300 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 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 fn size(&self, hash: &str) -> Option<u64> {
334 let _ = hash;
335 None
336 }
337
338 fn state(&self, hash: &str) -> ContentState {
341 if self.has(hash) {
342 ContentState::Resolved
343 } else {
344 ContentState::Unavailable
345 }
346 }
347
348 fn collect_unreferenced(&self, live: &BTreeSet<String>) -> Result<Collected, ContentError> {
355 let _ = live;
356 Err(ContentError::CollectionUnsupported)
357 }
358
359 fn release(&self, hash: &str) -> Result<Collected, ContentError> {
368 let _ = hash;
369 Err(ContentError::CollectionUnsupported)
370 }
371
372 fn shared(&self) -> bool {
377 false
378 }
379
380 fn workspace_scoped(&self) -> bool {
385 false
386 }
387
388 fn content_secret(&self) -> Option<tilo_seal::SymmetricKey> {
401 None
402 }
403
404 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 fn max_item_bytes(&self) -> usize {
421 ContentLimits::default().max_item_bytes
422 }
423
424 fn scratch_dir(&self) -> Option<PathBuf> {
428 None
429 }
430}
431
432struct 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#[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 #[must_use]
525 pub fn sealing(self) -> Self {
526 Self {
527 seals: true,
528 ..self
529 }
530 }
531
532 #[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 #[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 #[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 #[must_use]
617 pub const fn seals(&self) -> bool {
618 self.seals
619 }
620
621 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 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 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 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 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 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 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 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 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 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 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 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 let mut missing = false;
832 for (_, part) in &list.parts {
833 if !self.has(part) {
834 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 Err(error) => Some(Box::new(Failed(Some(error)))),
854 }
855 }
856
857 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 #[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 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 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 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 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 pub fn shared(&self) -> bool {
1039 self.backend.shared()
1040 }
1041
1042 pub fn workspace_scoped(&self) -> bool {
1045 self.backend.workspace_scoped()
1046 }
1047
1048 pub fn scratch_dir(&self) -> Option<PathBuf> {
1051 self.backend.scratch_dir()
1052 }
1053
1054 #[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 pub fn memory_in_workspace() -> Self {
1069 Self::memory().for_one_workspace()
1070 }
1071
1072 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 pub fn release(&self, reference: &str) -> Result<Collected, ContentError> {
1087 self.backend.release(&address_of(reference))
1088 }
1089}
1090
1091pub trait ContentSource {
1094 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#[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 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#[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;