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