| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! Access to stored objects, independent of where they live: the local store, |
| 5 | //! a cache, a remote server, or memory. |
| 6 | |
| 7 | use core::convert::Infallible; |
| 8 | use std::collections::HashMap; |
| 9 | use std::sync::Mutex; |
| 10 | |
| 11 | use crate::id::{Kind, ObjectId}; |
| 12 | |
| 13 | /// A place objects can be read from and written to. |
| 14 | pub trait Objects { |
| 15 | /// Why an access failed: I/O, corruption, a lost connection. |
| 16 | type Error: std::error::Error + Send + Sync + 'static; |
| 17 | |
| 18 | /// The kind and payload of an object, or `None` if it is not here. |
| 19 | fn get(&self, id: &ObjectId) -> Result<Option<(Kind, Vec<u8>)>, Self::Error>; |
| 20 | |
| 21 | /// Stores `payload` as an object of `kind` and returns its id. Storing an |
| 22 | /// object that is already present does nothing. |
| 23 | fn put(&self, kind: Kind, payload: &[u8]) -> Result<ObjectId, Self::Error>; |
| 24 | |
| 25 | /// Whether the object is here. |
| 26 | fn contains(&self, id: &ObjectId) -> Result<bool, Self::Error> { |
| 27 | Ok(self.get(id)?.is_some()) |
| 28 | } |
| 29 | |
| 30 | /// The kind and payload size of an object, or `None` if it is not here. |
| 31 | /// Stores that know the size without reading the payload should override |
| 32 | /// this, so that checks on large files stay cheap. |
| 33 | fn stat(&self, id: &ObjectId) -> Result<Option<(Kind, u64)>, Self::Error> { |
| 34 | Ok(self |
| 35 | .get(id)? |
| 36 | .map(|(kind, payload)| (kind, payload.len() as u64))) |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | impl<T: Objects + ?Sized> Objects for &T { |
| 41 | type Error = T::Error; |
| 42 | |
| 43 | fn get(&self, id: &ObjectId) -> Result<Option<(Kind, Vec<u8>)>, Self::Error> { |
| 44 | (**self).get(id) |
| 45 | } |
| 46 | |
| 47 | fn put(&self, kind: Kind, payload: &[u8]) -> Result<ObjectId, Self::Error> { |
| 48 | (**self).put(kind, payload) |
| 49 | } |
| 50 | |
| 51 | fn contains(&self, id: &ObjectId) -> Result<bool, Self::Error> { |
| 52 | (**self).contains(id) |
| 53 | } |
| 54 | |
| 55 | fn stat(&self, id: &ObjectId) -> Result<Option<(Kind, u64)>, Self::Error> { |
| 56 | (**self).stat(id) |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | /// Objects kept in memory, for tests and short-lived work. |
| 61 | #[derive(Debug, Default)] |
| 62 | pub struct MemoryObjects { |
| 63 | map: Mutex<HashMap<ObjectId, (Kind, Vec<u8>)>>, |
| 64 | } |
| 65 | |
| 66 | impl MemoryObjects { |
| 67 | /// An empty set of objects. |
| 68 | pub fn new() -> Self { |
| 69 | Self::default() |
| 70 | } |
| 71 | |
| 72 | /// Number of objects held. |
| 73 | pub fn len(&self) -> usize { |
| 74 | self.lock().len() |
| 75 | } |
| 76 | |
| 77 | /// Whether no object is held. |
| 78 | pub fn is_empty(&self) -> bool { |
| 79 | self.len() == 0 |
| 80 | } |
| 81 | |
| 82 | /// The ids of every object held, in no particular order. |
| 83 | pub fn ids(&self) -> Vec<ObjectId> { |
| 84 | self.lock().keys().copied().collect() |
| 85 | } |
| 86 | |
| 87 | fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<ObjectId, (Kind, Vec<u8>)>> { |
| 88 | // A panic while holding the lock cannot leave the map half-written: |
| 89 | // every operation is a single insert or lookup. |
| 90 | self.map |
| 91 | .lock() |
| 92 | .unwrap_or_else(|poisoned| poisoned.into_inner()) |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | impl Objects for MemoryObjects { |
| 97 | type Error = Infallible; |
| 98 | |
| 99 | fn get(&self, id: &ObjectId) -> Result<Option<(Kind, Vec<u8>)>, Self::Error> { |
| 100 | Ok(self.lock().get(id).cloned()) |
| 101 | } |
| 102 | |
| 103 | fn put(&self, kind: Kind, payload: &[u8]) -> Result<ObjectId, Self::Error> { |
| 104 | let id = ObjectId::hash(kind, payload); |
| 105 | self.lock() |
| 106 | .entry(id) |
| 107 | .or_insert_with(|| (kind, payload.to_vec())); |
| 108 | Ok(id) |
| 109 | } |
| 110 | |
| 111 | fn contains(&self, id: &ObjectId) -> Result<bool, Self::Error> { |
| 112 | Ok(self.lock().contains_key(id)) |
| 113 | } |
| 114 | |
| 115 | fn stat(&self, id: &ObjectId) -> Result<Option<(Kind, u64)>, Self::Error> { |
| 116 | Ok(self |
| 117 | .lock() |
| 118 | .get(id) |
| 119 | .map(|(kind, payload)| (*kind, payload.len() as u64))) |
| 120 | } |
| 121 | } |
| 122 | |
| 123 | #[cfg(test)] |
| 124 | mod tests { |
| 125 | use super::*; |
| 126 | |
| 127 | #[test] |
| 128 | fn memory_objects() { |
| 129 | let objects = MemoryObjects::new(); |
| 130 | assert!(objects.is_empty()); |
| 131 | let id = objects.put(Kind::Blob, b"hello\n").unwrap(); |
| 132 | assert_eq!(id, ObjectId::hash(Kind::Blob, b"hello\n")); |
| 133 | assert_eq!(objects.put(Kind::Blob, b"hello\n").unwrap(), id); |
| 134 | assert_eq!(objects.len(), 1); |
| 135 | assert_eq!( |
| 136 | objects.get(&id).unwrap(), |
| 137 | Some((Kind::Blob, b"hello\n".to_vec())) |
| 138 | ); |
| 139 | assert!(objects.contains(&id).unwrap()); |
| 140 | assert_eq!(objects.stat(&id).unwrap(), Some((Kind::Blob, 6))); |
| 141 | let other = ObjectId::hash(Kind::Tree, b"hello\n"); |
| 142 | assert_eq!(objects.get(&other).unwrap(), None); |
| 143 | // Through a reference, too. |
| 144 | let by_ref: &MemoryObjects = &objects; |
| 145 | assert!(Objects::contains(&by_ref, &id).unwrap()); |
| 146 | } |
| 147 | } |