diff --git a/apps/origin-src/src/sync.rs b/apps/origin-src/src/sync.rs
index 72b2e124..48fcb946 100644
--- a/apps/origin-src/src/sync.rs
+++ b/apps/origin-src/src/sync.rs
@@ -1,8 +1,19 @@
//! Sync: sharing records with a [remote](crate::remote).
//!
-//! - **Fetching** the records of changes compares them with the remote's,
-//! by id, and fetches those missing, with the records they refer to, and
-//! the records of the changes those belong to.
+//! - **Fetching** brings the chain of each target this node follows, those
+//! it holds and those asked for, from the last acceptance it holds on.
+//! Each acceptance must follow the one before it, and is verified against
+//! the key of the authority named by the policy governing it
+//! ([`Policy::governing`]): for an acceptance of `policy`, the one before
+//! it, and for any other, the policy it names, which must be on the chain
+//! of `policy` as this node verified it. Only the first acceptance of
+//! `policy` is checked against its own. Acceptances this node merely
+//! stores, such as the base of a revision fetched, never govern anything.
+//! Each acceptance comes with what it landed, and the records of the
+//! changes that brings.
+//! - The records of changes are compared with the remote's, by id, and
+//! those missing fetched, with the records they refer to, and the records
+//! of the changes those belong to.
//! - Snapshots don't come with records: [`Sync::need`] fetches one when
//! something reads it, such as a checkout. A snapshot is marked while it's
//! fetched ([`Store::fetching`]), so one whose fetch was interrupted is
@@ -10,20 +21,24 @@
//!
//! Transfers are bounded: a fetch's answers stop at
//! [`Pack::LIMIT`](origin_shared::pack::Pack::LIMIT), with the rest asked
-//! for again (see [`Part`]).
+//! for again (see [`Part`]). Fetched records are written before the chains
+//! that refer to them.
+use std::collections::hash_map::Entry;
use std::collections::{BTreeSet, HashMap, HashSet};
use std::mem;
use origin_platform::Native;
-use origin_shared::api::{FetchRecords, FetchSnapshot, InventoryRequest};
-use origin_shared::object::DecodeError;
+use origin_shared::api::{FetchRecords, FetchSnapshot, InventoryRequest, LogQuery};
+use origin_shared::object::{BadSignature, DecodeError};
use origin_shared::pack::Part;
use origin_shared::{
- ChangeId, EncodedObject, ObjectId, ObjectKind, Principal, PrincipalName, Revision, TreeId,
+ Acceptance, AcceptanceId, ChangeId, EncodedObject, Head, Object, ObjectId, ObjectKind,
+ Principal, PrincipalName, Record, Revision, TargetName, TreeId,
};
use crate::annotations::Annotations;
+use crate::policy::{Policy, PolicyError};
use crate::remote::{Remote, RemoteError};
use crate::service::Dependencies;
use crate::store::{Batch, Store, StoreError};
@@ -36,6 +51,17 @@ pub struct Sync<'a> {
node: Principal,
}
+/// A target whose chain a fetch extended.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Advanced {
+ /// The target.
+ pub target: TargetName,
+ /// Its head before, if this node followed it.
+ pub from: Option
,
+ /// Its head now.
+ pub to: Head,
+}
+
/// What fetching records did.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Fetched {
@@ -45,6 +71,16 @@ pub struct Fetched {
pub statements: usize,
}
+/// The new acceptances of a target, verified and about to be appended.
+struct Chain {
+ target: TargetName,
+ /// This node's head of the target, if it has one.
+ from: Option,
+ /// The remote's head: the last of `acceptances`.
+ to: Head,
+ acceptances: Vec<(AcceptanceId, Acceptance)>,
+}
+
impl<'a> Sync<'a> {
/// Syncs `store` with `remote`, as the node `node`.
pub fn new(store: &'a Store, remote: &'a Remote, node: PrincipalName) -> Self {
@@ -55,6 +91,217 @@ impl<'a> Sync<'a> {
}
}
+ /// Fetches the chains of `policy`, of the targets this node holds, and
+ /// of `more`, with what they landed, as the module explains. Returns
+ /// the targets that moved, `policy` first. Learns the names of all the
+ /// remote's targets, so acceptances of those this node doesn't follow
+ /// can be described.
+ ///
+ /// # Errors
+ ///
+ /// Fails if the remote doesn't have a target of `more`, a target's
+ /// chain differs from the remote's, an acceptance doesn't verify, or
+ /// the remote or the store fails.
+ pub fn fetch_chains(&self, more: &[TargetName]) -> Result, SyncError> {
+ let (advanced, landed) = self.chains(more)?;
+ self.fetch_changes(&landed)?;
+ Ok(advanced)
+ }
+
+ /// [`Sync::fetch_chains`], but for the records of the changes that
+ /// landed, which it returns, for the caller to fetch.
+ fn chains(&self, more: &[TargetName]) -> Result<(Vec, Vec), SyncError> {
+ let remote: HashMap = self
+ .remote
+ .targets()?
+ .into_iter()
+ .map(|target| (target.name, target.head))
+ .collect();
+ for name in remote.keys() {
+ self.store.name_target(name)?;
+ }
+ let mut follow: BTreeSet = self.store.targets()?.into_iter().collect();
+ for target in more {
+ if !remote.contains_key(target) {
+ return Err(SyncError::UnknownTarget(target.clone()));
+ }
+ follow.insert(target.clone());
+ }
+ follow.remove(&TargetName::POLICY);
+ let mut chains = Vec::new();
+ for target in [TargetName::POLICY].into_iter().chain(follow) {
+ // Targets only this node has stay as they are.
+ if let Some(&head) = remote.get(&target) {
+ chains.extend(self.chain(target, head)?);
+ }
+ }
+ self.verify(&chains)?;
+ let appending: HashSet = chains
+ .iter()
+ .flat_map(|chain| &chain.acceptances)
+ .map(|&(id, _)| id.into())
+ .collect();
+ let landed = chains
+ .iter()
+ .flat_map(|chain| &chain.acceptances)
+ .flat_map(|(_, acceptance)| &acceptance.body().landed)
+ .map(|&source| source.id());
+ // Objects found stored stay until the chains refer to them.
+ let _held = self.store.hold_objects()?;
+ let held = self.store.batch();
+ let records = self.closure(&held, landed, &appending)?;
+ held.commit()?;
+
+ let mut revised = Self::revised(&records)?;
+ revised.sort_unstable();
+ revised.dedup();
+ if !records.is_empty() {
+ self.store.write_all(&records)?;
+ }
+ let mut advanced = Vec::new();
+ for chain in chains {
+ let acceptances: Vec<_> = chain.acceptances.into_iter().map(|(_, a)| a).collect();
+ self.store.append_all(&chain.target, &acceptances, &[])?;
+ advanced.push(Advanced {
+ target: chain.target,
+ from: chain.from,
+ to: chain.to,
+ });
+ }
+ // The changes that landed come whole, so the next fetch only looks
+ // for what moved since.
+ Ok((advanced, revised))
+ }
+
+ /// The acceptances of `target` after the last this node holds, up to
+ /// the remote's head, `theirs`, each checked against its id and target,
+ /// and to follow the one before it. `None` if there are none.
+ fn chain(&self, target: TargetName, theirs: Head) -> Result