| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! Trees: one directory, stored as a single flat node or, when it is large, as |
| 5 | //! a balanced structure of nodes whose boundaries depend only on entry names. |
| 6 | //! |
| 7 | //! A directory with up to [`MAX_FLAT_ENTRIES`] entries is always one flat node. |
| 8 | //! A larger one is split into leaves and internal nodes: walking the sorted |
| 9 | //! entries, a node ends after an entry whose name hashes below a threshold |
| 10 | //! (once the node holds at least [`MIN_NODE_ENTRIES`]), or when it reaches |
| 11 | //! [`MAX_NODE_ENTRIES`]. The same set of entries therefore always gives the |
| 12 | //! same nodes and the same root id, whatever order it was edited in, and an |
| 13 | //! edit only touches the nodes on its path. |
| 14 | //! |
| 15 | //! [`build_directory`] makes every node of a directory from all of its |
| 16 | //! entries, and [`read_directory`] reads them all back. [`find_entry`] and |
| 17 | //! [`update_directory`] work one path at a time instead: they read only the |
| 18 | //! nodes on the way to the names they look up or edit, so what they cost |
| 19 | //! follows the number of names and the depth of the directory, not its size. |
| 20 | |
| 21 | use core::cmp::Ordering; |
| 22 | use core::fmt; |
| 23 | use std::collections::HashMap; |
| 24 | use std::rc::Rc; |
| 25 | |
| 26 | use crate::codec::{DecodeError, Reader, put_bytes, put_id, put_uv}; |
| 27 | use crate::id::{Kind, ObjectId}; |
| 28 | use crate::name::{NameError, forbidden_as_symlink, validate_name}; |
| 29 | |
| 30 | /// Format byte of every tree node. |
| 31 | pub const FORMAT: u8 = 1; |
| 32 | |
| 33 | /// A directory with at most this many entries is one flat node. |
| 34 | pub const MAX_FLAT_ENTRIES: usize = 1024; |
| 35 | |
| 36 | /// A node of a split directory only ends on a name boundary once it holds |
| 37 | /// at least this many entries or children. |
| 38 | pub const MIN_NODE_ENTRIES: usize = 32; |
| 39 | |
| 40 | /// A node of a split directory never holds more than this many entries or |
| 41 | /// children. |
| 42 | pub const MAX_NODE_ENTRIES: usize = 512; |
| 43 | |
| 44 | const SPLIT_CONTEXT: &str = "elffuss-braid 2026 tree-split v1"; |
| 45 | |
| 46 | /// One name in 128 ends a node: 2³² / 128. |
| 47 | const SPLIT_THRESHOLD: u32 = 1 << 25; |
| 48 | |
| 49 | const NODE_FLAT: u8 = 0; |
| 50 | const NODE_LEAF: u8 = 1; |
| 51 | const NODE_INTERNAL: u8 = 2; |
| 52 | |
| 53 | /// A git object id, kept for submodules (gitlinks). |
| 54 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] |
| 55 | pub enum GitId { |
| 56 | /// A SHA-1 id. |
| 57 | Sha1([u8; 20]), |
| 58 | /// A SHA-256 id. |
| 59 | Sha256([u8; 32]), |
| 60 | } |
| 61 | |
| 62 | impl GitId { |
| 63 | /// The raw id bytes. |
| 64 | pub fn as_bytes(&self) -> &[u8] { |
| 65 | match self { |
| 66 | GitId::Sha1(bytes) => bytes, |
| 67 | GitId::Sha256(bytes) => bytes, |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | pub(crate) fn encode(&self, out: &mut Vec<u8>) { |
| 72 | match self { |
| 73 | GitId::Sha1(bytes) => { |
| 74 | out.push(1); |
| 75 | out.extend_from_slice(bytes); |
| 76 | } |
| 77 | GitId::Sha256(bytes) => { |
| 78 | out.push(2); |
| 79 | out.extend_from_slice(bytes); |
| 80 | } |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | pub(crate) fn decode(reader: &mut Reader<'_>) -> Result<Self, DecodeError> { |
| 85 | let at = reader.position(); |
| 86 | match reader.u8()? { |
| 87 | 1 => Ok(GitId::Sha1(reader.array()?)), |
| 88 | 2 => Ok(GitId::Sha256(reader.array()?)), |
| 89 | _ => Err(DecodeError::Invalid { |
| 90 | at, |
| 91 | what: "git id algorithm", |
| 92 | }), |
| 93 | } |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | /// What a directory entry is. |
| 98 | #[derive(Clone, Debug, PartialEq, Eq, Hash)] |
| 99 | pub enum EntryKind { |
| 100 | /// A regular file. |
| 101 | File { blob: ObjectId, size: u64 }, |
| 102 | /// An executable file. |
| 103 | Executable { blob: ObjectId, size: u64 }, |
| 104 | /// A symlink; the blob holds its target. |
| 105 | Symlink { blob: ObjectId, size: u64 }, |
| 106 | /// A subdirectory. |
| 107 | Tree { tree: ObjectId }, |
| 108 | /// A git submodule, pinned to a commit of another repository. |
| 109 | Gitlink { commit: GitId }, |
| 110 | } |
| 111 | |
| 112 | impl EntryKind { |
| 113 | /// The one-byte code of this kind in the encoding. |
| 114 | pub const fn code(&self) -> u8 { |
| 115 | match self { |
| 116 | EntryKind::File { .. } => 0, |
| 117 | EntryKind::Executable { .. } => 1, |
| 118 | EntryKind::Symlink { .. } => 2, |
| 119 | EntryKind::Tree { .. } => 3, |
| 120 | EntryKind::Gitlink { .. } => 4, |
| 121 | } |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | /// One entry of a directory. |
| 126 | #[derive(Clone, Debug, PartialEq, Eq, Hash)] |
| 127 | pub struct Entry { |
| 128 | /// The entry's name, a single path component. |
| 129 | pub name: Vec<u8>, |
| 130 | /// What the entry is. |
| 131 | pub kind: EntryKind, |
| 132 | } |
| 133 | |
| 134 | impl Entry { |
| 135 | fn encode(&self, out: &mut Vec<u8>) { |
| 136 | put_bytes(out, &self.name); |
| 137 | out.push(self.kind.code()); |
| 138 | match &self.kind { |
| 139 | EntryKind::File { blob, size } |
| 140 | | EntryKind::Executable { blob, size } |
| 141 | | EntryKind::Symlink { blob, size } => { |
| 142 | put_id(out, blob); |
| 143 | put_uv(out, *size); |
| 144 | } |
| 145 | EntryKind::Tree { tree } => put_id(out, tree), |
| 146 | EntryKind::Gitlink { commit } => commit.encode(out), |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | fn decode(reader: &mut Reader<'_>) -> Result<Self, TreeError> { |
| 151 | let name = reader.bytes()?.to_vec(); |
| 152 | let at = reader.position(); |
| 153 | let kind = match reader.u8()? { |
| 154 | 0 => EntryKind::File { |
| 155 | blob: reader.id()?, |
| 156 | size: reader.uv()?, |
| 157 | }, |
| 158 | 1 => EntryKind::Executable { |
| 159 | blob: reader.id()?, |
| 160 | size: reader.uv()?, |
| 161 | }, |
| 162 | 2 => EntryKind::Symlink { |
| 163 | blob: reader.id()?, |
| 164 | size: reader.uv()?, |
| 165 | }, |
| 166 | 3 => EntryKind::Tree { tree: reader.id()? }, |
| 167 | 4 => EntryKind::Gitlink { |
| 168 | commit: GitId::decode(reader)?, |
| 169 | }, |
| 170 | _ => { |
| 171 | return Err(TreeError::Decode(DecodeError::Invalid { |
| 172 | at, |
| 173 | what: "entry kind", |
| 174 | })); |
| 175 | } |
| 176 | }; |
| 177 | let entry = Entry { name, kind }; |
| 178 | validate_entry(&entry)?; |
| 179 | Ok(entry) |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | /// Smallest possible encoded entry: a 1-byte name, a kind and a SHA-1 gitlink. |
| 184 | const MIN_ENTRY_BYTES: usize = 1 + 1 + 1 + 1 + 20; |
| 185 | |
| 186 | /// Smallest possible encoded child reference. |
| 187 | const MIN_CHILD_BYTES: usize = 1 + 1 + 32 + 1; |
| 188 | |
| 189 | /// A reference from an internal node to the node below it. |
| 190 | #[derive(Clone, Debug, PartialEq, Eq, Hash)] |
| 191 | pub struct Child { |
| 192 | /// Name of the last entry under this child. |
| 193 | pub last_name: Vec<u8>, |
| 194 | /// Id of the child node. |
| 195 | pub node: ObjectId, |
| 196 | /// Number of entries under this child. |
| 197 | pub entry_count: u64, |
| 198 | } |
| 199 | |
| 200 | /// One encoded tree object. |
| 201 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 202 | pub enum Node { |
| 203 | /// A whole directory of at most [`MAX_FLAT_ENTRIES`] entries. |
| 204 | Flat(Vec<Entry>), |
| 205 | /// A run of entries of a split directory. |
| 206 | Leaf(Vec<Entry>), |
| 207 | /// A run of children of a split directory. |
| 208 | Internal { |
| 209 | /// 1 for the nodes just above the leaves. |
| 210 | level: u8, |
| 211 | /// The nodes below, in name order. |
| 212 | children: Vec<Child>, |
| 213 | }, |
| 214 | } |
| 215 | |
| 216 | /// Why a tree is not valid. |
| 217 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 218 | pub enum TreeError { |
| 219 | /// The bytes are not a canonical encoding. |
| 220 | Decode(DecodeError), |
| 221 | /// An entry name is not valid. |
| 222 | Name { name: Vec<u8>, error: NameError }, |
| 223 | /// A name that git or braid reads is a symlink. |
| 224 | SymlinkName(Vec<u8>), |
| 225 | /// Names are not strictly ascending; `index` is the first entry out of order. |
| 226 | Unsorted { index: usize }, |
| 227 | /// A node holds more entries or children than allowed, or none. |
| 228 | BadNodeSize { count: usize }, |
| 229 | /// A child reference covers no entries. |
| 230 | EmptyChild, |
| 231 | /// A node referenced by a split directory is missing. |
| 232 | MissingNode(ObjectId), |
| 233 | /// The nodes are well-formed but not the canonical split of their entries. |
| 234 | NotCanonical, |
| 235 | } |
| 236 | |
| 237 | impl fmt::Display for TreeError { |
| 238 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 239 | match self { |
| 240 | TreeError::Decode(err) => write!(f, "{err}"), |
| 241 | TreeError::Name { name, error } => { |
| 242 | write!(f, "entry {:?}: {error}", String::from_utf8_lossy(name)) |
| 243 | } |
| 244 | TreeError::SymlinkName(name) => write!( |
| 245 | f, |
| 246 | "entry {:?} must not be a symlink", |
| 247 | String::from_utf8_lossy(name) |
| 248 | ), |
| 249 | TreeError::Unsorted { index } => { |
| 250 | write!(f, "entry {index} is out of order or a duplicate") |
| 251 | } |
| 252 | TreeError::BadNodeSize { count } => write!(f, "node holds {count} items"), |
| 253 | TreeError::EmptyChild => f.write_str("child reference covers no entries"), |
| 254 | TreeError::MissingNode(id) => write!(f, "tree node {id} is missing"), |
| 255 | TreeError::NotCanonical => { |
| 256 | f.write_str("nodes are not the canonical split of the directory") |
| 257 | } |
| 258 | } |
| 259 | } |
| 260 | } |
| 261 | |
| 262 | impl std::error::Error for TreeError {} |
| 263 | |
| 264 | impl From<DecodeError> for TreeError { |
| 265 | fn from(err: DecodeError) -> Self { |
| 266 | TreeError::Decode(err) |
| 267 | } |
| 268 | } |
| 269 | |
| 270 | /// Checks one entry on its own: its name, and the symlink restriction. |
| 271 | pub fn validate_entry(entry: &Entry) -> Result<(), TreeError> { |
| 272 | check_entry(&entry.name, &entry.kind) |
| 273 | } |
| 274 | |
| 275 | fn check_entry(name: &[u8], kind: &EntryKind) -> Result<(), TreeError> { |
| 276 | validate_name(name).map_err(|error| TreeError::Name { |
| 277 | name: name.to_vec(), |
| 278 | error, |
| 279 | })?; |
| 280 | if matches!(kind, EntryKind::Symlink { .. }) && forbidden_as_symlink(name) { |
| 281 | return Err(TreeError::SymlinkName(name.to_vec())); |
| 282 | } |
| 283 | Ok(()) |
| 284 | } |
| 285 | |
| 286 | fn check_ascending<'a>(names: impl Iterator<Item = &'a [u8]>) -> Result<(), TreeError> { |
| 287 | let mut previous: Option<&[u8]> = None; |
| 288 | for (index, name) in names.enumerate() { |
| 289 | if previous.is_some_and(|p| p >= name) { |
| 290 | return Err(TreeError::Unsorted { index }); |
| 291 | } |
| 292 | previous = Some(name); |
| 293 | } |
| 294 | Ok(()) |
| 295 | } |
| 296 | |
| 297 | impl Node { |
| 298 | /// The canonical encoding. |
| 299 | pub fn encode(&self) -> Vec<u8> { |
| 300 | let mut out = vec![FORMAT]; |
| 301 | match self { |
| 302 | Node::Flat(entries) | Node::Leaf(entries) => { |
| 303 | out.push(if matches!(self, Node::Flat(_)) { |
| 304 | NODE_FLAT |
| 305 | } else { |
| 306 | NODE_LEAF |
| 307 | }); |
| 308 | put_uv(&mut out, entries.len() as u64); |
| 309 | for entry in entries { |
| 310 | entry.encode(&mut out); |
| 311 | } |
| 312 | } |
| 313 | Node::Internal { level, children } => { |
| 314 | out.push(NODE_INTERNAL); |
| 315 | out.push(*level); |
| 316 | put_uv(&mut out, children.len() as u64); |
| 317 | for child in children { |
| 318 | put_bytes(&mut out, &child.last_name); |
| 319 | put_id(&mut out, &child.node); |
| 320 | put_uv(&mut out, child.entry_count); |
| 321 | } |
| 322 | } |
| 323 | } |
| 324 | out |
| 325 | } |
| 326 | |
| 327 | /// The id of this node. |
| 328 | pub fn id(&self) -> ObjectId { |
| 329 | ObjectId::hash(Kind::Tree, &self.encode()) |
| 330 | } |
| 331 | |
| 332 | /// Decodes one node and checks everything that can be checked without |
| 333 | /// the other nodes of its directory. |
| 334 | pub fn decode(bytes: &[u8]) -> Result<Self, TreeError> { |
| 335 | let mut reader = Reader::new(bytes); |
| 336 | let at = reader.position(); |
| 337 | if reader.u8()? != FORMAT { |
| 338 | return Err(DecodeError::Invalid { |
| 339 | at, |
| 340 | what: "tree format", |
| 341 | } |
| 342 | .into()); |
| 343 | } |
| 344 | let at = reader.position(); |
| 345 | let node = match reader.u8()? { |
| 346 | node_type @ (NODE_FLAT | NODE_LEAF) => { |
| 347 | let count = reader.count(MIN_ENTRY_BYTES)?; |
| 348 | let limit = if node_type == NODE_FLAT { |
| 349 | MAX_FLAT_ENTRIES |
| 350 | } else { |
| 351 | MAX_NODE_ENTRIES |
| 352 | }; |
| 353 | if count > limit || (node_type == NODE_LEAF && count == 0) { |
| 354 | return Err(TreeError::BadNodeSize { count }); |
| 355 | } |
| 356 | let mut entries = Vec::with_capacity(count); |
| 357 | for _ in 0..count { |
| 358 | entries.push(Entry::decode(&mut reader)?); |
| 359 | } |
| 360 | check_ascending(entries.iter().map(|e| e.name.as_slice()))?; |
| 361 | if node_type == NODE_FLAT { |
| 362 | Node::Flat(entries) |
| 363 | } else { |
| 364 | Node::Leaf(entries) |
| 365 | } |
| 366 | } |
| 367 | NODE_INTERNAL => { |
| 368 | let level_at = reader.position(); |
| 369 | let level = reader.u8()?; |
| 370 | if level == 0 { |
| 371 | return Err(DecodeError::Invalid { |
| 372 | at: level_at, |
| 373 | what: "internal node level", |
| 374 | } |
| 375 | .into()); |
| 376 | } |
| 377 | let count = reader.count(MIN_CHILD_BYTES)?; |
| 378 | if count == 0 || count > MAX_NODE_ENTRIES { |
| 379 | return Err(TreeError::BadNodeSize { count }); |
| 380 | } |
| 381 | let mut children = Vec::with_capacity(count); |
| 382 | for _ in 0..count { |
| 383 | let last_name = reader.bytes()?.to_vec(); |
| 384 | validate_name(&last_name).map_err(|error| TreeError::Name { |
| 385 | name: last_name.clone(), |
| 386 | error, |
| 387 | })?; |
| 388 | let node = reader.id()?; |
| 389 | let entry_count = reader.uv()?; |
| 390 | if entry_count == 0 { |
| 391 | return Err(TreeError::EmptyChild); |
| 392 | } |
| 393 | children.push(Child { |
| 394 | last_name, |
| 395 | node, |
| 396 | entry_count, |
| 397 | }); |
| 398 | } |
| 399 | check_ascending(children.iter().map(|c| c.last_name.as_slice()))?; |
| 400 | Node::Internal { level, children } |
| 401 | } |
| 402 | _ => { |
| 403 | return Err(DecodeError::Invalid { |
| 404 | at, |
| 405 | what: "tree node type", |
| 406 | } |
| 407 | .into()); |
| 408 | } |
| 409 | }; |
| 410 | reader.finish()?; |
| 411 | Ok(node) |
| 412 | } |
| 413 | } |
| 414 | |
| 415 | /// The encoded nodes of one directory, children before parents. The last |
| 416 | /// node is the root, whose id is the directory's id. |
| 417 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 418 | pub struct Directory { |
| 419 | /// `(id, encoding)` of every node. |
| 420 | pub nodes: Vec<(ObjectId, Vec<u8>)>, |
| 421 | } |
| 422 | |
| 423 | impl Directory { |
| 424 | /// The id of the directory: the id of its root node. |
| 425 | pub fn root(&self) -> ObjectId { |
| 426 | self.nodes |
| 427 | .last() |
| 428 | .map(|(id, _)| *id) |
| 429 | .expect("a directory always has a root node") |
| 430 | } |
| 431 | } |
| 432 | |
| 433 | /// Whether a node ends after an item that makes it hold `count` items. |
| 434 | /// `hit`, whether the item's name hashes below the threshold, is only asked |
| 435 | /// when it matters. |
| 436 | fn ends(count: usize, hit: impl FnOnce() -> bool) -> bool { |
| 437 | count >= MAX_NODE_ENTRIES || (count >= MIN_NODE_ENTRIES && hit()) |
| 438 | } |
| 439 | |
| 440 | /// The splitting rule, with one hasher kept for every name it looks at. |
| 441 | struct Splitter { |
| 442 | hasher: blake3::Hasher, |
| 443 | } |
| 444 | |
| 445 | impl Splitter { |
| 446 | fn new() -> Self { |
| 447 | Splitter { |
| 448 | hasher: blake3::Hasher::new_derive_key(SPLIT_CONTEXT), |
| 449 | } |
| 450 | } |
| 451 | |
| 452 | /// Whether `H(level, name)` falls below the threshold. |
| 453 | fn hit(&mut self, level: u8, name: &[u8]) -> bool { |
| 454 | self.hasher.reset(); |
| 455 | self.hasher.update(&[level]); |
| 456 | self.hasher.update(name); |
| 457 | let digest = self.hasher.finalize(); |
| 458 | let head = digest.as_bytes(); |
| 459 | u32::from_le_bytes([head[0], head[1], head[2], head[3]]) < SPLIT_THRESHOLD |
| 460 | } |
| 461 | |
| 462 | /// Whether a node of `level` ends after an item named `name` that makes |
| 463 | /// it hold `count` items. |
| 464 | fn ends(&mut self, level: u8, name: &[u8], count: usize) -> bool { |
| 465 | ends(count, || self.hit(level, name)) |
| 466 | } |
| 467 | } |
| 468 | |
| 469 | /// What the nodes of one level of a split directory hold: entries in the |
| 470 | /// leaves, references to the nodes below in internal nodes. |
| 471 | trait Item: Clone + PartialEq { |
| 472 | /// The name that orders items and that the splitting rule hashes. |
| 473 | fn name(&self) -> &[u8]; |
| 474 | /// How many entries of the directory it stands for. |
| 475 | fn entries(&self) -> u64; |
| 476 | /// The node of `level` that holds `items`. |
| 477 | fn node(level: u8, items: Vec<Self>) -> Node; |
| 478 | /// The items of `node`, if it holds this kind of item. |
| 479 | fn items(node: &Node) -> Option<&[Self]>; |
| 480 | } |
| 481 | |
| 482 | impl Item for Entry { |
| 483 | fn name(&self) -> &[u8] { |
| 484 | &self.name |
| 485 | } |
| 486 | |
| 487 | fn entries(&self) -> u64 { |
| 488 | 1 |
| 489 | } |
| 490 | |
| 491 | fn node(_: u8, items: Vec<Self>) -> Node { |
| 492 | Node::Leaf(items) |
| 493 | } |
| 494 | |
| 495 | fn items(node: &Node) -> Option<&[Self]> { |
| 496 | match node { |
| 497 | Node::Leaf(entries) => Some(entries), |
| 498 | _ => None, |
| 499 | } |
| 500 | } |
| 501 | } |
| 502 | |
| 503 | impl Item for Child { |
| 504 | fn name(&self) -> &[u8] { |
| 505 | &self.last_name |
| 506 | } |
| 507 | |
| 508 | fn entries(&self) -> u64 { |
| 509 | self.entry_count |
| 510 | } |
| 511 | |
| 512 | fn node(level: u8, items: Vec<Self>) -> Node { |
| 513 | Node::Internal { |
| 514 | level, |
| 515 | children: items, |
| 516 | } |
| 517 | } |
| 518 | |
| 519 | fn items(node: &Node) -> Option<&[Self]> { |
| 520 | match node { |
| 521 | Node::Internal { children, .. } => Some(children), |
| 522 | _ => None, |
| 523 | } |
| 524 | } |
| 525 | } |
| 526 | |
| 527 | /// A node cut by a [`Chunker`]: the reference a parent holds to it, and its |
| 528 | /// encoding. |
| 529 | struct Made { |
| 530 | child: Child, |
| 531 | bytes: Vec<u8>, |
| 532 | } |
| 533 | |
| 534 | /// Cuts the items of one level, given in name order, into nodes. |
| 535 | struct Chunker<I> { |
| 536 | level: u8, |
| 537 | /// The items of the node being filled. |
| 538 | run: Vec<I>, |
| 539 | made: Vec<Made>, |
| 540 | } |
| 541 | |
| 542 | impl<I: Item> Chunker<I> { |
| 543 | fn new(level: u8) -> Self { |
| 544 | Chunker { |
| 545 | level, |
| 546 | run: Vec::new(), |
| 547 | made: Vec::new(), |
| 548 | } |
| 549 | } |
| 550 | |
| 551 | /// How many items the node being filled holds with one more. |
| 552 | fn next_count(&self) -> usize { |
| 553 | self.run.len() + 1 |
| 554 | } |
| 555 | |
| 556 | /// Whether the last item ended a node, so that the next one starts a |
| 557 | /// new one. |
| 558 | fn at_boundary(&self) -> bool { |
| 559 | self.run.is_empty() |
| 560 | } |
| 561 | |
| 562 | /// Adds the next item, and ends its node after it if `cut`. |
| 563 | fn push(&mut self, item: I, cut: bool) { |
| 564 | self.run.push(item); |
| 565 | if cut { |
| 566 | self.cut(); |
| 567 | } |
| 568 | } |
| 569 | |
| 570 | /// Adds the next item, and ends its node where the splitting rule says. |
| 571 | fn add(&mut self, item: I, splitter: &mut Splitter) { |
| 572 | let cut = splitter.ends(self.level, item.name(), self.next_count()); |
| 573 | self.push(item, cut); |
| 574 | } |
| 575 | |
| 576 | /// Ends the node being filled, if it holds anything. |
| 577 | fn cut(&mut self) { |
| 578 | let Some(last) = self.run.last() else { |
| 579 | return; |
| 580 | }; |
| 581 | let last_name = last.name().to_vec(); |
| 582 | // Saturating: only references read from a corrupt directory could |
| 583 | // add up past the largest count. |
| 584 | let entry_count = self |
| 585 | .run |
| 586 | .iter() |
| 587 | .fold(0u64, |sum, item| sum.saturating_add(item.entries())); |
| 588 | let node = I::node(self.level, core::mem::take(&mut self.run)); |
| 589 | let bytes = node.encode(); |
| 590 | self.made.push(Made { |
| 591 | child: Child { |
| 592 | last_name, |
| 593 | node: ObjectId::hash(Kind::Tree, &bytes), |
| 594 | entry_count, |
| 595 | }, |
| 596 | bytes, |
| 597 | }); |
| 598 | } |
| 599 | |
| 600 | /// Ends the last node, and returns every node cut, in order. |
| 601 | fn finish(mut self) -> Vec<Made> { |
| 602 | self.cut(); |
| 603 | self.made |
| 604 | } |
| 605 | } |
| 606 | |
| 607 | /// One node of a directory built from scratch. |
| 608 | struct Built { |
| 609 | id: ObjectId, |
| 610 | bytes: Vec<u8>, |
| 611 | /// Whether it holds entries: a flat node or a leaf. |
| 612 | holds_entries: bool, |
| 613 | } |
| 614 | |
| 615 | /// Builds the canonical nodes of a directory from its entries, in any order. |
| 616 | pub fn build_directory(mut entries: Vec<Entry>) -> Result<Directory, TreeError> { |
| 617 | entries.sort_by(|a, b| a.name.cmp(&b.name)); |
| 618 | check_ascending(entries.iter().map(|e| e.name.as_slice()))?; |
| 619 | for entry in &entries { |
| 620 | validate_entry(entry)?; |
| 621 | } |
| 622 | let nodes = build_nodes(entries) |
| 623 | .into_iter() |
| 624 | .map(|node| (node.id, node.bytes)) |
| 625 | .collect(); |
| 626 | Ok(Directory { nodes }) |
| 627 | } |
| 628 | |
| 629 | /// The canonical nodes of sorted, valid entries, children before parents. |
| 630 | fn build_nodes(entries: Vec<Entry>) -> Vec<Built> { |
| 631 | if entries.len() <= MAX_FLAT_ENTRIES { |
| 632 | let bytes = Node::Flat(entries).encode(); |
| 633 | return vec![Built { |
| 634 | id: ObjectId::hash(Kind::Tree, &bytes), |
| 635 | bytes, |
| 636 | holds_entries: true, |
| 637 | }]; |
| 638 | } |
| 639 | let mut splitter = Splitter::new(); |
| 640 | let mut nodes = Vec::new(); |
| 641 | let mut leaves = Chunker::new(0); |
| 642 | for entry in entries { |
| 643 | leaves.add(entry, &mut splitter); |
| 644 | } |
| 645 | let mut children = keep(&mut nodes, leaves.finish(), true); |
| 646 | // Internal levels, until one node is left. |
| 647 | let mut level = 1u8; |
| 648 | while children.len() > 1 { |
| 649 | let mut chunker = Chunker::new(level); |
| 650 | for child in children { |
| 651 | chunker.add(child, &mut splitter); |
| 652 | } |
| 653 | children = keep(&mut nodes, chunker.finish(), false); |
| 654 | level += 1; |
| 655 | } |
| 656 | nodes |
| 657 | } |
| 658 | |
| 659 | /// Moves the nodes of one level into `nodes`, and returns the references to |
| 660 | /// them, for the level above. |
| 661 | fn keep(nodes: &mut Vec<Built>, made: Vec<Made>, holds_entries: bool) -> Vec<Child> { |
| 662 | made.into_iter() |
| 663 | .map(|made| { |
| 664 | nodes.push(Built { |
| 665 | id: made.child.node, |
| 666 | bytes: made.bytes, |
| 667 | holds_entries, |
| 668 | }); |
| 669 | made.child |
| 670 | }) |
| 671 | .collect() |
| 672 | } |
| 673 | |
| 674 | /// Reads every entry of the directory rooted at `root`, fetching nodes through |
| 675 | /// `fetch`, and checks that the nodes are exactly the canonical split of those |
| 676 | /// entries. |
| 677 | /// |
| 678 | /// The check goes node by node instead of building the directory again. Each |
| 679 | /// node must hash to its id and be what the reference to it says: its level, |
| 680 | /// its last name and its number of entries. The entries must ascend from one |
| 681 | /// leaf to the next, and every node must end where the splitting rule ends |
| 682 | /// it, and nowhere before, except the last node of each level, which the end |
| 683 | /// of the directory ends. With a root of two children or more, over more |
| 684 | /// entries than a flat node holds, that is the canonical split. |
| 685 | pub fn read_directory( |
| 686 | root: ObjectId, |
| 687 | mut fetch: impl FnMut(&ObjectId) -> Option<Vec<u8>>, |
| 688 | ) -> Result<Vec<Entry>, TreeError> { |
| 689 | let (level, children) = match fetched(root, &mut fetch)? { |
| 690 | Node::Flat(entries) => return Ok(entries), |
| 691 | Node::Leaf(_) => return Err(TreeError::NotCanonical), |
| 692 | Node::Internal { level, children } => (level, children), |
| 693 | }; |
| 694 | let total = split_total(&children)?; |
| 695 | let mut whole = Whole { |
| 696 | fetch, |
| 697 | splitter: Splitter::new(), |
| 698 | last_name: children |
| 699 | .last() |
| 700 | .map(|child| child.last_name.clone()) |
| 701 | .unwrap_or_default(), |
| 702 | // The counts are checked as the nodes are read: do not trust them |
| 703 | // with a large allocation before. |
| 704 | entries: Vec::with_capacity(usize::try_from(total).map_or(0, |total| total.min(1 << 16))), |
| 705 | }; |
| 706 | whole.below(level, &children, true)?; |
| 707 | Ok(whole.entries) |
| 708 | } |
| 709 | |
| 710 | /// Fetches the node `id`, checks that its bytes hash to its id, and decodes |
| 711 | /// it. |
| 712 | fn fetched( |
| 713 | id: ObjectId, |
| 714 | fetch: &mut impl FnMut(&ObjectId) -> Option<Vec<u8>>, |
| 715 | ) -> Result<Node, TreeError> { |
| 716 | let bytes = fetch(&id).ok_or(TreeError::MissingNode(id))?; |
| 717 | if ObjectId::hash(Kind::Tree, &bytes) != id { |
| 718 | return Err(TreeError::NotCanonical); |
| 719 | } |
| 720 | Node::decode(&bytes) |
| 721 | } |
| 722 | |
| 723 | /// A split directory being read whole, and checked node by node. |
| 724 | struct Whole<F> { |
| 725 | fetch: F, |
| 726 | splitter: Splitter, |
| 727 | /// The last name of the directory: the last node of every level ends |
| 728 | /// with it. |
| 729 | last_name: Vec<u8>, |
| 730 | entries: Vec<Entry>, |
| 731 | } |
| 732 | |
| 733 | impl<F: FnMut(&ObjectId) -> Option<Vec<u8>>> Whole<F> { |
| 734 | /// Checks where an internal node of `level` with `children` ends, then |
| 735 | /// reads every node below it, in order. |
| 736 | fn below(&mut self, level: u8, children: &[Child], last: bool) -> Result<(), TreeError> { |
| 737 | self.cuts(level, children, last)?; |
| 738 | for child in children { |
| 739 | let node = fetched(child.node, &mut self.fetch)?; |
| 740 | check_child(&node, level - 1, child)?; |
| 741 | let last = child.last_name == self.last_name; |
| 742 | match node { |
| 743 | Node::Leaf(entries) => { |
| 744 | self.cuts(0, &entries, last)?; |
| 745 | if let (Some(previous), Some(first)) = (self.entries.last(), entries.first()) |
| 746 | && first.name <= previous.name |
| 747 | { |
| 748 | return Err(TreeError::NotCanonical); |
| 749 | } |
| 750 | self.entries.extend(entries); |
| 751 | } |
| 752 | Node::Internal { level, children } => self.below(level, &children, last)?, |
| 753 | Node::Flat(_) => return Err(TreeError::NotCanonical), |
| 754 | } |
| 755 | } |
| 756 | Ok(()) |
| 757 | } |
| 758 | |
| 759 | /// Checks that a node of `level` that holds `items` ends where the |
| 760 | /// splitting rule ends it, and nowhere before. The last node of a level, |
| 761 | /// `last`, ends with the directory instead. |
| 762 | fn cuts<I: Item>(&mut self, level: u8, items: &[I], last: bool) -> Result<(), TreeError> { |
| 763 | for (index, item) in items.iter().enumerate() { |
| 764 | let end = index + 1 == items.len(); |
| 765 | if end && last { |
| 766 | break; |
| 767 | } |
| 768 | if self.splitter.ends(level, item.name(), index + 1) != end { |
| 769 | return Err(TreeError::NotCanonical); |
| 770 | } |
| 771 | } |
| 772 | Ok(()) |
| 773 | } |
| 774 | } |
| 775 | |
| 776 | // --------------------------------------------------------------------------- |
| 777 | // One path at a time |
| 778 | |
| 779 | /// One edit of a directory: the entry a name gets, or its removal. |
| 780 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 781 | pub struct EntryEdit { |
| 782 | /// The name. |
| 783 | pub name: Vec<u8>, |
| 784 | /// What the name becomes; `None` removes it. Removing a name the |
| 785 | /// directory does not have changes nothing. |
| 786 | pub kind: Option<EntryKind>, |
| 787 | } |
| 788 | |
| 789 | /// Checks edits on their own: names strictly ascending, and every entry they |
| 790 | /// set valid. |
| 791 | pub fn check_edits(edits: &[EntryEdit]) -> Result<(), TreeError> { |
| 792 | check_ascending(edits.iter().map(|edit| edit.name.as_slice()))?; |
| 793 | for edit in edits { |
| 794 | if let Some(kind) = &edit.kind { |
| 795 | check_entry(&edit.name, kind)?; |
| 796 | } |
| 797 | } |
| 798 | Ok(()) |
| 799 | } |
| 800 | |
| 801 | /// A node that an update of a directory made, and that the directory did not |
| 802 | /// have before. |
| 803 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 804 | pub struct NewNode { |
| 805 | /// Its id. |
| 806 | pub id: ObjectId, |
| 807 | /// Its encoding. |
| 808 | pub bytes: Vec<u8>, |
| 809 | /// The node of the directory before the update that it most likely |
| 810 | /// replaces: a hint for a store that may keep it as a difference from |
| 811 | /// that node, as [`Objects::put_similar`](crate::Objects::put_similar) |
| 812 | /// takes. |
| 813 | pub similar: Option<ObjectId>, |
| 814 | } |
| 815 | |
| 816 | /// A directory after an update. |
| 817 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 818 | pub struct Updated { |
| 819 | /// Its id: the id of its root node. |
| 820 | pub root: ObjectId, |
| 821 | /// How many entries it holds. |
| 822 | pub entries: u64, |
| 823 | /// Its nodes that the directory before the update did not have, children |
| 824 | /// before parents. With the nodes it kept, they are exactly the nodes |
| 825 | /// that [`build_directory`] makes of its entries. |
| 826 | pub nodes: Vec<NewNode>, |
| 827 | } |
| 828 | |
| 829 | /// Nodes of directories, each fetched, checked against its id and decoded |
| 830 | /// once, for the readers that go one path at a time. |
| 831 | #[derive(Debug, Default)] |
| 832 | pub struct NodeCache { |
| 833 | nodes: HashMap<ObjectId, Rc<Node>>, |
| 834 | } |
| 835 | |
| 836 | impl NodeCache { |
| 837 | /// An empty cache. |
| 838 | pub fn new() -> Self { |
| 839 | Self::default() |
| 840 | } |
| 841 | |
| 842 | /// How many nodes it holds: each was fetched once. |
| 843 | pub fn len(&self) -> usize { |
| 844 | self.nodes.len() |
| 845 | } |
| 846 | |
| 847 | /// Whether it holds no node. |
| 848 | pub fn is_empty(&self) -> bool { |
| 849 | self.nodes.is_empty() |
| 850 | } |
| 851 | |
| 852 | /// The node `id`. The first time, it is fetched through `fetch`, checked |
| 853 | /// against its id and decoded. |
| 854 | pub fn get( |
| 855 | &mut self, |
| 856 | id: ObjectId, |
| 857 | fetch: &mut impl FnMut(&ObjectId) -> Option<Vec<u8>>, |
| 858 | ) -> Result<Rc<Node>, TreeError> { |
| 859 | if let Some(node) = self.nodes.get(&id) { |
| 860 | return Ok(Rc::clone(node)); |
| 861 | } |
| 862 | let node = Rc::new(fetched(id, fetch)?); |
| 863 | self.nodes.insert(id, Rc::clone(&node)); |
| 864 | Ok(node) |
| 865 | } |
| 866 | } |
| 867 | |
| 868 | /// The entry named `name` in the directory whose root node is `root`, or |
| 869 | /// `None` if it has none. |
| 870 | /// |
| 871 | /// A split directory is searched from the root down: each internal node leads |
| 872 | /// to the child whose last name is the first at or after `name`, so only the |
| 873 | /// nodes on that path are read. Each of them is checked against its id and |
| 874 | /// against the reference that leads to it: its level, its last name and its |
| 875 | /// number of entries. Whether the directory as a whole is the canonical split |
| 876 | /// of its entries is what [`read_directory`] checks, by reading all of it. |
| 877 | pub fn find_entry( |
| 878 | cache: &mut NodeCache, |
| 879 | root: ObjectId, |
| 880 | name: &[u8], |
| 881 | mut fetch: impl FnMut(&ObjectId) -> Option<Vec<u8>>, |
| 882 | ) -> Result<Option<EntryKind>, TreeError> { |
| 883 | let mut node = cache.get(root, &mut fetch)?; |
| 884 | match &*node { |
| 885 | Node::Flat(entries) => return Ok(search(entries, name)), |
| 886 | Node::Leaf(_) => return Err(TreeError::NotCanonical), |
| 887 | Node::Internal { children, .. } => { |
| 888 | split_total(children)?; |
| 889 | } |
| 890 | } |
| 891 | loop { |
| 892 | let (level, children) = match &*node { |
| 893 | Node::Leaf(entries) => return Ok(search(entries, name)), |
| 894 | Node::Internal { level, children } => (*level, children), |
| 895 | Node::Flat(_) => return Err(TreeError::NotCanonical), |
| 896 | }; |
| 897 | let index = children.partition_point(|child| child.last_name.as_slice() < name); |
| 898 | let Some(child) = children.get(index) else { |
| 899 | // After the last name of the directory. |
| 900 | return Ok(None); |
| 901 | }; |
| 902 | let below = cache.get(child.node, &mut fetch)?; |
| 903 | check_child(&below, level - 1, child)?; |
| 904 | node = below; |
| 905 | } |
| 906 | } |
| 907 | |
| 908 | /// Applies `edits`, sorted by name, to the directory whose root node is |
| 909 | /// `root`, and returns the directory they make: its root, its number of |
| 910 | /// entries, and the nodes to store. The result is exactly what |
| 911 | /// [`build_directory`] makes of the edited entries, node for node. |
| 912 | /// |
| 913 | /// A flat directory is built again from its entries. A split one is updated |
| 914 | /// in place, one run of leaves at a time. A run starts at the leaf that holds |
| 915 | /// the first name left to edit, or would hold it: every boundary before it is |
| 916 | /// unchanged, since where a node ends depends only on the names up to there. The run |
| 917 | /// is cut into new leaves by the splitting rule, edits included, and it goes |
| 918 | /// on into the following leaves until a new leaf ends exactly where an old |
| 919 | /// one ended: from there the rule sees the same names from the same start, |
| 920 | /// so every following leaf is unchanged, up to the next name to edit. The |
| 921 | /// new leaves replace the old ones of the run in the level above, which is |
| 922 | /// updated the same way, up to the root. Only the nodes of the runs, and the |
| 923 | /// nodes on the paths that lead to them, are read. A directory that grows |
| 924 | /// past [`MAX_FLAT_ENTRIES`] entries is split, and one that shrinks to that |
| 925 | /// many or fewer is read whole and made flat again. |
| 926 | /// |
| 927 | /// The edits are checked before any node is read: an invalid one is an |
| 928 | /// error. Every node read is checked against its id and the reference that |
| 929 | /// leads to it, and the old boundaries inside the runs are checked against |
| 930 | /// the splitting rule; the rest of the directory is assumed canonical, as |
| 931 | /// every directory this crate builds is. |
| 932 | pub fn update_directory( |
| 933 | cache: &mut NodeCache, |
| 934 | root: ObjectId, |
| 935 | edits: &[EntryEdit], |
| 936 | mut fetch: impl FnMut(&ObjectId) -> Option<Vec<u8>>, |
| 937 | ) -> Result<Updated, TreeError> { |
| 938 | check_edits(edits)?; |
| 939 | let top = cache.get(root, &mut fetch)?; |
| 940 | match &*top { |
| 941 | Node::Flat(entries) => { |
| 942 | // An empty node is nothing for a store to start from. |
| 943 | let similar = (!entries.is_empty()).then_some(root); |
| 944 | Ok(rebuilt( |
| 945 | root, |
| 946 | similar, |
| 947 | merge_items(entries.iter().cloned(), entry_changes(edits)), |
| 948 | )) |
| 949 | } |
| 950 | Node::Leaf(_) => Err(TreeError::NotCanonical), |
| 951 | Node::Internal { level, children } => { |
| 952 | let entry_count = split_total(children)?; |
| 953 | let last_name = children |
| 954 | .last() |
| 955 | .map(|child| child.last_name.clone()) |
| 956 | .unwrap_or_default(); |
| 957 | Split { |
| 958 | cache, |
| 959 | fetch: &mut fetch, |
| 960 | root: Child { |
| 961 | last_name, |
| 962 | node: root, |
| 963 | entry_count, |
| 964 | }, |
| 965 | height: *level, |
| 966 | splitter: Splitter::new(), |
| 967 | made: Vec::new(), |
| 968 | } |
| 969 | .update(edits) |
| 970 | } |
| 971 | } |
| 972 | } |
| 973 | |
| 974 | /// The entry named `name` among sorted entries. |
| 975 | fn search(entries: &[Entry], name: &[u8]) -> Option<EntryKind> { |
| 976 | entries |
| 977 | .binary_search_by(|entry| entry.name.as_slice().cmp(name)) |
| 978 | .ok() |
| 979 | .map(|index| entries[index].kind.clone()) |
| 980 | } |
| 981 | |
| 982 | /// The number of entries under a split directory's root, whose children |
| 983 | /// are `children`: it has at least two, else the one below would be the |
| 984 | /// root, and more entries than a flat node holds. |
| 985 | fn split_total(children: &[Child]) -> Result<u64, TreeError> { |
| 986 | let total = children |
| 987 | .iter() |
| 988 | .try_fold(0u64, |sum, child| sum.checked_add(child.entry_count)); |
| 989 | match total { |
| 990 | Some(total) if children.len() >= 2 && total > MAX_FLAT_ENTRIES as u64 => Ok(total), |
| 991 | _ => Err(TreeError::NotCanonical), |
| 992 | } |
| 993 | } |
| 994 | |
| 995 | /// Checks that `node`, reached through `child`, is what that reference says: |
| 996 | /// a node of `level`, with the same last name and number of entries. |
| 997 | fn check_child(node: &Node, level: u8, child: &Child) -> Result<(), TreeError> { |
| 998 | let (last, count) = match node { |
| 999 | Node::Leaf(entries) if level == 0 => ( |
| 1000 | entries.last().map(|entry| entry.name.as_slice()), |
| 1001 | Some(entries.len() as u64), |
| 1002 | ), |
| 1003 | Node::Internal { |
| 1004 | level: found, |
| 1005 | children, |
| 1006 | } if *found == level => ( |
| 1007 | children.last().map(|child| child.last_name.as_slice()), |
| 1008 | children |
| 1009 | .iter() |
| 1010 | .try_fold(0u64, |sum, child| sum.checked_add(child.entry_count)), |
| 1011 | ), |
| 1012 | _ => return Err(TreeError::NotCanonical), |
| 1013 | }; |
| 1014 | if last == Some(child.last_name.as_slice()) && count == Some(child.entry_count) { |
| 1015 | Ok(()) |
| 1016 | } else { |
| 1017 | Err(TreeError::NotCanonical) |
| 1018 | } |
| 1019 | } |
| 1020 | |
| 1021 | /// Edits as changes to the items of the leaf level. |
| 1022 | fn entry_changes(edits: &[EntryEdit]) -> Vec<(Vec<u8>, Option<Entry>)> { |
| 1023 | edits |
| 1024 | .iter() |
| 1025 | .map(|edit| { |
| 1026 | let entry = edit.kind.clone().map(|kind| Entry { |
| 1027 | name: edit.name.clone(), |
| 1028 | kind, |
| 1029 | }); |
| 1030 | (edit.name.clone(), entry) |
| 1031 | }) |
| 1032 | .collect() |
| 1033 | } |
| 1034 | |
| 1035 | /// Sorted items after sorted changes, each of which sets the item of a name |
| 1036 | /// or removes it. |
| 1037 | fn merge_items<I: Item>( |
| 1038 | old: impl IntoIterator<Item = I>, |
| 1039 | changes: impl IntoIterator<Item = (Vec<u8>, Option<I>)>, |
| 1040 | ) -> Vec<I> { |
| 1041 | let mut merged = Vec::new(); |
| 1042 | let mut old = old.into_iter().peekable(); |
| 1043 | for (name, new) in changes { |
| 1044 | while let Some(item) = old.next_if(|item| item.name() < name.as_slice()) { |
| 1045 | merged.push(item); |
| 1046 | } |
| 1047 | old.next_if(|item| item.name() == name.as_slice()); |
| 1048 | merged.extend(new); |
| 1049 | } |
| 1050 | merged.extend(old); |
| 1051 | merged |
| 1052 | } |
| 1053 | |
| 1054 | /// The directory of `entries`, sorted and valid, built from scratch to |
| 1055 | /// replace the one whose root was `old_root`: every node but that root, the |
| 1056 | /// ones that hold entries paired with `similar`. |
| 1057 | fn rebuilt(old_root: ObjectId, similar: Option<ObjectId>, entries: Vec<Entry>) -> Updated { |
| 1058 | let count = entries.len() as u64; |
| 1059 | let built = build_nodes(entries); |
| 1060 | let root = built.last().map_or(old_root, |node| node.id); |
| 1061 | let nodes = built |
| 1062 | .into_iter() |
| 1063 | .filter(|node| node.id != old_root) |
| 1064 | .map(|node| NewNode { |
| 1065 | similar: similar.filter(|_| node.holds_entries), |
| 1066 | id: node.id, |
| 1067 | bytes: node.bytes, |
| 1068 | }) |
| 1069 | .collect(); |
| 1070 | Updated { |
| 1071 | root, |
| 1072 | entries: count, |
| 1073 | nodes, |
| 1074 | } |
| 1075 | } |
| 1076 | |
| 1077 | /// The changes to the items of one level: the item each name gets, or its |
| 1078 | /// removal, in name order. |
| 1079 | type ItemChanges<I> = Vec<(Vec<u8>, Option<I>)>; |
| 1080 | |
| 1081 | /// A split directory being updated. |
| 1082 | struct Split<'c, F> { |
| 1083 | cache: &'c mut NodeCache, |
| 1084 | fetch: F, |
| 1085 | /// The reference to its root before the update. |
| 1086 | root: Child, |
| 1087 | /// The level of that root. |
| 1088 | height: u8, |
| 1089 | splitter: Splitter, |
| 1090 | /// The nodes made so far that the directory did not have, children |
| 1091 | /// before parents, with their level and the node each most likely |
| 1092 | /// replaces. |
| 1093 | made: Vec<(u8, Made, Option<ObjectId>)>, |
| 1094 | } |
| 1095 | |
| 1096 | impl<F: FnMut(&ObjectId) -> Option<Vec<u8>>> Split<'_, F> { |
| 1097 | fn node(&mut self, id: ObjectId) -> Result<Rc<Node>, TreeError> { |
| 1098 | self.cache.get(id, &mut self.fetch) |
| 1099 | } |
| 1100 | |
| 1101 | fn update(mut self, edits: &[EntryEdit]) -> Result<Updated, TreeError> { |
| 1102 | let (mut changes, gained) = self.level::<Entry>(0, entry_changes(edits))?; |
| 1103 | let entries = i128::from(self.root.entry_count) + gained; |
| 1104 | if entries <= MAX_FLAT_ENTRIES as i128 { |
| 1105 | // Few enough entries for one flat node: read them all. |
| 1106 | let (old, largest) = self.entries()?; |
| 1107 | return Ok(rebuilt( |
| 1108 | self.root.node, |
| 1109 | largest, |
| 1110 | merge_items(old, entry_changes(edits)), |
| 1111 | )); |
| 1112 | } |
| 1113 | let entries = u64::try_from(entries).map_err(|_| TreeError::NotCanonical)?; |
| 1114 | for level in 1..self.height { |
| 1115 | if changes.is_empty() { |
| 1116 | // No node changed below this level, so none above it does. |
| 1117 | break; |
| 1118 | } |
| 1119 | changes = self.level::<Child>(level, changes)?.0; |
| 1120 | } |
| 1121 | if changes.is_empty() { |
| 1122 | // Edits that set names to the entries they had. |
| 1123 | debug_assert!(self.made.is_empty()); |
| 1124 | return Ok(Updated { |
| 1125 | root: self.root.node, |
| 1126 | entries, |
| 1127 | nodes: Vec::new(), |
| 1128 | }); |
| 1129 | } |
| 1130 | |
| 1131 | // The old root is the only node of its level, so the level is cut |
| 1132 | // again whole, and so is every level above it, until one node is left. |
| 1133 | let old_root = self.root.node; |
| 1134 | let node = self.node(old_root)?; |
| 1135 | let children = Child::items(&node).ok_or(TreeError::NotCanonical)?; |
| 1136 | let mut level = self.height; |
| 1137 | let mut chunker = Chunker::new(level); |
| 1138 | for child in merge_items(children.iter().cloned(), changes) { |
| 1139 | chunker.add(child, &mut self.splitter); |
| 1140 | } |
| 1141 | let mut top = self.record(level, chunker.finish(), Some(old_root)); |
| 1142 | while top.len() > 1 { |
| 1143 | level = level.checked_add(1).ok_or(TreeError::NotCanonical)?; |
| 1144 | let mut chunker = Chunker::new(level); |
| 1145 | for child in top { |
| 1146 | chunker.add(child, &mut self.splitter); |
| 1147 | } |
| 1148 | top = self.record(level, chunker.finish(), None); |
| 1149 | } |
| 1150 | let mut root = top.pop().ok_or(TreeError::NotCanonical)?; |
| 1151 | // A root with one child is not one: the first level with one node |
| 1152 | // holds the root, so the levels that lost all but one node go. |
| 1153 | while level > 0 { |
| 1154 | let children = self.children_of(&root, level)?; |
| 1155 | if children.len() != 1 { |
| 1156 | break; |
| 1157 | } |
| 1158 | root = children.into_iter().next().ok_or(TreeError::NotCanonical)?; |
| 1159 | level -= 1; |
| 1160 | } |
| 1161 | if level == 0 || root.entry_count != entries { |
| 1162 | return Err(TreeError::NotCanonical); |
| 1163 | } |
| 1164 | let nodes = self |
| 1165 | .made |
| 1166 | .into_iter() |
| 1167 | .filter(|(made_level, ..)| *made_level <= level) |
| 1168 | .map(|(_, made, similar)| NewNode { |
| 1169 | id: made.child.node, |
| 1170 | bytes: made.bytes, |
| 1171 | similar, |
| 1172 | }) |
| 1173 | .collect(); |
| 1174 | Ok(Updated { |
| 1175 | root: root.node, |
| 1176 | entries, |
| 1177 | nodes, |
| 1178 | }) |
| 1179 | } |
| 1180 | |
| 1181 | /// Keeps the nodes a whole level was cut into, the ones that are new |
| 1182 | /// paired with `similar`, and returns the references to all of them. |
| 1183 | fn record(&mut self, level: u8, made: Vec<Made>, similar: Option<ObjectId>) -> Vec<Child> { |
| 1184 | made.into_iter() |
| 1185 | .map(|made| { |
| 1186 | let child = made.child.clone(); |
| 1187 | if Some(child.node) != similar { |
| 1188 | self.made.push((level, made, similar)); |
| 1189 | } |
| 1190 | child |
| 1191 | }) |
| 1192 | .collect() |
| 1193 | } |
| 1194 | |
| 1195 | /// The children of the internal node of `level` that `node` refers to, |
| 1196 | /// made by this update or read from the directory. |
| 1197 | fn children_of(&mut self, node: &Child, level: u8) -> Result<Vec<Child>, TreeError> { |
| 1198 | let found = match self |
| 1199 | .made |
| 1200 | .iter() |
| 1201 | .find(|(_, made, _)| made.child.node == node.node) |
| 1202 | { |
| 1203 | Some((_, made, _)) => Rc::new(Node::decode(&made.bytes)?), |
| 1204 | None => self.node(node.node)?, |
| 1205 | }; |
| 1206 | check_child(&found, level, node)?; |
| 1207 | Child::items(&found) |
| 1208 | .map(<[Child]>::to_vec) |
| 1209 | .ok_or(TreeError::NotCanonical) |
| 1210 | } |
| 1211 | |
| 1212 | /// The node of `level` before the update that holds `name`, or would: |
| 1213 | /// the first whose last name is at or after `name`, or the last node of |
| 1214 | /// the level for a name after every other. With `after`, the first whose |
| 1215 | /// last name is after `name`, if there is one. |
| 1216 | fn locate(&mut self, level: u8, name: &[u8], after: bool) -> Result<Option<Child>, TreeError> { |
| 1217 | if after && name >= self.root.last_name.as_slice() { |
| 1218 | return Ok(None); |
| 1219 | } |
| 1220 | let mut current = self.root.clone(); |
| 1221 | let mut at = self.height; |
| 1222 | while at > level { |
| 1223 | let node = self.node(current.node)?; |
| 1224 | check_child(&node, at, ¤t)?; |
| 1225 | let children = Child::items(&node).ok_or(TreeError::NotCanonical)?; |
| 1226 | let index = children.partition_point(|child| { |
| 1227 | if after { |
| 1228 | child.last_name.as_slice() <= name |
| 1229 | } else { |
| 1230 | child.last_name.as_slice() < name |
| 1231 | } |
| 1232 | }); |
| 1233 | current = match (children.get(index), after) { |
| 1234 | (Some(child), _) => child.clone(), |
| 1235 | (None, false) => children.last().ok_or(TreeError::NotCanonical)?.clone(), |
| 1236 | // The node above ends after `name`, so one of its children does. |
| 1237 | (None, true) => return Err(TreeError::NotCanonical), |
| 1238 | }; |
| 1239 | at -= 1; |
| 1240 | } |
| 1241 | Ok(Some(current)) |
| 1242 | } |
| 1243 | |
| 1244 | /// Applies `changes` to the level `level`, below the root, one run at a |
| 1245 | /// time, and returns the changes this makes to the level above, with |
| 1246 | /// how many entries the directory gained (lost, if negative). |
| 1247 | fn level<I: Item>( |
| 1248 | &mut self, |
| 1249 | level: u8, |
| 1250 | changes: ItemChanges<I>, |
| 1251 | ) -> Result<(ItemChanges<Child>, i128), TreeError> { |
| 1252 | let mut above = Vec::new(); |
| 1253 | let mut gained = 0i128; |
| 1254 | let mut changes = changes.into_iter().peekable(); |
| 1255 | while let Some((name, _)) = changes.peek() { |
| 1256 | // The run starts at the node that holds the first name left to |
| 1257 | // change, or would: every boundary before it stays. |
| 1258 | let mut old = self |
| 1259 | .locate(level, name, false)? |
| 1260 | .ok_or(TreeError::NotCanonical)?; |
| 1261 | let mut chunker = Chunker::new(level); |
| 1262 | let mut replaced: Vec<Child> = Vec::new(); |
| 1263 | loop { |
| 1264 | let node = self.node(old.node)?; |
| 1265 | check_child(&node, level, &old)?; |
| 1266 | let items = I::items(&node).ok_or(TreeError::NotCanonical)?; |
| 1267 | if let (Some(previous), Some(first)) = (replaced.last(), items.first()) |
| 1268 | && first.name() <= previous.last_name.as_slice() |
| 1269 | { |
| 1270 | return Err(TreeError::NotCanonical); |
| 1271 | } |
| 1272 | // The last node of the level also takes every name after it. |
| 1273 | let last = old.last_name == self.root.last_name; |
| 1274 | let mut index = 0; |
| 1275 | loop { |
| 1276 | let change = changes |
| 1277 | .peek() |
| 1278 | .map(|(name, _)| name.as_slice()) |
| 1279 | .filter(|name| last || *name <= old.last_name.as_slice()); |
| 1280 | let order = match (items.get(index), change) { |
| 1281 | (None, None) => break, |
| 1282 | (Some(_), None) => Ordering::Less, |
| 1283 | (None, Some(_)) => Ordering::Greater, |
| 1284 | (Some(item), Some(name)) => item.name().cmp(name), |
| 1285 | }; |
| 1286 | if order == Ordering::Greater { |
| 1287 | // A name the node does not have. |
| 1288 | if let Some((name, Some(new))) = changes.next() { |
| 1289 | gained += i128::from(new.entries()); |
| 1290 | let cut = self.splitter.ends(level, &name, chunker.next_count()); |
| 1291 | chunker.push(new, cut); |
| 1292 | } |
| 1293 | continue; |
| 1294 | } |
| 1295 | let item = &items[index]; |
| 1296 | index += 1; |
| 1297 | // The same name gives the same hash: compute it once, for |
| 1298 | // the old boundary and for the new one. |
| 1299 | let mut hit = None; |
| 1300 | let splitter = &mut self.splitter; |
| 1301 | let mut hit_of = |
| 1302 | || *hit.get_or_insert_with(|| splitter.hit(level, item.name())); |
| 1303 | let ended = ends(index, &mut hit_of); |
| 1304 | let boundary = match (index == items.len(), last) { |
| 1305 | (false, _) => Some(false), |
| 1306 | (true, false) => Some(true), |
| 1307 | // The end of the directory ends the last node anyway. |
| 1308 | (true, true) => None, |
| 1309 | }; |
| 1310 | if boundary.is_some_and(|boundary| boundary != ended) { |
| 1311 | return Err(TreeError::NotCanonical); |
| 1312 | } |
| 1313 | let new = match order { |
| 1314 | Ordering::Equal => { |
| 1315 | let (_, new) = changes.next().ok_or(TreeError::NotCanonical)?; |
| 1316 | gained -= i128::from(item.entries()); |
| 1317 | if let Some(new) = &new { |
| 1318 | gained += i128::from(new.entries()); |
| 1319 | } |
| 1320 | new |
| 1321 | } |
| 1322 | _ => Some(item.clone()), |
| 1323 | }; |
| 1324 | if let Some(new) = new { |
| 1325 | let cut = ends(chunker.next_count(), &mut hit_of); |
| 1326 | chunker.push(new, cut); |
| 1327 | } |
| 1328 | } |
| 1329 | replaced.push(old); |
| 1330 | if chunker.at_boundary() || last { |
| 1331 | // Cut where an old node was cut, or at the end of the |
| 1332 | // level: what follows is unchanged. |
| 1333 | break; |
| 1334 | } |
| 1335 | let after = replaced |
| 1336 | .last() |
| 1337 | .map(|node| node.last_name.clone()) |
| 1338 | .unwrap_or_default(); |
| 1339 | old = self |
| 1340 | .locate(level, &after, true)? |
| 1341 | .ok_or(TreeError::NotCanonical)?; |
| 1342 | } |
| 1343 | self.settle(level, &replaced, chunker.finish(), &mut above); |
| 1344 | } |
| 1345 | Ok((above, gained)) |
| 1346 | } |
| 1347 | |
| 1348 | /// Keeps the nodes a run of `level` made in place of the `replaced` ones, |
| 1349 | /// each paired with the old node that held its last name or would have, |
| 1350 | /// and adds what this changes to `above`, the level above. |
| 1351 | fn settle( |
| 1352 | &mut self, |
| 1353 | level: u8, |
| 1354 | replaced: &[Child], |
| 1355 | made: Vec<Made>, |
| 1356 | above: &mut ItemChanges<Child>, |
| 1357 | ) { |
| 1358 | let mut old = replaced.iter().peekable(); |
| 1359 | for made in made { |
| 1360 | let name = made.child.last_name.as_slice(); |
| 1361 | while let Some(gone) = old.next_if(|old| old.last_name.as_slice() < name) { |
| 1362 | above.push((gone.last_name.clone(), None)); |
| 1363 | } |
| 1364 | if old |
| 1365 | .next_if(|old| old.last_name.as_slice() == name) |
| 1366 | .is_some_and(|old| *old == made.child) |
| 1367 | { |
| 1368 | // The same node as before. |
| 1369 | continue; |
| 1370 | } |
| 1371 | let similar = replaced |
| 1372 | .iter() |
| 1373 | .find(|old| old.last_name.as_slice() >= name) |
| 1374 | .or(replaced.last()) |
| 1375 | .map(|old| old.node); |
| 1376 | above.push((made.child.last_name.clone(), Some(made.child.clone()))); |
| 1377 | self.made.push((level, made, similar)); |
| 1378 | } |
| 1379 | above.extend(old.map(|gone| (gone.last_name.clone(), None))); |
| 1380 | } |
| 1381 | |
| 1382 | /// Every entry of the directory before the update, in order, and its |
| 1383 | /// largest leaf. |
| 1384 | fn entries(&mut self) -> Result<(Vec<Entry>, Option<ObjectId>), TreeError> { |
| 1385 | let mut entries: Vec<Entry> = Vec::new(); |
| 1386 | let mut largest: Option<(usize, ObjectId)> = None; |
| 1387 | // No name sorts before the empty one. |
| 1388 | let mut next = self.locate(0, b"", false)?; |
| 1389 | while let Some(leaf) = next { |
| 1390 | let node = self.node(leaf.node)?; |
| 1391 | check_child(&node, 0, &leaf)?; |
| 1392 | let found = Entry::items(&node).ok_or(TreeError::NotCanonical)?; |
| 1393 | if let (Some(previous), Some(first)) = (entries.last(), found.first()) |
| 1394 | && first.name <= previous.name |
| 1395 | { |
| 1396 | return Err(TreeError::NotCanonical); |
| 1397 | } |
| 1398 | if largest.is_none_or(|(len, _)| found.len() > len) { |
| 1399 | largest = Some((found.len(), leaf.node)); |
| 1400 | } |
| 1401 | entries.extend_from_slice(found); |
| 1402 | next = self.locate(0, &leaf.last_name, true)?; |
| 1403 | } |
| 1404 | Ok((entries, largest.map(|(_, id)| id))) |
| 1405 | } |
| 1406 | } |
| 1407 | |
| 1408 | #[cfg(test)] |
| 1409 | mod tests { |
| 1410 | use super::*; |
| 1411 | |
| 1412 | fn blob(text: &str) -> ObjectId { |
| 1413 | ObjectId::hash(Kind::Blob, text.as_bytes()) |
| 1414 | } |
| 1415 | |
| 1416 | fn file(name: &str, text: &str) -> Entry { |
| 1417 | Entry { |
| 1418 | name: name.as_bytes().to_vec(), |
| 1419 | kind: EntryKind::File { |
| 1420 | blob: blob(text), |
| 1421 | size: text.len() as u64, |
| 1422 | }, |
| 1423 | } |
| 1424 | } |
| 1425 | |
| 1426 | fn many(n: usize, content: &str) -> Vec<Entry> { |
| 1427 | (0..n).map(|i| file(&format!("f{i:05}"), content)).collect() |
| 1428 | } |
| 1429 | |
| 1430 | #[test] |
| 1431 | fn empty_tree() { |
| 1432 | let dir = build_directory(Vec::new()).unwrap(); |
| 1433 | assert_eq!(dir.nodes.len(), 1); |
| 1434 | assert_eq!(dir.nodes[0].1, vec![FORMAT, NODE_FLAT, 0]); |
| 1435 | assert_eq!( |
| 1436 | dir.root().to_hex(), |
| 1437 | "3136b0f18562ee73b840ea348c54ae3c7e97e4cc3e547ea9dd03fa1cd8b384cf", |
| 1438 | "the empty tree id is part of format v1" |
| 1439 | ); |
| 1440 | } |
| 1441 | |
| 1442 | #[test] |
| 1443 | fn small_tree_golden() { |
| 1444 | let entries = vec![ |
| 1445 | file("README.md", "hello\n"), |
| 1446 | Entry { |
| 1447 | name: b"run.sh".to_vec(), |
| 1448 | kind: EntryKind::Executable { |
| 1449 | blob: blob("#!/bin/sh\n"), |
| 1450 | size: 10, |
| 1451 | }, |
| 1452 | }, |
| 1453 | Entry { |
| 1454 | name: b"latest".to_vec(), |
| 1455 | kind: EntryKind::Symlink { |
| 1456 | blob: blob("README.md"), |
| 1457 | size: 9, |
| 1458 | }, |
| 1459 | }, |
| 1460 | Entry { |
| 1461 | name: b"src".to_vec(), |
| 1462 | kind: EntryKind::Tree { |
| 1463 | tree: build_directory(Vec::new()).unwrap().root(), |
| 1464 | }, |
| 1465 | }, |
| 1466 | Entry { |
| 1467 | name: b"vendor".to_vec(), |
| 1468 | kind: EntryKind::Gitlink { |
| 1469 | commit: GitId::Sha1([0x11; 20]), |
| 1470 | }, |
| 1471 | }, |
| 1472 | ]; |
| 1473 | let dir = build_directory(entries).unwrap(); |
| 1474 | assert_eq!(dir.nodes.len(), 1); |
| 1475 | assert_eq!( |
| 1476 | dir.root().to_hex(), |
| 1477 | "a6c6d54bb7663d576e8f7a702e0670927e22098d6c15c10475e06b51dc3d8c1b" |
| 1478 | ); |
| 1479 | } |
| 1480 | |
| 1481 | #[test] |
| 1482 | fn flat_up_to_the_limit_then_split() { |
| 1483 | let flat = build_directory(many(MAX_FLAT_ENTRIES, "x")).unwrap(); |
| 1484 | assert_eq!(flat.nodes.len(), 1); |
| 1485 | assert!(matches!( |
| 1486 | Node::decode(&flat.nodes[0].1).unwrap(), |
| 1487 | Node::Flat(_) |
| 1488 | )); |
| 1489 | |
| 1490 | let split = build_directory(many(MAX_FLAT_ENTRIES + 1, "x")).unwrap(); |
| 1491 | assert!(split.nodes.len() >= 3); |
| 1492 | assert!(matches!( |
| 1493 | Node::decode(&split.nodes.last().unwrap().1).unwrap(), |
| 1494 | Node::Internal { .. } |
| 1495 | )); |
| 1496 | } |
| 1497 | |
| 1498 | #[test] |
| 1499 | fn large_tree_golden() { |
| 1500 | let dir = build_directory(many(5000, "x")).unwrap(); |
| 1501 | assert_eq!( |
| 1502 | dir.root().to_hex(), |
| 1503 | "2c88a412664c1fd862c3487e1313a045a20fe4f7bdeaf1bb71e08564edc7dcce" |
| 1504 | ); |
| 1505 | assert_eq!(dir.nodes.len(), LARGE_TREE_NODES); |
| 1506 | } |
| 1507 | |
| 1508 | const LARGE_TREE_NODES: usize = 30; |
| 1509 | |
| 1510 | #[test] |
| 1511 | fn read_back_and_reject_non_canonical_splits() { |
| 1512 | let entries = many(3000, "x"); |
| 1513 | let dir = build_directory(entries.clone()).unwrap(); |
| 1514 | let store: std::collections::HashMap<ObjectId, Vec<u8>> = |
| 1515 | dir.nodes.iter().cloned().collect(); |
| 1516 | let read = read_directory(dir.root(), |id| store.get(id).cloned()).unwrap(); |
| 1517 | assert_eq!(read, entries); |
| 1518 | |
| 1519 | // The same entries packed into one oversized flat node are refused. |
| 1520 | let fake = Node::Flat(entries.clone()); |
| 1521 | let bytes = fake.encode(); |
| 1522 | assert!(matches!( |
| 1523 | Node::decode(&bytes), |
| 1524 | Err(TreeError::BadNodeSize { .. }) |
| 1525 | )); |
| 1526 | |
| 1527 | // Two leaves split at the wrong place, under a hand-made root. |
| 1528 | let left = Node::Leaf(entries[..100].to_vec()); |
| 1529 | let right = Node::Leaf(entries[100..500].to_vec()); |
| 1530 | let root = Node::Internal { |
| 1531 | level: 1, |
| 1532 | children: vec![ |
| 1533 | Child { |
| 1534 | last_name: entries[99].name.clone(), |
| 1535 | node: left.id(), |
| 1536 | entry_count: 100, |
| 1537 | }, |
| 1538 | Child { |
| 1539 | last_name: entries[499].name.clone(), |
| 1540 | node: right.id(), |
| 1541 | entry_count: 400, |
| 1542 | }, |
| 1543 | ], |
| 1544 | }; |
| 1545 | let store: std::collections::HashMap<ObjectId, Vec<u8>> = [&left, &right, &root] |
| 1546 | .iter() |
| 1547 | .map(|n| (n.id(), n.encode())) |
| 1548 | .collect(); |
| 1549 | assert_eq!( |
| 1550 | read_directory(root.id(), |id| store.get(id).cloned()), |
| 1551 | Err(TreeError::NotCanonical) |
| 1552 | ); |
| 1553 | } |
| 1554 | |
| 1555 | #[test] |
| 1556 | fn decode_rejects_bad_input() { |
| 1557 | let unsorted = Node::Flat(vec![file("b", "1"), file("a", "2")]).encode(); |
| 1558 | assert_eq!( |
| 1559 | Node::decode(&unsorted), |
| 1560 | Err(TreeError::Unsorted { index: 1 }) |
| 1561 | ); |
| 1562 | let duplicate = Node::Flat(vec![file("a", "1"), file("a", "2")]).encode(); |
| 1563 | assert_eq!( |
| 1564 | Node::decode(&duplicate), |
| 1565 | Err(TreeError::Unsorted { index: 1 }) |
| 1566 | ); |
| 1567 | let reserved = Node::Flat(vec![file(".GIT", "1")]).encode(); |
| 1568 | assert!(matches!( |
| 1569 | Node::decode(&reserved), |
| 1570 | Err(TreeError::Name { .. }) |
| 1571 | )); |
| 1572 | let symlink = Node::Flat(vec![Entry { |
| 1573 | name: b".gitmodules".to_vec(), |
| 1574 | kind: EntryKind::Symlink { |
| 1575 | blob: blob("x"), |
| 1576 | size: 1, |
| 1577 | }, |
| 1578 | }]) |
| 1579 | .encode(); |
| 1580 | assert!(matches!( |
| 1581 | Node::decode(&symlink), |
| 1582 | Err(TreeError::SymlinkName(_)) |
| 1583 | )); |
| 1584 | let mut trailing = Node::Flat(vec![file("a", "1")]).encode(); |
| 1585 | trailing.push(0); |
| 1586 | assert!(matches!( |
| 1587 | Node::decode(&trailing), |
| 1588 | Err(TreeError::Decode(DecodeError::TrailingBytes { .. })) |
| 1589 | )); |
| 1590 | assert!(Node::decode(&[]).is_err()); |
| 1591 | assert!(Node::decode(&[2, 0, 0]).is_err()); |
| 1592 | assert!(Node::decode(&[FORMAT, 9]).is_err()); |
| 1593 | assert!(Node::decode(&[FORMAT, NODE_LEAF, 0]).is_err()); |
| 1594 | assert!(Node::decode(&[FORMAT, NODE_INTERNAL, 0, 0]).is_err()); |
| 1595 | } |
| 1596 | |
| 1597 | type Store = HashMap<ObjectId, Vec<u8>>; |
| 1598 | |
| 1599 | /// How `read_directory` checked a directory before it went node by node: |
| 1600 | /// it read every entry, built the directory again and compared the roots. |
| 1601 | fn read_by_building_again(root: ObjectId, store: &Store) -> Result<Vec<Entry>, TreeError> { |
| 1602 | fn collect( |
| 1603 | id: ObjectId, |
| 1604 | store: &Store, |
| 1605 | entries: &mut Vec<Entry>, |
| 1606 | expected_level: Option<u8>, |
| 1607 | ) -> Result<(), TreeError> { |
| 1608 | let bytes = store.get(&id).ok_or(TreeError::MissingNode(id))?; |
| 1609 | match (Node::decode(bytes)?, expected_level) { |
| 1610 | (Node::Flat(found), None) => entries.extend(found), |
| 1611 | (Node::Leaf(found), Some(0)) => entries.extend(found), |
| 1612 | (Node::Internal { level, children }, expected) |
| 1613 | if expected.is_none_or(|e| e == level) => |
| 1614 | { |
| 1615 | for child in children { |
| 1616 | collect(child.node, store, entries, Some(level - 1))?; |
| 1617 | } |
| 1618 | } |
| 1619 | _ => return Err(TreeError::NotCanonical), |
| 1620 | } |
| 1621 | Ok(()) |
| 1622 | } |
| 1623 | let mut entries = Vec::new(); |
| 1624 | collect(root, store, &mut entries, None)?; |
| 1625 | if build_directory(entries.clone())?.root() != root { |
| 1626 | return Err(TreeError::NotCanonical); |
| 1627 | } |
| 1628 | Ok(entries) |
| 1629 | } |
| 1630 | |
| 1631 | /// A directory always split, its nodes cut where `cut` says, given the |
| 1632 | /// level, the number of items the node would hold and whether the name |
| 1633 | /// hashes below the threshold; nodes never grow past the limit. |
| 1634 | fn cut_with( |
| 1635 | entries: Vec<Entry>, |
| 1636 | mut cut: impl FnMut(u8, usize, bool) -> bool, |
| 1637 | ) -> (ObjectId, Store) { |
| 1638 | fn level<I: Item>( |
| 1639 | level: u8, |
| 1640 | items: Vec<I>, |
| 1641 | store: &mut Store, |
| 1642 | cut: &mut impl FnMut(u8, usize, bool) -> bool, |
| 1643 | ) -> Vec<Child> { |
| 1644 | let mut splitter = Splitter::new(); |
| 1645 | let mut chunker = Chunker::new(level); |
| 1646 | for item in items { |
| 1647 | let count = chunker.next_count(); |
| 1648 | let hit = splitter.hit(level, item.name()); |
| 1649 | let ends = cut(level, count, hit) || count >= MAX_NODE_ENTRIES; |
| 1650 | chunker.push(item, ends); |
| 1651 | } |
| 1652 | chunker |
| 1653 | .finish() |
| 1654 | .into_iter() |
| 1655 | .map(|made| { |
| 1656 | store.insert(made.child.node, made.bytes); |
| 1657 | made.child |
| 1658 | }) |
| 1659 | .collect() |
| 1660 | } |
| 1661 | let mut store = Store::new(); |
| 1662 | let mut children = level(0, entries, &mut store, &mut cut); |
| 1663 | let mut at = 1; |
| 1664 | while children.len() > 1 { |
| 1665 | children = level(at, children, &mut store, &mut cut); |
| 1666 | at += 1; |
| 1667 | } |
| 1668 | (children[0].node, store) |
| 1669 | } |
| 1670 | |
| 1671 | /// Ways to cut the nodes of one level other than by the splitting rule, |
| 1672 | /// which the others follow. |
| 1673 | #[derive(Clone, Copy, Debug)] |
| 1674 | enum Cut { |
| 1675 | /// The splitting rule everywhere. |
| 1676 | Rule, |
| 1677 | /// The `k`th cut of the rule is not made. |
| 1678 | Skip(usize), |
| 1679 | /// A cut after the `k`th item of the level, besides the rule's. |
| 1680 | Extra(usize), |
| 1681 | /// The `k`th cut of the rule is made one item later. |
| 1682 | Late(usize), |
| 1683 | /// Cut wherever a name hashes below the threshold, however few items |
| 1684 | /// the node holds. |
| 1685 | NoMinimum, |
| 1686 | /// Nodes of `k` items. |
| 1687 | Fixed(usize), |
| 1688 | } |
| 1689 | |
| 1690 | fn cutter(target: u8, way: Cut) -> impl FnMut(u8, usize, bool) -> bool { |
| 1691 | let (mut cuts, mut items, mut late) = (0, 0, false); |
| 1692 | move |level, count, hit| { |
| 1693 | let rule = ends(count, || hit); |
| 1694 | if level != target { |
| 1695 | return rule; |
| 1696 | } |
| 1697 | items += 1; |
| 1698 | cuts += usize::from(rule); |
| 1699 | match way { |
| 1700 | Cut::Rule => rule, |
| 1701 | Cut::Skip(k) => rule && cuts != k, |
| 1702 | Cut::Extra(k) => rule || items == k, |
| 1703 | Cut::Late(k) => { |
| 1704 | if std::mem::take(&mut late) { |
| 1705 | return true; |
| 1706 | } |
| 1707 | late = rule && cuts == k; |
| 1708 | rule && !late |
| 1709 | } |
| 1710 | Cut::NoMinimum => hit, |
| 1711 | Cut::Fixed(k) => count >= k, |
| 1712 | } |
| 1713 | } |
| 1714 | } |
| 1715 | |
| 1716 | fn cut() -> impl proptest::strategy::Strategy<Value = Cut> { |
| 1717 | use proptest::prelude::*; |
| 1718 | prop_oneof![ |
| 1719 | Just(Cut::Rule), |
| 1720 | (1usize..40).prop_map(Cut::Skip), |
| 1721 | (1usize..4_000).prop_map(Cut::Extra), |
| 1722 | (1usize..40).prop_map(Cut::Late), |
| 1723 | Just(Cut::NoMinimum), |
| 1724 | (1usize..=MAX_NODE_ENTRIES).prop_map(Cut::Fixed), |
| 1725 | ] |
| 1726 | } |
| 1727 | |
| 1728 | proptest::proptest! { |
| 1729 | #![proptest_config(proptest::prelude::ProptestConfig::with_cases(48))] |
| 1730 | |
| 1731 | /// Checking node by node accepts and refuses exactly the trees that |
| 1732 | /// building again and comparing did, whichever way their nodes are cut. |
| 1733 | #[test] |
| 1734 | fn reading_checks_what_building_again_checked( |
| 1735 | count in 900usize..4_000, |
| 1736 | seed in proptest::prelude::any::<u64>(), |
| 1737 | target in 0u8..3, |
| 1738 | way in cut(), |
| 1739 | ) { |
| 1740 | let entries: Vec<Entry> = (0..count as u64) |
| 1741 | .map(|i| { |
| 1742 | let name = format!("{:x}-{i}", seed.wrapping_mul(i + 1) % 7919); |
| 1743 | (name.clone(), file(&name, "x")) |
| 1744 | }) |
| 1745 | .collect::<std::collections::BTreeMap<_, _>>() |
| 1746 | .into_values() |
| 1747 | .collect(); |
| 1748 | let (root, store) = cut_with(entries.clone(), cutter(target, way)); |
| 1749 | let fetch = |id: &ObjectId| store.get(id).cloned(); |
| 1750 | let read = read_directory(root, fetch); |
| 1751 | proptest::prop_assert_eq!(&read, &read_by_building_again(root, &store)); |
| 1752 | if matches!(way, Cut::Rule) && entries.len() > MAX_FLAT_ENTRIES { |
| 1753 | proptest::prop_assert_eq!(read, Ok(entries)); |
| 1754 | } |
| 1755 | } |
| 1756 | } |
| 1757 | |
| 1758 | #[test] |
| 1759 | fn reading_refuses_a_root_with_one_child() { |
| 1760 | let dir = build_directory(many(3_000, "x")).unwrap(); |
| 1761 | let root = dir.root(); |
| 1762 | let mut store: Store = dir.nodes.into_iter().collect(); |
| 1763 | let Node::Internal { level, children } = Node::decode(&store[&root]).unwrap() else { |
| 1764 | panic!("split"); |
| 1765 | }; |
| 1766 | let above = Node::Internal { |
| 1767 | level: level + 1, |
| 1768 | children: vec![Child { |
| 1769 | last_name: children.last().unwrap().last_name.clone(), |
| 1770 | node: root, |
| 1771 | entry_count: 3_000, |
| 1772 | }], |
| 1773 | }; |
| 1774 | store.insert(above.id(), above.encode()); |
| 1775 | let fetch = |id: &ObjectId| store.get(id).cloned(); |
| 1776 | assert_eq!( |
| 1777 | read_directory(above.id(), fetch), |
| 1778 | Err(TreeError::NotCanonical) |
| 1779 | ); |
| 1780 | assert_eq!( |
| 1781 | read_by_building_again(above.id(), &store), |
| 1782 | Err(TreeError::NotCanonical) |
| 1783 | ); |
| 1784 | } |
| 1785 | } |