Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 27 additions & 7 deletions apps/origin-src/benches/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<TreeId>,
/// Revisions of the server's, each with its own edits.
theirs: Vec<RecordId>,
client: Store,
/// Edits only the client has.
ours: Vec<TreeId>,
Expand All @@ -80,8 +80,19 @@ static SETUP: LazyLock<Setup> = 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);
Expand All @@ -91,7 +102,9 @@ static SETUP: LazyLock<Setup> = 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)))
Expand Down Expand Up @@ -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());
});
}

Expand All @@ -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();
});
}

Expand Down
17 changes: 1 addition & 16 deletions apps/origin-src/src/annotations/promotion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -246,21 +246,6 @@ impl<P: Platform> Annotations<'_, P> {
}

impl<P: Platform> Store<P> {
/// 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<Option<TreeId>, 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,
Expand Down
62 changes: 42 additions & 20 deletions apps/origin-src/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<TreeId, ServiceError> {
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<Part, ServiceError> {
let is_tree = |id: TreeId| -> Result<bool, StoreError> {
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<ObjectId> = added
.iter()
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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,
Expand Down
94 changes: 58 additions & 36 deletions apps/origin-src/src/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)))?;
Expand All @@ -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)
Expand Down Expand Up @@ -887,45 +887,64 @@ 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<bool, SyncError> {
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<bool, SyncError> {
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,
};
self.fetch_parts(request, Some(snapshot))
}

/// [`Sync::need`], given the snapshot of `record`.
fn fetch_snapshot(
&self,
record: RecordId,
snapshot: TreeId,
have: &[TreeId],
) -> Result<bool, SyncError> {
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.
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -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(), []);
}
Expand Down Expand Up @@ -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);
}
Expand All @@ -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.
Expand All @@ -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);

Expand All @@ -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);
}

Expand Down
Loading