Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 18.0 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! Creating changesets, and the admission check a store runs before it
5//! accepts one.
6
7use braid_format::changeset::Assembled;
8use braid_format::{Change, ChangeOp, ChangesetParts, Kind, ObjectId, Objects, Signature};
9
10use crate::access::{
11 EMPTY_TREE, Trees, empty_tree_node, read_changes, read_changeset, stat_object,
12};
13use crate::apply::{apply, apply_sorted, check_nodes, first_problem};
14use crate::error::{Error, store_error};
15
16/// Creates a changeset: applies `changes` to the root tree of `parents[0]`
17/// (the empty tree when there are no parents), stores the new directories,
18/// the changeset, and its change-list blob when the list is too long to be
19/// inline. Returns the changeset's id.
20///
21/// The blobs the changes refer to must be stored by the caller; the admission
22/// check requires them.
23pub fn commit<O: Objects>(
24 objects: &O,
25 parents: Vec<ObjectId>,
26 changes: Vec<Change>,
27 author: Signature,
28 committer: Signature,
29 message: Vec<u8>,
30 extras: Vec<(Vec<u8>, Vec<u8>)>,
31) -> Result<ObjectId, Error> {
32 let base_root = match parents.first() {
33 Some(parent) => read_changeset(objects, *parent)?.root,
34 None => EMPTY_TREE,
35 };
36 let root = apply(objects, base_root, &changes)?;
37 if root == EMPTY_TREE {
38 // Not rebuilt when nothing changed, and never stored by a parent.
39 objects
40 .put(Kind::Tree, &empty_tree_node())
41 .map_err(store_error)?;
42 }
43 let assembled = ChangesetParts {
44 parents,
45 root,
46 changes,
47 author,
48 committer,
49 message,
50 extras,
51 git_origin: None,
52 }
53 .assemble()
54 .map_err(Error::Assemble)?;
55 store_assembled(objects, &assembled)?;
56 Ok(assembled.id)
57}
58
59/// Stores an assembled changeset, its change-list blob first.
60pub(crate) fn store_assembled<O: Objects>(objects: &O, assembled: &Assembled) -> Result<(), Error> {
61 if let Some((_, list)) = &assembled.external_list {
62 objects.put(Kind::Blob, list).map_err(store_error)?;
63 }
64 objects
65 .put(Kind::Changeset, &assembled.encoded)
66 .map_err(store_error)?;
67 Ok(())
68}
69
70/// The admission check: whether a store may accept the changeset `id`.
71///
72/// Every parent must already be admitted, as `is_admitted` says. The change
73/// list must be canonical: sorted, without duplicates or no-ops, and stored
74/// in its own blob only when it is too long to be inline. Applied to the root
75/// tree of the first parent (or the empty tree), it must give exactly the root
76/// the changeset declares, and no path may be deeper than
77/// [`MAX_PATH_DEPTH`](crate::MAX_PATH_DEPTH), so no admitted tree is deeper
78/// either. Every blob a change refers to must be stored, with the size the
79/// change gives it, as must the blob of the original git commit, and every
80/// directory the change rebuilds, byte for byte.
81///
82/// The cost follows the size of the change: only the directories on changed
83/// paths are read. Blobs are checked by kind and size with
84/// [`Objects::stat`], never read.
85///
86/// Returns `Ok(())` when the changeset is admissible. An error other than
87/// [`Error::Store`] says why it is not.
88pub fn admit<O: Objects>(
89 objects: &O,
90 id: ObjectId,
91 is_admitted: impl Fn(&ObjectId) -> bool,
92) -> Result<(), Error> {
93 let changeset = read_changeset(objects, id)?;
94 if let Some(parent) = changeset.parents.iter().find(|parent| !is_admitted(parent)) {
95 return Err(Error::ParentNotAdmitted {
96 changeset: id,
97 parent: *parent,
98 });
99 }
100 // Decoding checked the order, the paths, and the length of an inline list.
101 let changes = read_changes(objects, id, &changeset)?;
102 let base_root = match changeset.parents.first() {
103 Some(parent) => read_changeset(objects, *parent)?.root,
104 None => EMPTY_TREE,
105 };
106
107 let mut trees = Trees::new(objects);
108 let sorted: Vec<&Change> = changes.iter().collect();
109 let mut problems = Vec::new();
110 let applied = apply_sorted(&mut trees, base_root, &sorted, &mut problems)?;
111 if let Some(problem) = first_problem(problems) {
112 return Err(problem.into_error());
113 }
114 if applied.root != changeset.root {
115 return Err(Error::RootMismatch {
116 changeset: id,
117 declared: changeset.root,
118 computed: applied.root,
119 });
120 }
121 if applied.nodes.is_empty() {
122 // Nothing was rebuilt: the root is the base root, which must be here.
123 stat_object(objects, changeset.root, Kind::Tree)?;
124 }
125 check_nodes(objects, &applied.nodes)?;
126
127 for change in changes.iter() {
128 if let ChangeOp::File { blob, size }
129 | ChangeOp::Executable { blob, size }
130 | ChangeOp::Symlink { blob, size } = &change.op
131 {
132 check_blob(objects, *blob, *size)?;
133 }
134 }
135 if let Some(origin) = changeset.git_origin {
136 stat_object(objects, origin, Kind::Blob)?;
137 }
138 Ok(())
139}
140
141/// Checks that a blob is stored with the size an entry gives it, without
142/// reading it.
143fn check_blob<O: Objects>(objects: &O, blob: ObjectId, size: u64) -> Result<(), Error> {
144 let actual = stat_object(objects, blob, Kind::Blob)?;
145 if actual != size {
146 return Err(Error::BlobSize {
147 blob,
148 declared: size,
149 actual,
150 });
151 }
152 Ok(())
153}
154
155#[cfg(test)]
156mod tests {
157 use super::*;
158 use crate::access::read_tree;
159 use crate::error::ApplyProblem;
160 use crate::path::MAX_PATH_DEPTH;
161 use crate::testing::{Repo, deep_path, delete, signature, text_map};
162 use braid_format::changeset::{MAX_INLINE_CHANGES_BYTES, encode_change_list};
163 use braid_format::{Changes, Changeset, ChangesetError, MemoryObjects};
164 use std::cell::Cell;
165
166 fn admitted(ids: &[ObjectId]) -> impl Fn(&ObjectId) -> bool + '_ {
167 move |id| ids.contains(id)
168 }
169
170 /// Stores a hand-made changeset and returns its id.
171 fn forge(repo: &Repo, changeset: &Changeset) -> ObjectId {
172 repo.objects
173 .put(Kind::Changeset, &changeset.encode())
174 .unwrap()
175 }
176
177 #[test]
178 fn commit_builds_on_the_first_parent() {
179 let repo = Repo::new();
180 let first = repo.commit(&[], vec![repo.set("a.txt", "1"), repo.set("d/b.txt", "2")]);
181 let second = repo.commit(&[first], vec![repo.set("a.txt", "3"), delete("d/b.txt")]);
182 assert_eq!(repo.files(repo.root(second)), text_map(&[("a.txt", "3")]));
183 let changeset = read_changeset(&repo.objects, second).unwrap();
184 assert_eq!(changeset.parents, [first]);
185 assert_eq!(changeset.author, signature("author"));
186 assert_eq!(
187 changeset.changes,
188 Changes::Inline(vec![repo.set("a.txt", "3"), delete("d/b.txt")])
189 );
190 admit(&repo.objects, first, admitted(&[])).unwrap();
191 admit(&repo.objects, second, admitted(&[first])).unwrap();
192 }
193
194 #[test]
195 fn empty_commits_are_admissible() {
196 let repo = Repo::new();
197 let empty = repo.commit(&[], Vec::new());
198 assert_eq!(repo.root(empty), EMPTY_TREE);
199 admit(&repo.objects, empty, admitted(&[])).unwrap();
200 let again = repo.commit(&[empty], Vec::new());
201 admit(&repo.objects, again, admitted(&[empty])).unwrap();
202 // Deleting everything gives the empty tree too.
203 let one = repo.commit(&[empty], vec![repo.set("f", "x")]);
204 let none = repo.commit(&[one], vec![delete("f")]);
205 assert_eq!(repo.root(none), EMPTY_TREE);
206 admit(&repo.objects, none, admitted(&[one])).unwrap();
207 }
208
209 #[test]
210 fn commit_refuses_what_does_not_apply() {
211 let repo = Repo::new();
212 let first = repo.commit(&[], vec![repo.set("a", "1")]);
213 let result = commit(
214 &repo.objects,
215 vec![first],
216 vec![repo.set("a", "1")],
217 signature("a"),
218 signature("a"),
219 Vec::new(),
220 Vec::new(),
221 );
222 assert!(matches!(
223 result,
224 Err(Error::Apply {
225 problem: ApplyProblem::NoOp,
226 ..
227 })
228 ));
229 let missing_parent = ObjectId::hash(Kind::Changeset, b"nowhere");
230 let result = commit(
231 &repo.objects,
232 vec![missing_parent],
233 Vec::new(),
234 signature("a"),
235 signature("a"),
236 Vec::new(),
237 Vec::new(),
238 );
239 assert!(matches!(
240 result,
241 Err(Error::Missing {
242 kind: Kind::Changeset,
243 ..
244 })
245 ));
246 }
247
248 #[test]
249 fn admission_rejects_tampering() {
250 let repo = Repo::new();
251 let first = repo.commit(&[], vec![repo.set("a", "1"), repo.set("b", "2")]);
252 let second = repo.commit(&[first], vec![repo.set("a", "3"), repo.set("c/d", "4")]);
253 let good = read_changeset(&repo.objects, second).unwrap();
254
255 // A parent that is not admitted.
256 assert!(matches!(
257 admit(&repo.objects, second, admitted(&[])),
258 Err(Error::ParentNotAdmitted { parent, .. }) if parent == first
259 ));
260
261 // A wrong root.
262 let mut wrong_root = good.clone();
263 wrong_root.root = repo.root(first);
264 assert!(matches!(
265 admit(&repo.objects, forge(&repo, &wrong_root), admitted(&[first])),
266 Err(Error::RootMismatch { .. })
267 ));
268
269 // A blob that is not stored.
270 let unstored = Change {
271 path: b"z".to_vec(),
272 op: ChangeOp::File {
273 blob: ObjectId::hash(Kind::Blob, b"never stored"),
274 size: 12,
275 },
276 };
277 let missing = commit(
278 &repo.objects,
279 vec![first],
280 vec![unstored],
281 signature("a"),
282 signature("a"),
283 Vec::new(),
284 Vec::new(),
285 )
286 .unwrap();
287 assert!(matches!(
288 admit(&repo.objects, missing, admitted(&[first])),
289 Err(Error::Missing {
290 kind: Kind::Blob,
291 ..
292 })
293 ));
294
295 // A blob with another size than the change says.
296 let mut wrong_size = repo.set("z", "four");
297 if let ChangeOp::File { size, .. } = &mut wrong_size.op {
298 *size = 5;
299 }
300 let bad = commit(
301 &repo.objects,
302 vec![first],
303 vec![wrong_size],
304 signature("a"),
305 signature("a"),
306 Vec::new(),
307 Vec::new(),
308 )
309 .unwrap();
310 assert!(matches!(
311 admit(&repo.objects, bad, admitted(&[first])),
312 Err(Error::BlobSize {
313 declared: 5,
314 actual: 4,
315 ..
316 })
317 ));
318
319 // An unsorted change list does not even decode.
320 let mut unsorted = good.clone();
321 unsorted.changes = Changes::Inline(vec![repo.set("c/d", "4"), repo.set("a", "3")]);
322 assert!(matches!(
323 admit(&repo.objects, forge(&repo, &unsorted), admitted(&[first])),
324 Err(Error::Changeset {
325 error: ChangesetError::Unsorted { .. },
326 ..
327 })
328 ));
329
330 // A no-op change, with the root it would give.
331 let mut no_op = good.clone();
332 no_op.changes = Changes::Inline(vec![repo.set("b", "2")]);
333 no_op.root = repo.root(first);
334 assert!(matches!(
335 admit(&repo.objects, forge(&repo, &no_op), admitted(&[first])),
336 Err(Error::Apply {
337 problem: ApplyProblem::NoOp,
338 ..
339 })
340 ));
341
342 // A change list that leaves out a change: the root does not match.
343 let mut partial = good.clone();
344 partial.changes = Changes::Inline(vec![repo.set("a", "3")]);
345 assert!(matches!(
346 admit(&repo.objects, forge(&repo, &partial), admitted(&[first])),
347 Err(Error::RootMismatch { .. })
348 ));
349
350 // A missing git origin.
351 let mut origin = good.clone();
352 origin.git_origin = Some(ObjectId::hash(Kind::Blob, b"raw commit"));
353 assert!(matches!(
354 admit(&repo.objects, forge(&repo, &origin), admitted(&[first])),
355 Err(Error::Missing {
356 kind: Kind::Blob,
357 ..
358 })
359 ));
360
361 // The untouched original is still fine.
362 admit(&repo.objects, second, admitted(&[first])).unwrap();
363 }
364
365 #[test]
366 fn admission_requires_the_new_directories() {
367 let objects = braid_format::MemoryObjects::new();
368 let repo = Repo::new();
369 let first = repo.commit(&[], vec![repo.set("a/b", "1")]);
370 let second = repo.commit(&[first], vec![repo.set("a/c", "2")]);
371 // Copy everything except the directories `second` created.
372 let new_dirs: Vec<ObjectId> = {
373 let root = repo.root(second);
374 let a = read_tree(&repo.objects, root)
375 .unwrap()
376 .into_iter()
377 .find_map(|entry| match entry.kind {
378 braid_format::EntryKind::Tree { tree } => Some(tree),
379 _ => None,
380 })
381 .unwrap();
382 vec![root, a]
383 };
384 for id in repo.objects.ids() {
385 if !new_dirs.contains(&id) {
386 let (kind, bytes) = repo.objects.get(&id).unwrap().unwrap();
387 objects.put(kind, &bytes).unwrap();
388 }
389 }
390 assert!(matches!(
391 admit(&objects, second, admitted(&[first])),
392 Err(Error::Missing {
393 kind: Kind::Tree,
394 ..
395 })
396 ));
397 }
398
399 #[test]
400 fn long_change_lists_are_external() {
401 let repo = Repo::new();
402 let changes: Vec<Change> = (0..2000)
403 .map(|i| repo.set(&format!("dir/file-{i:05}.txt"), "x"))
404 .collect();
405 assert!(encode_change_list(&changes).len() > MAX_INLINE_CHANGES_BYTES);
406 let first = repo.commit(&[], changes.clone());
407 let changeset = read_changeset(&repo.objects, first).unwrap();
408 let Changes::External { list, count } = changeset.changes else {
409 panic!("expected an external list");
410 };
411 assert_eq!(count, 2000);
412 assert!(repo.objects.contains(&list).unwrap());
413 assert_eq!(
414 read_changes(&repo.objects, first, &changeset)
415 .unwrap()
416 .as_ref(),
417 changes.as_slice()
418 );
419 admit(&repo.objects, first, admitted(&[])).unwrap();
420
421 // A count that does not match the list.
422 let mut miscounted = changeset.clone();
423 miscounted.changes = Changes::External { list, count: 1999 };
424 assert!(matches!(
425 admit(&repo.objects, forge(&repo, &miscounted), admitted(&[])),
426 Err(Error::ChangeCount { .. })
427 ));
428
429 // A short list stored externally is not canonical.
430 let short = vec![repo.set("only", "x")];
431 let short_list = repo
432 .objects
433 .put(Kind::Blob, &encode_change_list(&short))
434 .unwrap();
435 let mut external = changeset.clone();
436 external.changes = Changes::External {
437 list: short_list,
438 count: 1,
439 };
440 external.root = repo.tree(&[("only", "x")]);
441 assert!(matches!(
442 admit(&repo.objects, forge(&repo, &external), admitted(&[])),
443 Err(Error::ExternalListFitsInline { .. })
444 ));
445 }
446
447 #[test]
448 fn admission_enforces_the_depth_limit() {
449 let repo = Repo::new();
450 let deepest = deep_path(MAX_PATH_DEPTH);
451 let first = repo.commit(&[], vec![repo.set(&deepest, "x")]);
452 admit(&repo.objects, first, admitted(&[])).unwrap();
453
454 // `commit` refuses a deeper path...
455 let deeper = deep_path(MAX_PATH_DEPTH + 1);
456 let result = commit(
457 &repo.objects,
458 vec![first],
459 vec![repo.set(&deeper, "x")],
460 signature("a"),
461 signature("a"),
462 Vec::new(),
463 Vec::new(),
464 );
465 assert!(matches!(result, Err(Error::TooDeep { .. })), "{result:?}");
466 // ...and a changeset made by hand with one is not admitted.
467 let forged = ChangesetParts {
468 parents: vec![first],
469 root: repo.root(first),
470 changes: vec![repo.set(&deeper, "x")],
471 author: signature("a"),
472 committer: signature("a"),
473 message: Vec::new(),
474 extras: Vec::new(),
475 git_origin: None,
476 }
477 .assemble()
478 .unwrap();
479 store_assembled(&repo.objects, &forged).unwrap();
480 let result = admit(&repo.objects, forged.id, admitted(&[first]));
481 assert!(matches!(result, Err(Error::TooDeep { .. })), "{result:?}");
482 }
483
484 /// A store that counts the blobs read in full.
485 struct Counting<'a> {
486 inner: &'a MemoryObjects,
487 blob_reads: Cell<usize>,
488 }
489
490 impl Objects for Counting<'_> {
491 type Error = core::convert::Infallible;
492
493 fn get(&self, id: &ObjectId) -> Result<Option<(Kind, Vec<u8>)>, Self::Error> {
494 let found = self.inner.get(id)?;
495 if matches!(found, Some((Kind::Blob, _))) {
496 self.blob_reads.set(self.blob_reads.get() + 1);
497 }
498 Ok(found)
499 }
500
501 fn put(&self, kind: Kind, payload: &[u8]) -> Result<ObjectId, Self::Error> {
502 self.inner.put(kind, payload)
503 }
504
505 fn stat(&self, id: &ObjectId) -> Result<Option<(Kind, u64)>, Self::Error> {
506 self.inner.stat(id)
507 }
508 }
509
510 #[test]
511 fn admission_checks_blobs_without_reading_them() {
512 let repo = Repo::new();
513 let first = repo.commit(
514 &[],
515 vec![
516 repo.set("a", "1"),
517 repo.exec("b", "2"),
518 repo.symlink("c", "a"),
519 ],
520 );
521 let second = repo.commit(&[first], vec![repo.set("a", "3"), repo.set("d/e", "4")]);
522 let counting = Counting {
523 inner: &repo.objects,
524 blob_reads: Cell::new(0),
525 };
526 admit(&counting, first, admitted(&[])).unwrap();
527 admit(&counting, second, admitted(&[first])).unwrap();
528 assert_eq!(counting.blob_reads.get(), 0);
529 }
530}