| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! Every object a set of changesets reaches: what a client needs to hold |
| 5 | //! them, or what a server lacks of them. |
| 6 | //! |
| 7 | //! From each changeset the walk takes the changeset itself, its external |
| 8 | //! change list, the blob holding its original git commit, and every node |
| 9 | //! and blob of its root tree; then, as far as `history` says, its parents. |
| 10 | //! Changesets in `have` are not walked, and the nodes and blobs of their |
| 11 | //! root trees are left out of the result: whoever asks holds them. A walk |
| 12 | //! of the whole history also skips every ancestor of a `have` changeset, |
| 13 | //! so that the second parent of a merge does not lead it back down a |
| 14 | //! history the asker holds; finding them reads every changeset `have` |
| 15 | //! reaches, and nothing else. |
| 16 | |
| 17 | use std::collections::{HashSet, VecDeque}; |
| 18 | |
| 19 | use braid_format::changeset::Changes; |
| 20 | use braid_format::tree::{EntryKind, Node}; |
| 21 | use braid_format::{Changeset, Kind, ObjectId, Objects}; |
| 22 | |
| 23 | use crate::access::{EMPTY_TREE, read_object}; |
| 24 | use crate::error::{Error, store_error}; |
| 25 | |
| 26 | /// What to walk. |
| 27 | #[derive(Clone, Debug, Default)] |
| 28 | pub struct Reach<'a> { |
| 29 | /// The changesets wanted. |
| 30 | pub want: &'a [ObjectId], |
| 31 | /// Changesets already held with everything they reach. |
| 32 | pub have: &'a [ObjectId], |
| 33 | /// `None` for every ancestor, `Some(0)` for the wanted changesets |
| 34 | /// alone, `Some(n)` for n generations along all parents. |
| 35 | pub history: Option<u32>, |
| 36 | /// When given, only the parts of trees on the way to or under one of |
| 37 | /// these path prefixes (`/`-separated, no leading or trailing `/`). |
| 38 | pub paths: Option<&'a [Vec<u8>]>, |
| 39 | /// When given, the walk stops with [`Error::TooManyObjects`] as soon as |
| 40 | /// it would list more objects than this, so that a server answering |
| 41 | /// for others bounds the work and the memory of one request. |
| 42 | pub max_objects: Option<usize>, |
| 43 | } |
| 44 | |
| 45 | /// One object reached: its id, kind and size in bytes. |
| 46 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 47 | pub struct Reached { |
| 48 | /// The object's id. |
| 49 | pub id: ObjectId, |
| 50 | /// Its kind. |
| 51 | pub kind: Kind, |
| 52 | /// Its size in bytes, decoded. |
| 53 | pub size: u64, |
| 54 | } |
| 55 | |
| 56 | /// Lists every object `reach` reaches, each once: a changeset before the |
| 57 | /// objects it names, a tree node before what it holds. The empty tree is |
| 58 | /// never listed: everyone has it. |
| 59 | /// |
| 60 | /// With [`Reach::max_objects`], neither the list nor the objects of the |
| 61 | /// `have` root trees may grow past that many, or the walk stops with |
| 62 | /// [`Error::TooManyObjects`]. |
| 63 | pub fn reachable<O: Objects>(objects: &O, reach: &Reach<'_>) -> Result<Vec<Reached>, Error> { |
| 64 | let mut walk = Walk { |
| 65 | objects, |
| 66 | paths: reach.paths, |
| 67 | max: reach.max_objects, |
| 68 | seen: HashSet::new(), |
| 69 | out: Vec::new(), |
| 70 | }; |
| 71 | // What the asker holds: the `have` changesets, with all their ancestors |
| 72 | // when the walk could reach them, and the nodes and blobs of every |
| 73 | // `have` root tree. |
| 74 | let stop = match reach.history { |
| 75 | None => ancestors(objects, reach.have)?, |
| 76 | Some(_) => reach.have.iter().copied().collect(), |
| 77 | }; |
| 78 | let mut known = Walk { |
| 79 | objects, |
| 80 | paths: None, |
| 81 | max: reach.max_objects, |
| 82 | seen: HashSet::new(), |
| 83 | out: Vec::new(), |
| 84 | }; |
| 85 | for have in reach.have { |
| 86 | if let Some((Kind::Changeset, bytes)) = objects.get(have).map_err(store_error)? { |
| 87 | let changeset = |
| 88 | Changeset::decode(&bytes).map_err(|error| Error::Changeset { id: *have, error })?; |
| 89 | known.tree(changeset.root, &[])?; |
| 90 | } |
| 91 | } |
| 92 | walk.seen = known.seen; |
| 93 | |
| 94 | let mut queue: VecDeque<(ObjectId, u32)> = VecDeque::new(); |
| 95 | let mut queued: HashSet<ObjectId> = HashSet::new(); |
| 96 | for id in reach.want { |
| 97 | if !stop.contains(id) && queued.insert(*id) { |
| 98 | queue.push_back((*id, 0)); |
| 99 | } |
| 100 | } |
| 101 | while let Some((id, depth)) = queue.pop_front() { |
| 102 | let bytes = read_object(objects, id, Kind::Changeset)?; |
| 103 | let changeset = |
| 104 | Changeset::decode(&bytes).map_err(|error| Error::Changeset { id, error })?; |
| 105 | walk.emit(id, Kind::Changeset, bytes.len() as u64)?; |
| 106 | if let Changes::External { list, .. } = &changeset.changes { |
| 107 | walk.object(*list, Kind::Blob)?; |
| 108 | } |
| 109 | if let Some(origin) = changeset.git_origin { |
| 110 | walk.object(origin, Kind::Blob)?; |
| 111 | } |
| 112 | walk.tree(changeset.root, &[])?; |
| 113 | let deeper = reach.history.is_none_or(|limit| depth < limit); |
| 114 | if deeper { |
| 115 | for parent in &changeset.parents { |
| 116 | if !stop.contains(parent) && queued.insert(*parent) { |
| 117 | queue.push_back((*parent, depth + 1)); |
| 118 | } |
| 119 | } |
| 120 | } |
| 121 | } |
| 122 | Ok(walk.out) |
| 123 | } |
| 124 | |
| 125 | /// `have` and every ancestor of it, along all parents, among the |
| 126 | /// changesets stored: an id that is not a stored changeset is kept, and not |
| 127 | /// walked. |
| 128 | fn ancestors<O: Objects>(objects: &O, have: &[ObjectId]) -> Result<HashSet<ObjectId>, Error> { |
| 129 | let mut found: HashSet<ObjectId> = HashSet::new(); |
| 130 | let mut pending: Vec<ObjectId> = have.to_vec(); |
| 131 | while let Some(id) = pending.pop() { |
| 132 | if !found.insert(id) { |
| 133 | continue; |
| 134 | } |
| 135 | if let Some((Kind::Changeset, bytes)) = objects.get(&id).map_err(store_error)? { |
| 136 | let changeset = |
| 137 | Changeset::decode(&bytes).map_err(|error| Error::Changeset { id, error })?; |
| 138 | pending.extend( |
| 139 | changeset |
| 140 | .parents |
| 141 | .iter() |
| 142 | .filter(|parent| !found.contains(parent)), |
| 143 | ); |
| 144 | } |
| 145 | } |
| 146 | Ok(found) |
| 147 | } |
| 148 | |
| 149 | struct Walk<'a, O> { |
| 150 | objects: &'a O, |
| 151 | paths: Option<&'a [Vec<u8>]>, |
| 152 | /// The most objects `out` may hold. |
| 153 | max: Option<usize>, |
| 154 | seen: HashSet<ObjectId>, |
| 155 | out: Vec<Reached>, |
| 156 | } |
| 157 | |
| 158 | impl<O: Objects> Walk<'_, O> { |
| 159 | fn emit(&mut self, id: ObjectId, kind: Kind, size: u64) -> Result<(), Error> { |
| 160 | if self.seen.insert(id) { |
| 161 | if let Some(limit) = self.max |
| 162 | && self.out.len() >= limit |
| 163 | { |
| 164 | return Err(Error::TooManyObjects { limit }); |
| 165 | } |
| 166 | self.out.push(Reached { id, kind, size }); |
| 167 | } |
| 168 | Ok(()) |
| 169 | } |
| 170 | |
| 171 | /// A whole object whose size is not known yet. |
| 172 | fn object(&mut self, id: ObjectId, kind: Kind) -> Result<(), Error> { |
| 173 | if self.seen.contains(&id) { |
| 174 | return Ok(()); |
| 175 | } |
| 176 | match self.objects.stat(&id).map_err(store_error)? { |
| 177 | Some((found, size)) if found == kind => self.emit(id, kind, size), |
| 178 | Some((found, _)) => Err(Error::WrongKind { |
| 179 | id, |
| 180 | expected: kind, |
| 181 | found, |
| 182 | }), |
| 183 | None => Err(Error::Missing { id, kind }), |
| 184 | } |
| 185 | } |
| 186 | |
| 187 | /// Whether anything at `path` (a directory or a file) can be wanted. |
| 188 | fn wanted(&self, path: &[u8]) -> bool { |
| 189 | let Some(prefixes) = self.paths else { |
| 190 | return true; |
| 191 | }; |
| 192 | prefixes.iter().any(|prefix| { |
| 193 | // On the way to the prefix, or under it. |
| 194 | let on_the_way = prefix.starts_with(path) |
| 195 | && (prefix.len() == path.len() || path.is_empty() || prefix[path.len()] == b'/'); |
| 196 | let under = path.starts_with(prefix) |
| 197 | && (path.len() == prefix.len() || prefix.is_empty() || path[prefix.len()] == b'/'); |
| 198 | on_the_way || under |
| 199 | }) |
| 200 | } |
| 201 | |
| 202 | /// A tree node and what it holds; `dir` is the directory's path. |
| 203 | fn tree(&mut self, node: ObjectId, dir: &[u8]) -> Result<(), Error> { |
| 204 | if node == EMPTY_TREE || self.seen.contains(&node) { |
| 205 | return Ok(()); |
| 206 | } |
| 207 | let bytes = read_object(self.objects, node, Kind::Tree)?; |
| 208 | let decoded = Node::decode(&bytes).map_err(|error| Error::Tree { id: node, error })?; |
| 209 | self.emit(node, Kind::Tree, bytes.len() as u64)?; |
| 210 | match decoded { |
| 211 | Node::Flat(entries) | Node::Leaf(entries) => { |
| 212 | for entry in entries { |
| 213 | let path = if dir.is_empty() { |
| 214 | entry.name.clone() |
| 215 | } else { |
| 216 | [dir, b"/", &entry.name].concat() |
| 217 | }; |
| 218 | if !self.wanted(&path) { |
| 219 | continue; |
| 220 | } |
| 221 | match entry.kind { |
| 222 | EntryKind::File { blob, size } |
| 223 | | EntryKind::Executable { blob, size } |
| 224 | | EntryKind::Symlink { blob, size } => self.emit(blob, Kind::Blob, size)?, |
| 225 | EntryKind::Tree { tree } => self.tree(tree, &path)?, |
| 226 | EntryKind::Gitlink { .. } => {} |
| 227 | } |
| 228 | } |
| 229 | } |
| 230 | Node::Internal { children, .. } => { |
| 231 | for child in children { |
| 232 | self.tree(child.node, dir)?; |
| 233 | } |
| 234 | } |
| 235 | } |
| 236 | Ok(()) |
| 237 | } |
| 238 | } |
| 239 | |
| 240 | #[cfg(test)] |
| 241 | mod tests { |
| 242 | use super::*; |
| 243 | use crate::testing::Repo; |
| 244 | use braid_format::MemoryObjects; |
| 245 | |
| 246 | fn ids(reached: &[Reached]) -> HashSet<ObjectId> { |
| 247 | reached.iter().map(|r| r.id).collect() |
| 248 | } |
| 249 | |
| 250 | /// Copies what `reached` lists into a fresh store. |
| 251 | fn copy(from: &MemoryObjects, reached: &[Reached]) -> MemoryObjects { |
| 252 | let to = MemoryObjects::new(); |
| 253 | for r in reached { |
| 254 | let (kind, bytes) = from.get(&r.id).unwrap().unwrap(); |
| 255 | assert_eq!(kind, r.kind); |
| 256 | assert_eq!(bytes.len() as u64, r.size, "{:?}", r.kind); |
| 257 | to.put(kind, &bytes).unwrap(); |
| 258 | } |
| 259 | to |
| 260 | } |
| 261 | |
| 262 | #[test] |
| 263 | fn everything_a_history_needs_and_nothing_twice() { |
| 264 | let repo = Repo::new(); |
| 265 | let one = repo.commit( |
| 266 | &[], |
| 267 | vec![repo.set("a.txt", "1\n"), repo.set("src/lib.rs", "x\n")], |
| 268 | ); |
| 269 | let two = repo.commit(&[one], vec![repo.set("a.txt", "2\n")]); |
| 270 | let three = repo.commit(&[two], vec![repo.set("src/main.rs", "y\n")]); |
| 271 | let all = reachable( |
| 272 | &repo.objects, |
| 273 | &Reach { |
| 274 | want: &[three], |
| 275 | ..Reach::default() |
| 276 | }, |
| 277 | ) |
| 278 | .unwrap(); |
| 279 | assert_eq!(all.len(), ids(&all).len(), "listed once"); |
| 280 | assert_eq!(all[0].id, three, "a changeset first"); |
| 281 | // A store holding only what was listed reads every changeset and tree. |
| 282 | let copied = copy(&repo.objects, &all); |
| 283 | for changeset in [one, two, three] { |
| 284 | let read = crate::read_changeset(&copied, changeset).unwrap(); |
| 285 | crate::read_tree(&copied, read.root).unwrap(); |
| 286 | } |
| 287 | // The blob "x" is shared by all three trees and listed once. |
| 288 | let x = repo.blob("x\n"); |
| 289 | assert_eq!(all.iter().filter(|r| r.id == x).count(), 1); |
| 290 | } |
| 291 | |
| 292 | #[test] |
| 293 | fn have_and_history_cut_the_walk() { |
| 294 | let repo = Repo::new(); |
| 295 | let one = repo.commit( |
| 296 | &[], |
| 297 | vec![repo.set("a.txt", "1\n"), repo.set("b.txt", "b\n")], |
| 298 | ); |
| 299 | let two = repo.commit(&[one], vec![repo.set("a.txt", "2\n")]); |
| 300 | let three = repo.commit(&[two], vec![repo.set("a.txt", "3\n")]); |
| 301 | // Holding two: only three and what it adds. |
| 302 | let new = reachable( |
| 303 | &repo.objects, |
| 304 | &Reach { |
| 305 | want: &[three], |
| 306 | have: &[two], |
| 307 | ..Reach::default() |
| 308 | }, |
| 309 | ) |
| 310 | .unwrap(); |
| 311 | let new = ids(&new); |
| 312 | assert!(new.contains(&three)); |
| 313 | assert!(!new.contains(&two) && !new.contains(&one)); |
| 314 | assert!(new.contains(&repo.blob("3\n"))); |
| 315 | assert!(!new.contains(&repo.blob("b\n")), "b.txt is in two's tree"); |
| 316 | // history 0: the wanted changeset alone. |
| 317 | let only = reachable( |
| 318 | &repo.objects, |
| 319 | &Reach { |
| 320 | want: &[three], |
| 321 | history: Some(0), |
| 322 | ..Reach::default() |
| 323 | }, |
| 324 | ) |
| 325 | .unwrap(); |
| 326 | let only = ids(&only); |
| 327 | assert!(only.contains(&three) && !only.contains(&two)); |
| 328 | // history 1: one generation more. |
| 329 | let one_more = reachable( |
| 330 | &repo.objects, |
| 331 | &Reach { |
| 332 | want: &[three], |
| 333 | history: Some(1), |
| 334 | ..Reach::default() |
| 335 | }, |
| 336 | ) |
| 337 | .unwrap(); |
| 338 | let one_more = ids(&one_more); |
| 339 | assert!(one_more.contains(&two) && !one_more.contains(&one)); |
| 340 | } |
| 341 | |
| 342 | #[test] |
| 343 | fn a_merge_does_not_lead_back_into_what_is_held() { |
| 344 | let repo = Repo::new(); |
| 345 | let root = repo.commit(&[], vec![repo.set("a.txt", "0\n")]); |
| 346 | let side = repo.commit(&[root], vec![repo.set("side.txt", "s\n")]); |
| 347 | let held = repo.commit(&[root], vec![repo.set("a.txt", "1\n")]); |
| 348 | // A merge of the side branch on top of what the asker holds. |
| 349 | let merge = repo.commit(&[held, side], vec![repo.set("side.txt", "s\n")]); |
| 350 | let new = reachable( |
| 351 | &repo.objects, |
| 352 | &Reach { |
| 353 | want: &[merge], |
| 354 | have: &[held], |
| 355 | ..Reach::default() |
| 356 | }, |
| 357 | ) |
| 358 | .unwrap(); |
| 359 | let new = ids(&new); |
| 360 | assert!(new.contains(&merge) && new.contains(&side)); |
| 361 | assert!(!new.contains(&root), "an ancestor of what is held"); |
| 362 | assert!(!new.contains(&held)); |
| 363 | // Unknown ids in `have` are ignored. |
| 364 | let unknown = ObjectId::hash(Kind::Changeset, b"unknown"); |
| 365 | let all = reachable( |
| 366 | &repo.objects, |
| 367 | &Reach { |
| 368 | want: &[merge], |
| 369 | have: &[unknown], |
| 370 | ..Reach::default() |
| 371 | }, |
| 372 | ) |
| 373 | .unwrap(); |
| 374 | assert!(ids(&all).contains(&root)); |
| 375 | } |
| 376 | |
| 377 | #[test] |
| 378 | fn paths_keep_the_way_and_what_is_under() { |
| 379 | let repo = Repo::new(); |
| 380 | let head = repo.commit( |
| 381 | &[], |
| 382 | vec![ |
| 383 | repo.set("README", "r\n"), |
| 384 | repo.set("src/net/tcp.rs", "tcp\n"), |
| 385 | repo.set("src/net/udp.rs", "udp\n"), |
| 386 | repo.set("src/fs/io.rs", "io\n"), |
| 387 | repo.set("srcx/other.rs", "other\n"), |
| 388 | ], |
| 389 | ); |
| 390 | let paths = vec![b"src/net".to_vec()]; |
| 391 | let some = reachable( |
| 392 | &repo.objects, |
| 393 | &Reach { |
| 394 | want: &[head], |
| 395 | history: Some(0), |
| 396 | paths: Some(&paths), |
| 397 | ..Reach::default() |
| 398 | }, |
| 399 | ) |
| 400 | .unwrap(); |
| 401 | let some = ids(&some); |
| 402 | assert!(some.contains(&repo.blob("tcp\n"))); |
| 403 | assert!(some.contains(&repo.blob("udp\n"))); |
| 404 | for left_out in ["r\n", "io\n", "other\n"] { |
| 405 | assert!(!some.contains(&repo.blob(left_out)), "{left_out}"); |
| 406 | } |
| 407 | } |
| 408 | |
| 409 | #[test] |
| 410 | fn a_walk_stops_at_its_limit() { |
| 411 | let repo = Repo::new(); |
| 412 | let one = repo.commit(&[], vec![repo.set("a.txt", "1\n")]); |
| 413 | let two = repo.commit(&[one], vec![repo.set("b.txt", "2\n")]); |
| 414 | let walk = |max_objects, have: &[ObjectId]| { |
| 415 | reachable( |
| 416 | &repo.objects, |
| 417 | &Reach { |
| 418 | want: &[two], |
| 419 | have, |
| 420 | max_objects, |
| 421 | ..Reach::default() |
| 422 | }, |
| 423 | ) |
| 424 | }; |
| 425 | let all = walk(None, &[]).unwrap(); |
| 426 | assert_eq!(walk(Some(all.len()), &[]).unwrap(), all); |
| 427 | assert!(matches!( |
| 428 | walk(Some(all.len() - 1), &[]), |
| 429 | Err(Error::TooManyObjects { limit }) if limit == all.len() - 1 |
| 430 | )); |
| 431 | // The objects of what the asker holds count too: one's tree has a |
| 432 | // node and a blob. |
| 433 | assert!(matches!( |
| 434 | walk(Some(1), &[one]), |
| 435 | Err(Error::TooManyObjects { limit: 1 }) |
| 436 | )); |
| 437 | } |
| 438 | |
| 439 | #[test] |
| 440 | fn a_missing_object_is_an_error() { |
| 441 | let repo = Repo::new(); |
| 442 | let head = repo.commit(&[], vec![repo.set("a.txt", "1\n")]); |
| 443 | let (_, bytes) = repo.objects.get(&head).unwrap().unwrap(); |
| 444 | let partial = MemoryObjects::new(); |
| 445 | partial.put(Kind::Changeset, &bytes).unwrap(); |
| 446 | assert!(matches!( |
| 447 | reachable( |
| 448 | &partial, |
| 449 | &Reach { |
| 450 | want: &[head], |
| 451 | ..Reach::default() |
| 452 | } |
| 453 | ), |
| 454 | Err(Error::Missing { .. }) |
| 455 | )); |
| 456 | } |
| 457 | } |