| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! Typed access to stored objects: blobs, trees and changesets. |
| 5 | |
| 6 | use std::borrow::Cow; |
| 7 | use std::collections::HashMap; |
| 8 | use std::rc::Rc; |
| 9 | |
| 10 | use braid_format::changeset::{MAX_INLINE_CHANGES_BYTES, decode_change_list}; |
| 11 | use braid_format::{ |
| 12 | Change, Changes, Changeset, Entry, EntryKind, Kind, Node, ObjectId, Objects, TreeError, |
| 13 | build_directory, read_directory, |
| 14 | }; |
| 15 | |
| 16 | use crate::error::{Error, store_error}; |
| 17 | use crate::path::check_depth; |
| 18 | |
| 19 | /// Id of the tree with no entries: the root of an empty repository, and the |
| 20 | /// base of a changeset without parents. Part of format v1. |
| 21 | pub const EMPTY_TREE: ObjectId = ObjectId::from_bytes([ |
| 22 | 0x31, 0x36, 0xb0, 0xf1, 0x85, 0x62, 0xee, 0x73, 0xb8, 0x40, 0xea, 0x34, 0x8c, 0x54, 0xae, 0x3c, |
| 23 | 0x7e, 0x97, 0xe4, 0xcc, 0x3e, 0x54, 0x7e, 0xa9, 0xdd, 0x03, 0xfa, 0x1c, 0xd8, 0xb3, 0x84, 0xcf, |
| 24 | ]); |
| 25 | |
| 26 | /// The encoding of the empty tree. |
| 27 | pub(crate) fn empty_tree_node() -> Vec<u8> { |
| 28 | Node::Flat(Vec::new()).encode() |
| 29 | } |
| 30 | |
| 31 | /// Reads an object that must be present and of `kind`, and checks that its |
| 32 | /// bytes hash to its id. |
| 33 | pub fn read_object<O: Objects>(objects: &O, id: ObjectId, kind: Kind) -> Result<Vec<u8>, Error> { |
| 34 | match objects.get(&id).map_err(store_error)? { |
| 35 | None => Err(Error::Missing { id, kind }), |
| 36 | Some((found, _)) if found != kind => Err(Error::WrongKind { |
| 37 | id, |
| 38 | expected: kind, |
| 39 | found, |
| 40 | }), |
| 41 | Some((_, bytes)) if ObjectId::hash(kind, &bytes) != id => Err(Error::Corrupt { id }), |
| 42 | Some((_, bytes)) => Ok(bytes), |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | /// The size of an object that must be stored as `kind`, from |
| 47 | /// [`Objects::stat`]: the content is not read, if the store can avoid it. |
| 48 | pub fn stat_object<O: Objects>(objects: &O, id: ObjectId, kind: Kind) -> Result<u64, Error> { |
| 49 | match objects.stat(&id).map_err(store_error)? { |
| 50 | None => Err(Error::Missing { id, kind }), |
| 51 | Some((found, size)) if found == kind => Ok(size), |
| 52 | Some((found, _)) => Err(Error::WrongKind { |
| 53 | id, |
| 54 | expected: kind, |
| 55 | found, |
| 56 | }), |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | /// Reads the content of a blob. |
| 61 | pub fn read_blob<O: Objects>(objects: &O, id: ObjectId) -> Result<Vec<u8>, Error> { |
| 62 | read_object(objects, id, Kind::Blob) |
| 63 | } |
| 64 | |
| 65 | /// Reads every entry of a directory, flat or split, in name order. |
| 66 | /// |
| 67 | /// A split directory is checked to be exactly the canonical split of its |
| 68 | /// entries. The empty tree is known without reading it. |
| 69 | pub fn read_tree<O: Objects>(objects: &O, id: ObjectId) -> Result<Vec<Entry>, Error> { |
| 70 | if id == EMPTY_TREE { |
| 71 | return Ok(Vec::new()); |
| 72 | } |
| 73 | // `read_directory` sees a node it cannot fetch as missing; remember why. |
| 74 | let mut failure = None; |
| 75 | let read = read_directory(id, |node| match objects.get(node) { |
| 76 | Ok(Some((Kind::Tree, bytes))) => Some(bytes), |
| 77 | Ok(Some((found, _))) => { |
| 78 | failure.get_or_insert(Error::WrongKind { |
| 79 | id: *node, |
| 80 | expected: Kind::Tree, |
| 81 | found, |
| 82 | }); |
| 83 | None |
| 84 | } |
| 85 | Ok(None) => None, |
| 86 | Err(error) => { |
| 87 | failure.get_or_insert(store_error(error)); |
| 88 | None |
| 89 | } |
| 90 | }); |
| 91 | read.map_err(|error| match (failure, error) { |
| 92 | (Some(failure), _) => failure, |
| 93 | (None, TreeError::MissingNode(node)) => Error::Missing { |
| 94 | id: node, |
| 95 | kind: Kind::Tree, |
| 96 | }, |
| 97 | (None, error) => Error::Tree { id, error }, |
| 98 | }) |
| 99 | } |
| 100 | |
| 101 | /// Stores a directory: builds its canonical nodes from `entries`, in any |
| 102 | /// order, stores every node, and returns the directory's id. |
| 103 | pub fn write_tree<O: Objects>(objects: &O, entries: Vec<Entry>) -> Result<ObjectId, Error> { |
| 104 | let directory = build_directory(entries).map_err(Error::Entries)?; |
| 105 | for (_, bytes) in &directory.nodes { |
| 106 | objects.put(Kind::Tree, bytes).map_err(store_error)?; |
| 107 | } |
| 108 | Ok(directory.root()) |
| 109 | } |
| 110 | |
| 111 | /// Reads and decodes a changeset. Its change list may be external: see |
| 112 | /// [`read_changes`]. |
| 113 | pub fn read_changeset<O: Objects>(objects: &O, id: ObjectId) -> Result<Changeset, Error> { |
| 114 | let bytes = read_object(objects, id, Kind::Changeset)?; |
| 115 | Changeset::decode(&bytes).map_err(|error| Error::Changeset { id, error }) |
| 116 | } |
| 117 | |
| 118 | /// The change list of `changeset`, whose id is `id`: borrowed when it is |
| 119 | /// inline, fetched and decoded when it is in its own blob. |
| 120 | /// |
| 121 | /// An external list must hold as many changes as the changeset declares, and |
| 122 | /// must be too long to have been stored inline. |
| 123 | pub fn read_changes<'c, O: Objects>( |
| 124 | objects: &O, |
| 125 | id: ObjectId, |
| 126 | changeset: &'c Changeset, |
| 127 | ) -> Result<Cow<'c, [Change]>, Error> { |
| 128 | match &changeset.changes { |
| 129 | Changes::Inline(changes) => Ok(Cow::Borrowed(changes)), |
| 130 | Changes::External { list, count } => { |
| 131 | let bytes = read_blob(objects, *list)?; |
| 132 | if bytes.len() <= MAX_INLINE_CHANGES_BYTES { |
| 133 | return Err(Error::ExternalListFitsInline { |
| 134 | changeset: id, |
| 135 | len: bytes.len(), |
| 136 | }); |
| 137 | } |
| 138 | let changes = |
| 139 | decode_change_list(&bytes).map_err(|error| Error::Changeset { id, error })?; |
| 140 | if changes.len() as u64 != *count { |
| 141 | return Err(Error::ChangeCount { |
| 142 | changeset: id, |
| 143 | declared: *count, |
| 144 | found: changes.len(), |
| 145 | }); |
| 146 | } |
| 147 | Ok(Cow::Owned(changes)) |
| 148 | } |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | /// The entry at `path` in the tree `root`, or `None` if there is none (or a |
| 153 | /// prefix of `path` is not a directory). A path deeper than |
| 154 | /// [`MAX_PATH_DEPTH`](crate::MAX_PATH_DEPTH) is an error. |
| 155 | pub fn entry_at<O: Objects>( |
| 156 | objects: &O, |
| 157 | root: ObjectId, |
| 158 | path: &[u8], |
| 159 | ) -> Result<Option<EntryKind>, Error> { |
| 160 | check_depth(path)?; |
| 161 | Ok(Trees::new(objects).find(root, path)?.into_entry()) |
| 162 | } |
| 163 | |
| 164 | /// What is at a path of a tree. |
| 165 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 166 | pub(crate) enum Found { |
| 167 | /// This entry. |
| 168 | Entry(EntryKind), |
| 169 | /// Nothing, and every prefix of the path that exists is a directory. |
| 170 | Absent, |
| 171 | /// Nothing, because the prefix of this many bytes is not a directory. |
| 172 | Blocked(usize), |
| 173 | } |
| 174 | |
| 175 | impl Found { |
| 176 | pub(crate) fn into_entry(self) -> Option<EntryKind> { |
| 177 | match self { |
| 178 | Found::Entry(kind) => Some(kind), |
| 179 | Found::Absent | Found::Blocked(_) => None, |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | pub(crate) fn entry(&self) -> Option<&EntryKind> { |
| 184 | match self { |
| 185 | Found::Entry(kind) => Some(kind), |
| 186 | Found::Absent | Found::Blocked(_) => None, |
| 187 | } |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | /// The entry named `name` in a directory's sorted entries. |
| 192 | pub(crate) fn lookup<'e>(entries: &'e [Entry], name: &[u8]) -> Option<&'e EntryKind> { |
| 193 | entries |
| 194 | .binary_search_by(|entry| entry.name.as_slice().cmp(name)) |
| 195 | .ok() |
| 196 | .map(|index| &entries[index].kind) |
| 197 | } |
| 198 | |
| 199 | /// Directories read during one operation, by id, so that each one is fetched |
| 200 | /// and checked once. |
| 201 | pub(crate) struct Trees<'o, O> { |
| 202 | objects: &'o O, |
| 203 | directories: HashMap<ObjectId, Rc<[Entry]>>, |
| 204 | } |
| 205 | |
| 206 | impl<'o, O: Objects> Trees<'o, O> { |
| 207 | pub(crate) fn new(objects: &'o O) -> Self { |
| 208 | Trees { |
| 209 | objects, |
| 210 | directories: HashMap::new(), |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | pub(crate) fn objects(&self) -> &'o O { |
| 215 | self.objects |
| 216 | } |
| 217 | |
| 218 | /// The entries of a directory, in name order. |
| 219 | pub(crate) fn read(&mut self, id: ObjectId) -> Result<Rc<[Entry]>, Error> { |
| 220 | if let Some(entries) = self.directories.get(&id) { |
| 221 | return Ok(Rc::clone(entries)); |
| 222 | } |
| 223 | let entries: Rc<[Entry]> = read_tree(self.objects, id)?.into(); |
| 224 | self.directories.insert(id, Rc::clone(&entries)); |
| 225 | Ok(entries) |
| 226 | } |
| 227 | |
| 228 | /// The entries of a directory that may not exist. |
| 229 | pub(crate) fn read_or_empty(&mut self, id: Option<ObjectId>) -> Result<Rc<[Entry]>, Error> { |
| 230 | match id { |
| 231 | Some(id) => self.read(id), |
| 232 | None => Ok(Vec::new().into()), |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | /// What is at `path` in the tree `root`. |
| 237 | pub(crate) fn find(&mut self, root: ObjectId, path: &[u8]) -> Result<Found, Error> { |
| 238 | let mut dir = root; |
| 239 | let mut start = 0; |
| 240 | loop { |
| 241 | let slash = path[start..].iter().position(|byte| *byte == b'/'); |
| 242 | let end = slash.map_or(path.len(), |slash| start + slash); |
| 243 | let entries = self.read(dir)?; |
| 244 | match (lookup(&entries, &path[start..end]), slash) { |
| 245 | (None, _) => return Ok(Found::Absent), |
| 246 | (Some(kind), None) => return Ok(Found::Entry(kind.clone())), |
| 247 | (Some(EntryKind::Tree { tree }), Some(_)) => { |
| 248 | dir = *tree; |
| 249 | start = end + 1; |
| 250 | } |
| 251 | (Some(_), Some(_)) => return Ok(Found::Blocked(end)), |
| 252 | } |
| 253 | } |
| 254 | } |
| 255 | |
| 256 | /// Length of the deepest proper prefix of `path` that is a directory in |
| 257 | /// the tree `root`; 0 when that is the root itself. |
| 258 | pub(crate) fn deepest_directory( |
| 259 | &mut self, |
| 260 | root: ObjectId, |
| 261 | path: &[u8], |
| 262 | ) -> Result<usize, Error> { |
| 263 | let mut dir = root; |
| 264 | let mut deepest = 0; |
| 265 | let mut start = 0; |
| 266 | while let Some(slash) = path[start..].iter().position(|byte| *byte == b'/') { |
| 267 | let end = start + slash; |
| 268 | let entries = self.read(dir)?; |
| 269 | match lookup(&entries, &path[start..end]) { |
| 270 | Some(EntryKind::Tree { tree }) => { |
| 271 | dir = *tree; |
| 272 | deepest = end; |
| 273 | start = end + 1; |
| 274 | } |
| 275 | _ => break, |
| 276 | } |
| 277 | } |
| 278 | Ok(deepest) |
| 279 | } |
| 280 | |
| 281 | /// Length of the shortest proper prefix of `path` that does not exist in |
| 282 | /// the tree `root`, if there is one and every prefix above it is a |
| 283 | /// directory. |
| 284 | pub(crate) fn first_missing_directory( |
| 285 | &mut self, |
| 286 | root: ObjectId, |
| 287 | path: &[u8], |
| 288 | ) -> Result<Option<usize>, Error> { |
| 289 | let mut dir = root; |
| 290 | let mut start = 0; |
| 291 | while let Some(slash) = path[start..].iter().position(|byte| *byte == b'/') { |
| 292 | let end = start + slash; |
| 293 | let entries = self.read(dir)?; |
| 294 | match lookup(&entries, &path[start..end]) { |
| 295 | Some(EntryKind::Tree { tree }) => { |
| 296 | dir = *tree; |
| 297 | start = end + 1; |
| 298 | } |
| 299 | Some(_) => return Ok(None), |
| 300 | None => return Ok(Some(end)), |
| 301 | } |
| 302 | } |
| 303 | Ok(None) |
| 304 | } |
| 305 | } |
| 306 | |
| 307 | #[cfg(test)] |
| 308 | mod tests { |
| 309 | use super::*; |
| 310 | use crate::testing::Repo; |
| 311 | use braid_format::MemoryObjects; |
| 312 | |
| 313 | #[test] |
| 314 | fn empty_tree_id_is_the_format_constant() { |
| 315 | assert_eq!(build_directory(Vec::new()).unwrap().root(), EMPTY_TREE); |
| 316 | assert_eq!(ObjectId::hash(Kind::Tree, &empty_tree_node()), EMPTY_TREE); |
| 317 | assert_eq!( |
| 318 | EMPTY_TREE.to_hex(), |
| 319 | "3136b0f18562ee73b840ea348c54ae3c7e97e4cc3e547ea9dd03fa1cd8b384cf" |
| 320 | ); |
| 321 | // Known without being stored. |
| 322 | assert_eq!(read_tree(&MemoryObjects::new(), EMPTY_TREE).unwrap(), []); |
| 323 | } |
| 324 | |
| 325 | #[test] |
| 326 | fn typed_reads_check_kind_and_presence() { |
| 327 | let objects = MemoryObjects::new(); |
| 328 | let blob = objects.put(Kind::Blob, b"hello\n").unwrap(); |
| 329 | assert_eq!(read_blob(&objects, blob).unwrap(), b"hello\n"); |
| 330 | assert!(matches!( |
| 331 | read_tree(&objects, blob), |
| 332 | Err(Error::WrongKind { |
| 333 | expected: Kind::Tree, |
| 334 | found: Kind::Blob, |
| 335 | .. |
| 336 | }) |
| 337 | )); |
| 338 | assert!(matches!( |
| 339 | read_changeset(&objects, blob), |
| 340 | Err(Error::WrongKind { .. }) |
| 341 | )); |
| 342 | let absent = ObjectId::hash(Kind::Blob, b"absent"); |
| 343 | assert!(matches!( |
| 344 | read_blob(&objects, absent), |
| 345 | Err(Error::Missing { |
| 346 | kind: Kind::Blob, |
| 347 | .. |
| 348 | }) |
| 349 | )); |
| 350 | assert!(matches!( |
| 351 | read_tree(&objects, absent), |
| 352 | Err(Error::Missing { |
| 353 | kind: Kind::Tree, |
| 354 | .. |
| 355 | }) |
| 356 | )); |
| 357 | // A changeset whose bytes do not decode. |
| 358 | let junk = objects.put(Kind::Changeset, b"junk").unwrap(); |
| 359 | assert!(matches!( |
| 360 | read_changeset(&objects, junk), |
| 361 | Err(Error::Changeset { .. }) |
| 362 | )); |
| 363 | } |
| 364 | |
| 365 | #[test] |
| 366 | fn split_directories_are_written_and_read_back() { |
| 367 | let repo = Repo::new(); |
| 368 | let entries: Vec<Entry> = (0..3000) |
| 369 | .map(|i| Entry { |
| 370 | name: format!("f{i:05}").into_bytes(), |
| 371 | kind: repo.file_kind("x"), |
| 372 | }) |
| 373 | .collect(); |
| 374 | let id = write_tree(&repo.objects, entries.clone()).unwrap(); |
| 375 | assert_eq!(read_tree(&repo.objects, id).unwrap(), entries); |
| 376 | assert!( |
| 377 | repo.objects.len() > 3, |
| 378 | "a split directory has several nodes" |
| 379 | ); |
| 380 | let duplicate = vec![entries[0].clone(), entries[0].clone()]; |
| 381 | assert!(matches!( |
| 382 | write_tree(&repo.objects, duplicate), |
| 383 | Err(Error::Entries(TreeError::Unsorted { .. })) |
| 384 | )); |
| 385 | } |
| 386 | |
| 387 | #[test] |
| 388 | fn find_reports_entries_absences_and_blockers() { |
| 389 | let repo = Repo::new(); |
| 390 | let root = repo.tree(&[("a/b/c.txt", "1"), ("f", "2")]); |
| 391 | let mut trees = Trees::new(&repo.objects); |
| 392 | assert!(matches!( |
| 393 | trees.find(root, b"a/b/c.txt").unwrap(), |
| 394 | Found::Entry(EntryKind::File { .. }) |
| 395 | )); |
| 396 | assert!(matches!( |
| 397 | trees.find(root, b"a/b").unwrap(), |
| 398 | Found::Entry(EntryKind::Tree { .. }) |
| 399 | )); |
| 400 | assert_eq!(trees.find(root, b"a/x/y").unwrap(), Found::Absent); |
| 401 | assert_eq!(trees.find(root, b"f/g/h").unwrap(), Found::Blocked(1)); |
| 402 | assert_eq!(trees.deepest_directory(root, b"a/b/new/x").unwrap(), 3); |
| 403 | assert_eq!(trees.deepest_directory(root, b"x/y").unwrap(), 0); |
| 404 | assert_eq!( |
| 405 | trees.first_missing_directory(root, b"a/z/q").unwrap(), |
| 406 | Some(3) |
| 407 | ); |
| 408 | assert_eq!( |
| 409 | trees.first_missing_directory(root, b"a/b/c.txt").unwrap(), |
| 410 | None |
| 411 | ); |
| 412 | assert_eq!(trees.first_missing_directory(root, b"f/g").unwrap(), None); |
| 413 | assert_eq!( |
| 414 | entry_at(&repo.objects, root, b"f").unwrap(), |
| 415 | Some(repo.file_kind("2")) |
| 416 | ); |
| 417 | assert_eq!(entry_at(&repo.objects, root, b"f/g").unwrap(), None); |
| 418 | } |
| 419 | } |