| 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 | /// Stores `payload` like [`Objects::put`], with a hint: the object is |
| 26 | /// probably close to `similar`, such as the previous version of the same |
| 27 | /// file or directory. A store may keep it as a difference from that |
| 28 | /// object; the id, and what [`Objects::get`] returns, are the same |
| 29 | /// either way. A hint that names an object that is not here is ignored. |
| 30 | /// |
| 31 | /// The default ignores the hint and calls [`Objects::put`]. |
| 32 | fn put_similar( |
| 33 | &self, |
| 34 | kind: Kind, |
| 35 | payload: &[u8], |
| 36 | similar: &ObjectId, |
| 37 | ) -> Result<ObjectId, Self::Error> { |
| 38 | let _ = similar; |
| 39 | self.put(kind, payload) |
| 40 | } |
| 41 | |
| 42 | /// Whether the object is here. |
| 43 | fn contains(&self, id: &ObjectId) -> Result<bool, Self::Error> { |
| 44 | Ok(self.get(id)?.is_some()) |
| 45 | } |
| 46 | |
| 47 | /// The kind and payload size of an object, or `None` if it is not here. |
| 48 | /// Stores that know the size without reading the payload should override |
| 49 | /// this, so that checks on large files stay cheap. |
| 50 | fn stat(&self, id: &ObjectId) -> Result<Option<(Kind, u64)>, Self::Error> { |
| 51 | Ok(self |
| 52 | .get(id)? |
| 53 | .map(|(kind, payload)| (kind, payload.len() as u64))) |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | impl<T: Objects + ?Sized> Objects for &T { |
| 58 | type Error = T::Error; |
| 59 | |
| 60 | fn get(&self, id: &ObjectId) -> Result<Option<(Kind, Vec<u8>)>, Self::Error> { |
| 61 | (**self).get(id) |
| 62 | } |
| 63 | |
| 64 | fn put(&self, kind: Kind, payload: &[u8]) -> Result<ObjectId, Self::Error> { |
| 65 | (**self).put(kind, payload) |
| 66 | } |
| 67 | |
| 68 | fn put_similar( |
| 69 | &self, |
| 70 | kind: Kind, |
| 71 | payload: &[u8], |
| 72 | similar: &ObjectId, |
| 73 | ) -> Result<ObjectId, Self::Error> { |
| 74 | (**self).put_similar(kind, payload, similar) |
| 75 | } |
| 76 | |
| 77 | fn contains(&self, id: &ObjectId) -> Result<bool, Self::Error> { |
| 78 | (**self).contains(id) |
| 79 | } |
| 80 | |
| 81 | fn stat(&self, id: &ObjectId) -> Result<Option<(Kind, u64)>, Self::Error> { |
| 82 | (**self).stat(id) |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | /// Objects kept in memory, for tests and short-lived work. |
| 87 | #[derive(Debug, Default)] |
| 88 | pub struct MemoryObjects { |
| 89 | map: Mutex<HashMap<ObjectId, (Kind, Vec<u8>)>>, |
| 90 | } |
| 91 | |
| 92 | impl MemoryObjects { |
| 93 | /// An empty set of objects. |
| 94 | pub fn new() -> Self { |
| 95 | Self::default() |
| 96 | } |
| 97 | |
| 98 | /// Number of objects held. |
| 99 | pub fn len(&self) -> usize { |
| 100 | self.lock().len() |
| 101 | } |
| 102 | |
| 103 | /// Whether no object is held. |
| 104 | pub fn is_empty(&self) -> bool { |
| 105 | self.len() == 0 |
| 106 | } |
| 107 | |
| 108 | /// The ids of every object held, in no particular order. |
| 109 | pub fn ids(&self) -> Vec<ObjectId> { |
| 110 | self.lock().keys().copied().collect() |
| 111 | } |
| 112 | |
| 113 | fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<ObjectId, (Kind, Vec<u8>)>> { |
| 114 | // A panic while holding the lock cannot leave the map half-written: |
| 115 | // every operation is a single insert or lookup. |
| 116 | self.map |
| 117 | .lock() |
| 118 | .unwrap_or_else(|poisoned| poisoned.into_inner()) |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | impl Objects for MemoryObjects { |
| 123 | type Error = Infallible; |
| 124 | |
| 125 | fn get(&self, id: &ObjectId) -> Result<Option<(Kind, Vec<u8>)>, Self::Error> { |
| 126 | Ok(self.lock().get(id).cloned()) |
| 127 | } |
| 128 | |
| 129 | fn put(&self, kind: Kind, payload: &[u8]) -> Result<ObjectId, Self::Error> { |
| 130 | let id = ObjectId::hash(kind, payload); |
| 131 | self.lock() |
| 132 | .entry(id) |
| 133 | .or_insert_with(|| (kind, payload.to_vec())); |
| 134 | Ok(id) |
| 135 | } |
| 136 | |
| 137 | fn contains(&self, id: &ObjectId) -> Result<bool, Self::Error> { |
| 138 | Ok(self.lock().contains_key(id)) |
| 139 | } |
| 140 | |
| 141 | fn stat(&self, id: &ObjectId) -> Result<Option<(Kind, u64)>, Self::Error> { |
| 142 | Ok(self |
| 143 | .lock() |
| 144 | .get(id) |
| 145 | .map(|(kind, payload)| (*kind, payload.len() as u64))) |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | #[cfg(test)] |
| 150 | mod tests { |
| 151 | use super::*; |
| 152 | |
| 153 | #[test] |
| 154 | fn memory_objects() { |
| 155 | let objects = MemoryObjects::new(); |
| 156 | assert!(objects.is_empty()); |
| 157 | let id = objects.put(Kind::Blob, b"hello\n").unwrap(); |
| 158 | assert_eq!(id, ObjectId::hash(Kind::Blob, b"hello\n")); |
| 159 | assert_eq!(objects.put(Kind::Blob, b"hello\n").unwrap(), id); |
| 160 | assert_eq!(objects.len(), 1); |
| 161 | assert_eq!( |
| 162 | objects.get(&id).unwrap(), |
| 163 | Some((Kind::Blob, b"hello\n".to_vec())) |
| 164 | ); |
| 165 | assert!(objects.contains(&id).unwrap()); |
| 166 | assert_eq!(objects.stat(&id).unwrap(), Some((Kind::Blob, 6))); |
| 167 | let other = ObjectId::hash(Kind::Tree, b"hello\n"); |
| 168 | assert_eq!(objects.get(&other).unwrap(), None); |
| 169 | // Through a reference, too. |
| 170 | let by_ref: &MemoryObjects = &objects; |
| 171 | assert!(Objects::contains(&by_ref, &id).unwrap()); |
| 172 | // A hint changes nothing in memory, even one naming an absent object. |
| 173 | let next = Objects::put_similar(&by_ref, Kind::Blob, b"hello!\n", &id).unwrap(); |
| 174 | assert_eq!(next, ObjectId::hash(Kind::Blob, b"hello!\n")); |
| 175 | assert_eq!( |
| 176 | objects.put_similar(Kind::Tree, b"x", &other).unwrap(), |
| 177 | ObjectId::hash(Kind::Tree, b"x") |
| 178 | ); |
| 179 | assert_eq!(objects.len(), 3); |
| 180 | } |
| 181 | } |