From 1a7880d921cf14aa9305316822be25f66729379d Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 16:03:52 +0100 Subject: [PATCH] feat(sync): fetch a snapshot by the record it belongs to A snapshot was fetched by its tree's id. Any tree can be named that way, including one deep within a snapshot, whose paths would then read as if they were at the root: once reading depends on paths, a caller could reach a directory they may not read by naming its tree. `FetchSnapshot` now names the record whose snapshot to walk, `of`: a revision or an acceptance. The server walks that record's snapshot from its root, and refuses anything else, so every path it walks is the path the content has. `Sync::need` and `Sync::repair` take the record too, and so does everything in a working copy that fetches a snapshot it lacks: moves, diffs, landings, converging and clones. A move onto a new revision, made of what the working copy holds and not written yet, needs nothing from the remote: it no longer asks. --- apps/origin-src/benches/sync.rs | 34 +++++-- apps/origin-src/src/annotations/promotion.rs | 17 +--- apps/origin-src/src/service.rs | 62 ++++++++----- apps/origin-src/src/sync.rs | 94 ++++++++++++-------- apps/origin-src/src/tree.rs | 34 ++++++- apps/origin-src/src/workspace/land.rs | 9 +- apps/origin-src/src/workspace/mod.rs | 59 +++++++----- apps/origin-src/src/workspace/registry.rs | 4 +- apps/origin-src/src/workspace/remote.rs | 36 ++++---- apps/origin-src/tests/http.rs | 20 +++-- apps/origin-src/tests/sync.rs | 6 ++ crates/origin-client/src/lib.rs | 4 +- crates/origin-shared/src/api.rs | 7 +- crates/origin-shared/src/object/revision.rs | 11 ++- docs/openapi.json | 10 +-- 15 files changed, 267 insertions(+), 140 deletions(-) diff --git a/apps/origin-src/benches/sync.rs b/apps/origin-src/benches/sync.rs index a081b189..bc977f0a 100644 --- a/apps/origin-src/benches/sync.rs +++ b/apps/origin-src/benches/sync.rs @@ -53,8 +53,8 @@ struct Setup { /// The tip of `main`, the whole fixture, and its snapshot. tip: Base, snapshot: TreeId, - /// Edits only the server has. - theirs: Vec, + /// Revisions of the server's, each with its own edits. + theirs: Vec, client: Store, /// Edits only the client has. ours: Vec, @@ -80,8 +80,19 @@ static SETUP: LazyLock = LazyLock::new(|| { }; let snapshot = snapshot_into(service.store(), None); let tip = land(&service, snapshot); + let mut records = Vec::new(); let theirs = (1..=u64::from(SAMPLES)) - .map(|version| snapshot_into(service.store(), Some(version))) + .map(|version| { + let snapshot = snapshot_into(service.store(), Some(version)); + let (description, revision) = revision(tip, snapshot); + let id = RecordId::Revision(revision.id().into()); + records.extend([description.clone(), revision.clone()]); + let pack = Pack { + objects: vec![description, revision], + }; + service.put_records(&Caller::Owner, pack).unwrap(); + id + }) .collect(); let (runtime, url) = serve(service, &node); @@ -91,7 +102,9 @@ static SETUP: LazyLock = LazyLock::new(|| { let remote = Remote::open(&url, node.clone(), Some("bench".to_owned())).unwrap(); let sync = Sync::new(&store, &remote, "laptop".parse().unwrap()); sync.fetch_chains(&[TargetName::MAIN]).unwrap(); - sync.need(snapshot, &[]).unwrap(); + sync.need(tip.into(), &[]).unwrap(); + // The client knows the records, as a fetch would have brought them. + store.write_all(&records).unwrap(); // Versions the server's edits never reach. let ours = (1..=u64::from(SAMPLES)) .map(|version| snapshot_into(&store, Some(1_000 + version))) @@ -183,11 +196,18 @@ fn clone_snapshot(bencher: Bencher<'_, '_>) { let dir = tempfile::tempdir().unwrap(); let store = Store::new(dir.path().join(".origin"), Native::default()); store.init().unwrap(); + // A clone fetches the chain first. + let Base::Acceptance(tip) = setup.tip else { + unreachable!("the tip is an acceptance") + }; + store + .write_all(&[setup.client.read(tip.into()).unwrap()]) + .unwrap(); (dir, store) }) .bench_local_refs(|(_, store)| { let sync = Sync::new(store, &remote, "laptop".parse().unwrap()); - assert!(sync.need(setup.snapshot, &[]).unwrap()); + assert!(sync.need(setup.tip.into(), &[]).unwrap()); }); } @@ -201,8 +221,8 @@ fn fetch_100_edited(bencher: Bencher<'_, '_>) { let next = AtomicUsize::new(0); bencher .with_inputs(|| setup.theirs[next.fetch_add(1, Ordering::Relaxed) % SAMPLES as usize]) - .bench_local_values(|snapshot| { - sync.need(snapshot, &[setup.snapshot]).unwrap(); + .bench_local_values(|revision| { + sync.need(revision, &[setup.snapshot]).unwrap(); }); } diff --git a/apps/origin-src/src/annotations/promotion.rs b/apps/origin-src/src/annotations/promotion.rs index fec5d6fb..41536ff7 100644 --- a/apps/origin-src/src/annotations/promotion.rs +++ b/apps/origin-src/src/annotations/promotion.rs @@ -18,7 +18,7 @@ use std::collections::HashSet; use origin_platform::Platform; use origin_shared::api::Annotation; -use origin_shared::{Principal, Record, RecordId, Statement, StatementId, TreeId}; +use origin_shared::{Principal, Record, RecordId, Statement, StatementId}; use super::Annotations; use crate::store::{Store, StoreError}; @@ -246,21 +246,6 @@ impl Annotations<'_, P> { } impl Store

{ - /// The snapshot of a record a statement is about, which its input - /// digest is taken from. Statements have none. - /// - /// # Errors - /// - /// Fails if the record cannot be read. - pub fn snapshot_of(&self, subject: RecordId) -> Result, StoreError> { - Ok(match subject { - RecordId::Snapshot(id) => Some(id), - RecordId::Revision(id) => Some(self.get(id)?.snapshot), - RecordId::Acceptance(id) => Some(self.get(id)?.body().state), - RecordId::Statement(_) => None, - }) - } - /// Checks the claim `statement`, `id`, makes. A statement that promotes /// none makes its own. A promotion must name an original the store has /// that is [promotable](Statement::is_promotable), match its kind, diff --git a/apps/origin-src/src/service.rs b/apps/origin-src/src/service.rs index dedfcf80..3fdeed33 100644 --- a/apps/origin-src/src/service.rs +++ b/apps/origin-src/src/service.rs @@ -333,36 +333,50 @@ impl OriginService { }) } - /// The objects of the snapshot the request names that the caller lacks, - /// as a pack, parents before children: those none of the snapshots it - /// has holds at the same path, under the paths it asks for, but the - /// first `skip`. See [`Store::added`]. The pack stops short at - /// [`Pack::LIMIT`]: the rest comes from asking again, skipping what - /// came. + /// The snapshot of a record, a revision or an acceptance, if it is one. + fn snapshot_of(&self, record: RecordId) -> Result { + let unknown = || ServiceError::UnknownRecord(record); + let snapshot = match record { + RecordId::Revision(id) => self.store.get(id).map(|revision| revision.snapshot), + RecordId::Acceptance(id) => { + self.store.get(id).map(|acceptance| acceptance.body().state) + } + RecordId::Statement(_) | RecordId::Snapshot(_) => { + return Err(ServiceError::NotASnapshot(record)); + } + }; + match snapshot { + // Not a record of the kind it's named as. + Err(StoreError::NotFound(_) | StoreError::Decode { .. }) => Err(unknown()), + snapshot => Ok(snapshot?), + } + } + + /// The objects of the snapshot of the record the request names that the + /// caller lacks, as a pack, parents before children: those none of the + /// snapshots it has holds at the same path, under the paths it asks + /// for, but the first `skip`. See [`Store::added`]. The pack stops + /// short at [`Pack::LIMIT`]: the rest comes from asking again, skipping + /// what came. /// /// # Errors /// - /// Fails if the repository doesn't have the snapshot, or cannot read - /// it. + /// Fails if the record isn't a revision or an acceptance, or the + /// repository cannot read its snapshot. pub fn snapshot( &self, _caller: &Caller, request: &FetchSnapshot, ) -> Result { - let is_tree = |id: TreeId| -> Result { - let object = self.store.try_read(id.into())?; - Ok(object.is_some_and(|object| object.kind().ok() == Some(ObjectKind::Tree))) - }; - if !is_tree(request.snapshot)? { - return Err(ServiceError::UnknownSnapshot(request.snapshot)); - } + let snapshot = self.snapshot_of(request.of)?; let mut have = Vec::new(); for &id in &request.have { - if is_tree(id)? { + let object = self.store.try_read(id.into())?; + if object.is_some_and(|object| object.kind().ok() == Some(ObjectKind::Tree)) { have.push(id); } } - let added = self.store.added(request.snapshot, &have, &request.paths)?; + let added = self.store.added(snapshot, &have, &request.paths)?; let skip = usize::try_from(request.skip).unwrap_or(usize::MAX); let ids: Vec = added .iter() @@ -954,6 +968,12 @@ pub enum ServiceError { /// A blob, a tree or an attachment was fetched as a record. #[error("{0} is not a record: fetch snapshots by walking them")] NotARecord(ObjectId), + /// The repository has no such record, or the caller doesn't see it. + #[error("record {0} not found")] + UnknownRecord(RecordId), + /// A snapshot was asked of a record that has none. + #[error("{0} has no snapshot: name a revision or an acceptance")] + NotASnapshot(RecordId), /// An object put refers to one as an object of another kind: a /// snapshot that isn't a tree, a file that is one, a description that /// isn't an attachment. @@ -1037,13 +1057,15 @@ impl ServiceError { Self::UnknownRepository(_) | Self::UnknownChange(_) | Self::UnknownTarget(_) - | Self::UnknownSnapshot(_) => ErrorCode::NotFound, + | Self::UnknownSnapshot(_) + | Self::UnknownRecord(_) => ErrorCode::NotFound, Self::NoTarget | Self::NotARecord(_) + | Self::NotASnapshot(_) + | Self::WrongKind { .. } | Self::Malformed { .. } | Self::Acceptance(_) - | Self::Missing { .. } - | Self::WrongKind { .. } => ErrorCode::BadRequest, + | Self::Missing { .. } => ErrorCode::BadRequest, Self::Statement { source, .. } => match &**source { AnnotateError::Store(error) => Self::store_code(error), _ => ErrorCode::BadRequest, diff --git a/apps/origin-src/src/sync.rs b/apps/origin-src/src/sync.rs index 9fefb4d6..a8bac424 100644 --- a/apps/origin-src/src/sync.rs +++ b/apps/origin-src/src/sync.rs @@ -572,7 +572,7 @@ impl<'a> Sync<'a> { }; // Small, and the policy in force once it's the tip. if chain.target == TargetName::POLICY { - self.need(body.state, &[])?; + self.fetch_snapshot(RecordId::Acceptance(*id), body.state, &[])?; } let governing = Policy::governing(*id, body) .map_err(|error| unverified(Unverified::Policy(error)))?; @@ -589,7 +589,7 @@ impl<'a> Sync<'a> { self.on_policy_chain(governing)? .ok_or_else(|| unverified(Unverified::OffChain(governing)))? }; - self.need(state, &[])?; + self.fetch_snapshot(RecordId::Acceptance(governing), state, &[])?; let policy = Policy::of_snapshot(self.store, state)? .ok_or(unverified(Unverified::NoPolicy))?; vacant.insert(policy) @@ -887,38 +887,37 @@ impl<'a> Sync<'a> { Ok(objects) } - /// Fetches the trees and blobs of `snapshot`, unless the store holds it - /// whole, skipping what the snapshots `have`, which it holds whole, - /// hold at the same path. Returns whether it fetched. + /// Fetches the trees and blobs of the snapshot of `record`, a revision + /// or an acceptance this node has, unless the store holds it whole, + /// skipping what the snapshots `have`, which it holds whole, hold at + /// the same path. Returns whether it fetched. /// /// # Errors /// - /// Fails if the remote doesn't have the snapshot, or the remote or the - /// store fails. - pub fn need(&self, snapshot: TreeId, have: &[TreeId]) -> Result { - if self.store.holds(snapshot)? { - return Ok(false); - } - let request = FetchSnapshot { - snapshot, - have: self.store.held_whole(have.iter().copied())?, - paths: Vec::new(), - skip: 0, - }; - self.fetch_parts(request, Some(snapshot))?; - Ok(true) + /// Fails if the record has no snapshot, the remote doesn't have it, or + /// the remote or the store fails. + pub fn need(&self, record: RecordId, have: &[TreeId]) -> Result { + let snapshot = self + .store + .snapshot_of(record)? + .ok_or(SyncError::NoSnapshot(record))?; + self.fetch_snapshot(record, snapshot, have) } - /// Fetches `snapshot` whole again, whatever the store holds: what the - /// store lacks of a snapshot it has the root of, which reading it - /// found. + /// Fetches the whole snapshot of `record` again, whatever the store + /// holds: what the store lacks of a snapshot it has the root of, which + /// reading it found. /// /// # Errors /// /// Fails like [`Sync::need`]. - pub fn repair(&self, snapshot: TreeId) -> Result<(), SyncError> { + pub fn repair(&self, record: RecordId) -> Result<(), SyncError> { + let snapshot = self + .store + .snapshot_of(record)? + .ok_or(SyncError::NoSnapshot(record))?; let request = FetchSnapshot { - snapshot, + of: record, have: Vec::new(), paths: Vec::new(), skip: 0, @@ -926,6 +925,26 @@ impl<'a> Sync<'a> { self.fetch_parts(request, Some(snapshot)) } + /// [`Sync::need`], given the snapshot of `record`. + fn fetch_snapshot( + &self, + record: RecordId, + snapshot: TreeId, + have: &[TreeId], + ) -> Result { + if self.store.holds(snapshot)? { + return Ok(false); + } + let request = FetchSnapshot { + of: record, + have: self.store.held_whole(have.iter().copied())?, + paths: Vec::new(), + skip: 0, + }; + self.fetch_parts(request, Some(snapshot))?; + Ok(true) + } + /// Fetches what `request` asks for, part after part, in one batch. With /// `whole`, the snapshot it fetches whole, which is marked until the /// batch is durable. @@ -998,10 +1017,7 @@ impl<'a> Sync<'a> { let mut seen = HashSet::new(); for (id, revision) in &revisions { // The remote has these snapshots, or gets them first. - let mut have = vec![match revision.base { - Base::Acceptance(base) => self.store.get(base)?.body().state, - Base::Revision(base) => self.store.get(base)?.snapshot, - }]; + let mut have = vec![self.store.base_snapshot(revision.base)?]; for &predecessor in &revision.predecessors { if shared.contains(&predecessor.into()) { have.push(self.store.get(predecessor)?.snapshot); @@ -1339,6 +1355,9 @@ pub enum SyncError { /// The remote has no such target. #[error("the remote has no target `{0}`")] UnknownTarget(TargetName), + /// A snapshot was needed of a record that has none. + #[error("{0} has no snapshot")] + NoSnapshot(RecordId), /// The change has no revision to push. #[error("change {} has no revisions", .0.short())] UnknownChange(ChangeId), @@ -1546,8 +1565,9 @@ mod tests { !client.store.contains(state.into()).unwrap(), "snapshots are lazy" ); - assert!(client.sync().need(state, &[]).unwrap()); - assert!(!client.sync().need(state, &[]).unwrap(), "once"); + let tip = RecordId::Acceptance(server.tip(&TargetName::MAIN).acceptance); + assert!(client.sync().need(tip, &[]).unwrap()); + assert!(!client.sync().need(tip, &[]).unwrap(), "once"); assert_eq!(client.store.diff(state, state).unwrap(), []); assert_eq!(client.sync().fetch_chains(&[]).unwrap(), []); } @@ -1888,16 +1908,17 @@ mod tests { statements: 1 } ); - let snapshot = other.store.get(first).unwrap().snapshot; + let record = RecordId::Revision(first); let request = FetchSnapshot { - snapshot, + of: record, have: Vec::new(), paths: Vec::new(), skip: 0, }; let part = other.remote.snapshot(&request).unwrap(); assert!(part.more && part.pack.objects.len() < 10, "{part:?}"); - assert!(other.sync().need(snapshot, &[]).unwrap()); + assert!(other.sync().need(record, &[]).unwrap()); + let snapshot = other.store.snapshot_of(record).unwrap().unwrap(); let empty = build(&other.store, &[]); assert_eq!(other.store.diff(empty, snapshot).unwrap().len(), 20); } @@ -1912,7 +1933,8 @@ mod tests { .sync() .fetch_changes(&[ChangeId::from_bytes([1; 16])]) .unwrap(); - let snapshot = client.store.get(revision).unwrap().snapshot; + let record = RecordId::Revision(revision); + let snapshot = client.store.snapshot_of(record).unwrap().unwrap(); let empty = build(&client.store, &[]); // A fetch cut short once the root was published, not what it holds. @@ -1924,7 +1946,7 @@ mod tests { batch.commit().unwrap(); drop(fetching); assert!(!client.store.holds(snapshot).unwrap()); - assert!(client.sync().need(snapshot, &[]).unwrap(), "fetched again"); + assert!(client.sync().need(record, &[]).unwrap(), "fetched again"); assert!(client.store.holds(snapshot).unwrap()); assert_eq!(client.store.diff(empty, snapshot).unwrap().len(), 1); @@ -1935,7 +1957,7 @@ mod tests { .unwrap(); client.store.remove(&[src.id]).unwrap(); assert!(client.store.diff(empty, snapshot).is_err()); - client.sync().repair(snapshot).unwrap(); + client.sync().repair(record).unwrap(); assert_eq!(client.store.diff(empty, snapshot).unwrap().len(), 1); } diff --git a/apps/origin-src/src/tree.rs b/apps/origin-src/src/tree.rs index 0605c76b..f854cce5 100644 --- a/apps/origin-src/src/tree.rs +++ b/apps/origin-src/src/tree.rs @@ -8,8 +8,8 @@ use std::path::PathBuf; use origin_platform::Platform; use origin_shared::{ - Digest, EncodedObject, EntryKind, EntryName, Inputs, ObjectId, Record, RepoPath, Tree, - TreeEntry, TreeId, + Base, Digest, EncodedObject, EntryKind, EntryName, Inputs, ObjectId, Record, RecordId, + RepoPath, Tree, TreeEntry, TreeId, }; use crate::conflict::{Conflicted, Conflicts}; @@ -400,6 +400,36 @@ impl<'a, P: Platform> Snapshots<'a, P> { } } +impl Store

{ + /// The snapshot `base` names: an acceptance's state or a revision's + /// snapshot. + /// + /// # Errors + /// + /// Fails if the record cannot be read. + pub fn base_snapshot(&self, base: Base) -> Result { + Ok(match base { + Base::Acceptance(id) => self.get(id)?.body().state, + Base::Revision(id) => self.get(id)?.snapshot, + }) + } + + /// The snapshot of a record: a revision's, an acceptance's state, or a + /// snapshot itself. Statements have none. + /// + /// # Errors + /// + /// Fails if the record cannot be read. + pub fn snapshot_of(&self, record: RecordId) -> Result, StoreError> { + Ok(match record { + RecordId::Snapshot(id) => Some(id), + RecordId::Revision(id) => Some(self.get(id)?.snapshot), + RecordId::Acceptance(id) => Some(self.get(id)?.body().state), + RecordId::Statement(_) => None, + }) + } +} + /// A snapshot being fetched, marked durably in the store's `fetching/`, so /// an interrupted fetch, which published trees before what they hold, is /// never taken for a whole snapshot: see [`Store::holds`]. Dropping it diff --git a/apps/origin-src/src/workspace/land.rs b/apps/origin-src/src/workspace/land.rs index 62a1753b..72612f46 100644 --- a/apps/origin-src/src/workspace/land.rs +++ b/apps/origin-src/src/workspace/land.rs @@ -26,7 +26,8 @@ use std::{mem, slice}; use origin_shared::api::{LandRequest, Landings, NewTarget}; use origin_shared::landing::{Blocked, Landing, Pending, Proposal}; use origin_shared::{ - Base, ChangeId, EncodedObject, Record, Revision, RevisionId, Source, TargetName, TreeId, + Base, ChangeId, EncodedObject, Record, RecordId, Revision, RevisionId, Source, TargetName, + TreeId, }; use super::{Behind, WorkingCopy, Workspace, WorkspaceError}; @@ -292,8 +293,8 @@ impl Workspace { .store .head(target)? .ok_or_else(|| WorkspaceError::UnknownTarget(target.clone()))?; + self.need(&[RecordId::Acceptance(tip.acceptance)])?; let state = self.store.get(tip.acceptance)?.body().state; - self.need(&[state])?; let tip_label = format!("{target} #{}", tip.seq); let merge = self.store.merge_marked( Some(base), @@ -365,6 +366,8 @@ impl Workspace { working_copy: &mut WorkingCopy, rebased: RevisionId, ) -> Result<(), WorkspaceError> { + // A clone may not have the rebased revision's snapshot yet. + self.need(&[RecordId::Revision(rebased)])?; let theirs: Revision = self.store.get(rebased)?; if working_copy.files == working_copy.revision.snapshot { return self.move_to(working_copy, rebased, &theirs, &[], &Conflicts::default()); @@ -404,8 +407,8 @@ impl Workspace { .store .head(onto)? .ok_or_else(|| WorkspaceError::UnknownTarget(onto.clone()))?; + self.need(&[RecordId::Acceptance(tip.acceptance)])?; let state = self.store.get(tip.acceptance)?.body().state; - self.need(&[state])?; let current = &working_copy.revision; let tip_label = format!("{onto} #{}", tip.seq); let merge = self.store.merge_marked( diff --git a/apps/origin-src/src/workspace/mod.rs b/apps/origin-src/src/workspace/mod.rs index 90508bd5..2529a687 100644 --- a/apps/origin-src/src/workspace/mod.rs +++ b/apps/origin-src/src/workspace/mod.rs @@ -784,11 +784,14 @@ impl Workspace { ) -> Result<(), WorkspaceError> { // Before changing any file. self.may_move()?; - // Fetched first, so a fetch that fails moves nothing. + // Fetched first, so a fetch that fails moves nothing. A new + // revision is made of what's here. let changes = if revision.snapshot == working_copy.files { Vec::new() + } else if unwritten.is_empty() { + self.changes(working_copy.files, RecordId::Revision(to))? } else { - self.changes(working_copy.files, revision.snapshot)? + self.store.diff(working_copy.files, revision.snapshot)? }; // The files stay as they are: there's nothing to finish. if changes.is_empty() { @@ -849,18 +852,23 @@ impl Workspace { Ok(Worktree::new(&self.root, &self.store).restore(&changes)?) } - /// The changes that make the files of `from` those of `to`, after - /// fetching what the repository lacks of `to`. A move asks for them - /// before it publishes `moving`, so a fetch that fails moves nothing. - fn changes(&self, from: TreeId, to: TreeId) -> Result, WorkspaceError> { + /// The changes that make the files of `from` those of the snapshot of + /// `to`, a revision or an acceptance, after fetching what the + /// repository lacks of it. A move asks for them before it publishes + /// `moving`, so a fetch that fails moves nothing. + fn changes(&self, from: TreeId, to: RecordId) -> Result, WorkspaceError> { self.need(&[to])?; - Ok(match self.store.diff(from, to) { + let tree = self + .store + .snapshot_of(to)? + .ok_or(SyncError::NoSnapshot(to))?; + Ok(match self.store.diff(from, tree) { // A snapshot can lack trees its root names, if its fetch was // cut short before fetches were marked: fetch it whole again. Err(StoreError::NotFound(missing)) => match self.remote()? { Some(remote) => { self.sync(remote).repair(to)?; - self.store.diff(from, to)? + self.store.diff(from, tree)? } None => return Err(StoreError::NotFound(missing).into()), }, @@ -939,7 +947,11 @@ impl Workspace { /// cannot be read. pub fn diff(&mut self) -> Result<(), WorkspaceError> { let working_copy = self.snapshot()?; - self.print_diff(working_copy.revision.base, working_copy.files) + self.print_diff( + working_copy.id, + working_copy.revision.base, + working_copy.files, + ) } /// `origin show []`: prints a change's head, or each of them if @@ -990,15 +1002,21 @@ impl Workspace { println!(" {line}"); } println!(); - self.print_diff(revision.base, files)?; + self.print_diff(id, revision.base, files)?; } Ok(()) } - /// Prints the changes `snapshot` makes to `base`, line by line. - fn print_diff(&self, base: Base, snapshot: TreeId) -> Result<(), WorkspaceError> { + /// Prints the changes `snapshot`, of revision `id`, makes to `base`, + /// line by line. + fn print_diff( + &self, + id: RevisionId, + base: Base, + snapshot: TreeId, + ) -> Result<(), WorkspaceError> { let base = self.base_tree(base)?; - self.need(&[snapshot])?; + self.need(&[RecordId::Revision(id)])?; for change in self.store.diff(base, snapshot)? { print!("{}", FileDiff::new(&self.store, &change)?); } @@ -1217,11 +1235,8 @@ impl Workspace { heads[heads.len() - 1] }; let kept_revision: Revision = self.store.get(kept)?; - let snapshots = heads - .iter() - .map(|&head| Ok(self.store.get(head)?.snapshot)) - .collect::, WorkspaceError>>()?; - self.need(&snapshots)?; + let records: Vec<_> = heads.iter().copied().map(RecordId::Revision).collect(); + self.need(&records)?; let base = self.merge_base(&heads)?; let mut snapshot = kept_revision.snapshot; let mut merged = Conflicts::default(); @@ -1528,12 +1543,8 @@ impl Workspace { /// The snapshot a revision was made on top of, fetched if the /// repository lacks it. fn base_tree(&self, base: Base) -> Result { - let tree = match base { - Base::Acceptance(id) => self.store.get(id)?.body().state, - Base::Revision(id) => self.store.get(id)?.snapshot, - }; - self.need(&[tree])?; - Ok(tree) + self.need(&[base.into()])?; + Ok(self.store.base_snapshot(base)?) } fn describe_base(&self, base: Base) -> Result { diff --git a/apps/origin-src/src/workspace/registry.rs b/apps/origin-src/src/workspace/registry.rs index 9c53beab..cf247986 100644 --- a/apps/origin-src/src/workspace/registry.rs +++ b/apps/origin-src/src/workspace/registry.rs @@ -19,7 +19,7 @@ use std::os::unix::ffi::OsStrExt; use std::path::{self, Path, PathBuf}; use origin_platform::DurableWrite; -use origin_shared::{ChangeId, Digest, EncodedObject, Record, Revision, Tree}; +use origin_shared::{ChangeId, Digest, EncodedObject, Record, RecordId, Revision, Tree}; use super::{Workspace, WorkspaceError}; use crate::oplog::Why; @@ -73,7 +73,7 @@ impl Workspace { let store = store.with_actor(self.store.actor().in_workspace(&root)); let mut workspace = Self::at(root, store, self.config.clone(), id); let empty = Tree::default().encode().id().into(); - let changes = workspace.changes(empty, revision.snapshot)?; + let changes = workspace.changes(empty, RecordId::Revision(id))?; workspace.checkout(&changes, None)?; let repository = Self::path_bytes(self.store.root()); workspace.write_durably(workspace.meta(Self::REPOSITORY), &repository)?; diff --git a/apps/origin-src/src/workspace/remote.rs b/apps/origin-src/src/workspace/remote.rs index d733ca3f..c31d5f3e 100644 --- a/apps/origin-src/src/workspace/remote.rs +++ b/apps/origin-src/src/workspace/remote.rs @@ -24,7 +24,7 @@ use std::sync::OnceLock; use origin_platform::Native; use origin_shared::{ - Base, ChangeId, EncodedObject, Record, Revision, RevisionId, TargetName, Tree, TreeId, + Base, ChangeId, EncodedObject, Record, RecordId, Revision, RevisionId, TargetName, Tree, }; use super::{Workspace, WorkspaceError}; @@ -119,7 +119,7 @@ impl Workspace { .head(target)? .ok_or_else(|| WorkspaceError::UnknownTarget(target.clone()))?; let state = store.get(tip.acceptance)?.body().state; - sync.need(state, &[])?; + sync.need(RecordId::Acceptance(tip.acceptance), &[])?; let empty_tree = Tree::default().encode(); let empty_description = EncodedObject::attachment(b""); @@ -142,7 +142,8 @@ impl Workspace { )?; workspace.save_cursor(&cursor)?; workspace.remote = OnceLock::from(Some(remote)); - let changes = workspace.changes(empty_tree.id().into(), state)?; + let changes = + workspace.changes(empty_tree.id().into(), RecordId::Acceptance(tip.acceptance))?; workspace.checkout(&changes, None)?; workspace.publish_pointer(None, id, Why::Command)?; println!( @@ -356,25 +357,30 @@ impl Workspace { Ok(()) } - /// Fetches the snapshots of `trees` the repository lacks, if it has a - /// remote: a clone only holds the snapshots it read. Skips what the - /// working copy's revision and its base hold. Without a remote, reading - /// a missing snapshot fails later. - pub(super) fn need(&self, trees: &[TreeId]) -> Result<(), WorkspaceError> { - if self.store.held_whole(trees.iter().copied())?.len() == trees.len() { + /// Fetches the snapshots of `records`, revisions and acceptances, that + /// the repository lacks, if it has a remote: a clone only holds the + /// snapshots it read. Skips what the working copy's revision and its + /// base hold. Without a remote, reading a missing snapshot fails later. + pub(super) fn need(&self, records: &[RecordId]) -> Result<(), WorkspaceError> { + let mut lacking = Vec::new(); + for &record in records { + if let Some(snapshot) = self.store.snapshot_of(record)? + && !self.store.holds(snapshot)? + { + lacking.push(record); + } + } + if lacking.is_empty() { return Ok(()); } let Some(remote) = self.remote()? else { return Ok(()); }; let current = self.store.get(self.revision)?; - let base = match current.base { - Base::Acceptance(id) => self.store.get(id)?.body().state, - Base::Revision(id) => self.store.get(id)?.snapshot, - }; + let base = self.store.base_snapshot(current.base)?; let sync = self.sync(remote); - for &tree in trees { - sync.need(tree, &[current.snapshot, base])?; + for record in lacking { + sync.need(record, &[current.snapshot, base])?; } Ok(()) } diff --git a/apps/origin-src/tests/http.rs b/apps/origin-src/tests/http.rs index 541047db..9346bbaf 100644 --- a/apps/origin-src/tests/http.rs +++ b/apps/origin-src/tests/http.rs @@ -500,7 +500,7 @@ async fn fetches_snapshots_by_walking_them() { }; let snapshot = |have: Vec, paths: &[&str]| FetchSnapshot { - snapshot: tree.id().into(), + of: RecordId::Revision(made.id), have, paths: paths .iter() @@ -524,7 +524,7 @@ async fn fetches_snapshots_by_walking_them() { repo.put_records(&edited.pack()).await.unwrap(); let changed = repo .fetch_snapshot(&FetchSnapshot { - snapshot: edited.objects[2].id().into(), + of: RecordId::Revision(edited.id), have: vec![tree.id().into()], paths: Vec::new(), skip: 0, @@ -536,14 +536,24 @@ async fn fetches_snapshots_by_walking_them() { [edited.objects[2].clone(), edited.objects[1].clone()], "the new tree and the edited file" ); - let missing = FetchSnapshot { - snapshot: description.id().into(), + let subtree = FetchSnapshot { + of: RecordId::Snapshot(tree.id().into()), have: Vec::new(), paths: Vec::new(), skip: 0, }; + let error = repo.fetch_snapshot(&subtree).await.unwrap_err(); + assert_eq!( + code(error), + ErrorCode::BadRequest, + "only a record's snapshot, not a tree within one" + ); + let missing = FetchSnapshot { + of: RecordId::Revision(description.id().into()), + ..subtree + }; let error = repo.fetch_snapshot(&missing).await.unwrap_err(); - assert_eq!(code(error), ErrorCode::NotFound, "a blob is no snapshot"); + assert_eq!(code(error), ErrorCode::NotFound); } #[tokio::test] diff --git a/apps/origin-src/tests/sync.rs b/apps/origin-src/tests/sync.rs index 99572a34..106f63c3 100644 --- a/apps/origin-src/tests/sync.rs +++ b/apps/origin-src/tests/sync.rs @@ -208,6 +208,7 @@ fn a_move_that_cannot_fetch_moves_nothing() { let url = origin.root().to_str().unwrap(); let clone = Repo::clone(&ada, url, &[]); clone.ok(&["fetch", "--change", &change]); + let own = clone.change(); // The remote is gone while `edit` needs the change's files from it. let away = origin.root().with_extension("away"); @@ -221,4 +222,9 @@ fn a_move_that_cannot_fetch_moves_nothing() { fs::rename(&away, origin.root()).unwrap(); clone.ok(&["edit", &change]); assert_eq!(clone.read("x"), "x\n"); + + // A move that needs nothing from it works without it. + fs::rename(origin.root(), &away).unwrap(); + clone.ok(&["edit", &own]); + assert_eq!(clone.read("notes"), "mine\n"); } diff --git a/crates/origin-client/src/lib.rs b/crates/origin-client/src/lib.rs index 48f319ad..bb1dafaf 100644 --- a/crates/origin-client/src/lib.rs +++ b/crates/origin-client/src/lib.rs @@ -73,8 +73,8 @@ endpoints! { /// holds those up to the last record it has. fn fetch_records(request: &FetchRecords) -> Part = POST "records/fetch", json(request) => part; - /// Fetches the trees and blobs of a snapshot that none of the - /// request's snapshots holds at the same path, parents first. A + /// Fetches the trees and blobs of a record's snapshot that none of + /// the request's snapshots holds at the same path, parents first. A /// part that stops short is followed by asking again, skipping the /// objects it holds. fn fetch_snapshot(request: &FetchSnapshot) -> Part = diff --git a/crates/origin-shared/src/api.rs b/crates/origin-shared/src/api.rs index 86babad8..42120b7a 100644 --- a/crates/origin-shared/src/api.rs +++ b/crates/origin-shared/src/api.rs @@ -119,8 +119,11 @@ pub struct FetchRecords { /// a repository, so what each caller may read can be checked by path. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, ToSchema)] pub struct FetchSnapshot { - /// The snapshot. - pub snapshot: TreeId, + /// The record whose snapshot it is: a revision or an acceptance. Only a + /// record's snapshot is walked, never a tree within one, whose paths + /// would be read as others. + #[schema(value_type = String)] + pub of: RecordId, /// Snapshots the caller holds whole. Whatever one of them holds at the /// same path is skipped, so only what changed since comes. Those the /// repository doesn't have are ignored. diff --git a/crates/origin-shared/src/object/revision.rs b/crates/origin-shared/src/object/revision.rs index 83e5148c..436e3bdd 100644 --- a/crates/origin-shared/src/object/revision.rs +++ b/crates/origin-shared/src/object/revision.rs @@ -1,5 +1,5 @@ use super::{ObjectKind, Record, fields, tagged}; -use crate::{AcceptanceId, AttachmentId, ChangeId, Principal, RevisionId, TreeId}; +use crate::{AcceptanceId, AttachmentId, ChangeId, Principal, RecordId, RevisionId, TreeId}; /// One immutable version of a change. /// @@ -56,3 +56,12 @@ tagged!(Base { Acceptance = 1, Revision = 2, }); + +impl From for RecordId { + fn from(base: Base) -> Self { + match base { + Base::Acceptance(id) => Self::Acceptance(id), + Base::Revision(id) => Self::Revision(id), + } + } +} diff --git a/docs/openapi.json b/docs/openapi.json index b8e6b374..a3924aa9 100644 --- a/docs/openapi.json +++ b/docs/openapi.json @@ -1362,7 +1362,7 @@ "type": "object", "description": "Asks for the objects of a snapshot that the caller lacks: its trees and\nblobs, walked from its root. This is the only way blobs and trees leave\na repository, so what each caller may read can be checked by path.", "required": [ - "snapshot" + "of" ], "properties": { "have": { @@ -1372,6 +1372,10 @@ }, "description": "Snapshots the caller holds whole. Whatever one of them holds at the\nsame path is skipped, so only what changed since comes. Those the\nrepository doesn't have are ignored." }, + "of": { + "type": "string", + "description": "The record whose snapshot it is: a revision or an acceptance. Only a\nrecord's snapshot is walked, never a tree within one, whose paths\nwould be read as others." + }, "paths": { "type": "array", "items": { @@ -1384,10 +1388,6 @@ "format": "int64", "description": "Skip this many of the objects, which earlier parts brought: a\nresponse that stops short has the [`MORE`] header.", "minimum": 0 - }, - "snapshot": { - "$ref": "#/components/schemas/TreeId", - "description": "The snapshot." } } },