diff --git a/apps/origin-src/src/lib.rs b/apps/origin-src/src/lib.rs
index 336d1f99..f00f28fc 100644
--- a/apps/origin-src/src/lib.rs
+++ b/apps/origin-src/src/lib.rs
@@ -11,6 +11,7 @@ pub mod fixture;
pub mod index;
pub mod output;
pub mod policy;
+pub mod queue;
pub mod store;
pub mod targets;
pub mod tree;
diff --git a/apps/origin-src/src/policy.rs b/apps/origin-src/src/policy.rs
index b35f4a55..d25a9ae9 100644
--- a/apps/origin-src/src/policy.rs
+++ b/apps/origin-src/src/policy.rs
@@ -33,8 +33,8 @@ use std::str::FromStr;
use origin_platform::Platform;
use origin_shared::{
- AcceptanceId, Kind, NodePublicKey, Principal, PrincipalName, RepoPath, TargetName, TreeId,
- Verdict,
+ AcceptanceId, EncodedObject, EntryKind, EntryName, Kind, NodePublicKey, Principal,
+ PrincipalName, Record, RepoPath, TargetName, Tree, TreeEntry, TreeId, Verdict,
};
use serde::Deserialize;
@@ -166,6 +166,19 @@ impl Policy {
})
}
+ /// A snapshot holding only `policy` as its `policy.toml`: the file and
+ /// the tree.
+ pub(crate) fn snapshot(policy: &str) -> (EncodedObject, EncodedObject) {
+ let file = EncodedObject::blob(policy.as_bytes());
+ let entry = TreeEntry {
+ kind: EntryKind::File,
+ id: file.id(),
+ };
+ let name = EntryName::new(Self::FILE).expect("`policy.toml` is a valid name");
+ let tree: Tree = [(name, entry)].into_iter().collect();
+ (file, tree.encode())
+ }
+
/// The node that orders `target`: the one its table names, or else the
/// authority of `policy`. `None` if neither has a table.
#[must_use]
diff --git a/apps/origin-src/src/queue/mod.rs b/apps/origin-src/src/queue/mod.rs
new file mode 100644
index 00000000..9858d171
--- /dev/null
+++ b/apps/origin-src/src/queue/mod.rs
@@ -0,0 +1,129 @@
+//! The landing queue: how a target's authority lands changes on it, one
+//! acceptance at a time. It starts a repository's history with
+//! [`Queue::init`], checking the policy it begins with.
+
+use origin_platform::{Native, Platform};
+use origin_shared::{
+ AcceptanceBody, AcceptanceId, EncodedObject, NodeKey, PrincipalName, Record, TargetName, Tree,
+ TreeId,
+};
+
+use crate::policy::{Policy, PolicyError};
+use crate::store::{Store, StoreError};
+
+/// The landing queues of a store's targets, as run by one node.
+#[derive(Debug)]
+pub struct Queue<'a, P = Native> {
+ store: &'a Store
,
+ key: &'a NodeKey,
+ node: PrincipalName,
+}
+
+impl<'a, P: Platform> Queue<'a, P> {
+ /// The queues of `store`, run by the node `node`, which signs with
+ /// `key`.
+ pub fn new(store: &'a Store
, key: &'a NodeKey, node: PrincipalName) -> Self {
+ Self { store, key, node }
+ }
+
+ /// Starts a repository's history: the `policy` target, holding `policy`
+ /// as its `policy.toml`, and an empty `main`, both of which the policy
+ /// must have this node order. Returns `main`'s first acceptance.
+ ///
+ /// # Errors
+ ///
+ /// Fails if the policy is invalid or doesn't make this node the
+ /// authority of both targets, either target exists, or the records
+ /// cannot be written.
+ pub fn init(&self, policy: &str) -> Result {
+ let (file, tree) = Policy::snapshot(policy);
+ let empty = Tree::default().encode();
+ self.store.write_all(&[file, tree.clone(), empty.clone()])?;
+ let policy = Self::check_policy(self.store, tree.id().into())?;
+ for target in [TargetName::POLICY, TargetName::MAIN] {
+ self.authorize(&policy, &target)?;
+ }
+ let genesis = |target: &TargetName, state: &EncodedObject, policy| {
+ AcceptanceBody {
+ target: target.id(),
+ seq: 0,
+ prev: None,
+ state: state.id().into(),
+ landed: Vec::new(),
+ evidence: Vec::new(),
+ policy,
+ }
+ .sign(self.key)
+ };
+ let policy = self.store.append(
+ &TargetName::POLICY,
+ &genesis(&TargetName::POLICY, &tree, None),
+ )?;
+ Ok(self.store.append(
+ &TargetName::MAIN,
+ &genesis(&TargetName::MAIN, &empty, Some(policy)),
+ )?)
+ }
+
+ /// The policy in `state`, about to become the policy in force, if it's
+ /// a valid one that names an authority for `policy`, so the target
+ /// never locks up.
+ fn check_policy(store: &Store, state: TreeId) -> Result {
+ let policy = Policy::of_snapshot(store, state)
+ .and_then(|policy| policy.ok_or(PolicyError::Missing))
+ .map_err(LandError::InvalidPolicy)?;
+ if policy.authority(&TargetName::POLICY).is_none() {
+ return Err(LandError::NoAuthority(TargetName::POLICY));
+ }
+ Ok(policy)
+ }
+
+ /// Checks that this node is the authority of `target` under `policy`,
+ /// with the key it lists.
+ fn authorize(&self, policy: &Policy, target: &TargetName) -> Result<(), LandError> {
+ let authority = policy
+ .authority(target)
+ .ok_or_else(|| LandError::NoAuthority(target.clone()))?;
+ if *authority != self.node {
+ return Err(LandError::NotAuthority {
+ target: target.clone(),
+ authority: authority.clone(),
+ node: self.node.clone(),
+ });
+ }
+ if policy.node_key(authority) != Some(&self.key.public()) {
+ return Err(LandError::WrongKey(self.node.clone()));
+ }
+ Ok(())
+ }
+}
+
+/// A failure to land.
+#[derive(Debug, thiserror::Error)]
+pub enum LandError {
+ /// The policy names no authority for the target.
+ #[error("policy.toml names no authority for `{0}`: give it, or `policy`, a [targets] table")]
+ NoAuthority(TargetName),
+ /// Another node orders the target.
+ #[error(
+ "node:{authority} is the authority of `{target}`, so only it lands there, and this is \
+ node:{node}"
+ )]
+ NotAuthority {
+ /// The target.
+ target: TargetName,
+ /// Its authority.
+ authority: PrincipalName,
+ /// This node.
+ node: PrincipalName,
+ },
+ /// The policy lists another key for this node.
+ #[error("policy.toml lists another key for node:{0} than this node's")]
+ WrongKey(PrincipalName),
+ /// Landing on `policy` would leave it without a valid policy.
+ #[error("landing would leave `policy` without a valid policy.toml")]
+ InvalidPolicy(#[source] PolicyError),
+ /// Records cannot be read or written.
+ #[error(transparent)]
+ Store(#[from] StoreError),
+}
diff --git a/apps/origin-src/src/workspace/mod.rs b/apps/origin-src/src/workspace/mod.rs
index 7cee97d8..b3a4eefd 100644
--- a/apps/origin-src/src/workspace/mod.rs
+++ b/apps/origin-src/src/workspace/mod.rs
@@ -28,9 +28,9 @@ use std::path::{self, Path, PathBuf};
use origin_platform::Native;
use origin_shared::{
- AcceptanceBody, AcceptanceId, Base, BlobId, ChangeId, EncodedObject, EntryKind, EntryName,
- Kind, NodePublicKey, Principal, Record, RecordId, RepoPath, Revision, RevisionId, Source,
- Statement, StatementId, TargetId, TargetName, Tree, TreeEntry, TreeId,
+ AcceptanceId, Base, BlobId, ChangeId, EncodedObject, Kind, NodePublicKey, Principal, Record,
+ RecordId, RepoPath, Revision, RevisionId, Source, Statement, StatementId, TargetId, TargetName,
+ Tree, TreeId,
};
use crate::ancestry::Ancestry;
@@ -39,6 +39,7 @@ use crate::config::{ConfigError, UserConfig};
use crate::conflict::Conflicts;
use crate::index::{FindChangeError, FindError, Index};
use crate::output::FileDiff;
+use crate::queue::{LandError, Queue};
use crate::store::{Store, StoreError};
use crate::worktree::{SnapshotError, StatCache, Worktree};
@@ -100,32 +101,10 @@ impl Workspace {
let store = Store::new(meta, Native::default());
store.init()?;
- let (policy, policy_tree) = Self::policy(&config, &key.public());
+ let policy = Self::policy(&config, &key.public());
+ let main = Queue::new(&store, &key, config.node().clone()).init(&policy)?;
let empty_tree = Tree::default().encode();
let empty_description = EncodedObject::blob(b"");
- let genesis = |target: &TargetName, state: &EncodedObject, policy| AcceptanceBody {
- target: target.id(),
- seq: 0,
- prev: None,
- state: state.id().into(),
- landed: Vec::new(),
- evidence: Vec::new(),
- policy,
- };
- store.write_all(&[
- policy,
- policy_tree.clone(),
- empty_tree.clone(),
- empty_description.clone(),
- ])?;
- let policy = store.append(
- &TargetName::POLICY,
- &genesis(&TargetName::POLICY, &policy_tree, None).sign(&key),
- )?;
- let main = store.append(
- &TargetName::MAIN,
- &genesis(&TargetName::MAIN, &empty_tree, Some(policy)).sign(&key),
- )?;
let revision = Revision {
change: ChangeId::random().map_err(WorkspaceError::Random)?,
@@ -143,7 +122,10 @@ impl Workspace {
config,
revision: encoded.id().into(),
};
- workspace.save(&[vec![encoded]], workspace.revision)?;
+ workspace.save(
+ &[vec![empty_description], vec![encoded]],
+ workspace.revision,
+ )?;
println!(
"Initialized a repository in {}: node:{} is the authority of `policy` and `main`",
workspace.root.display(),
@@ -153,12 +135,12 @@ impl Workspace {
Ok(workspace)
}
- /// The first `policy.toml`, and the snapshot holding it: this node is
- /// the authority of `policy` and `main`, and neither requires anything,
- /// so a solo project lands instantly.
- fn policy(config: &UserConfig, key: &NodePublicKey) -> (EncodedObject, EncodedObject) {
+ /// The first `policy.toml`: this node is the authority of `policy` and
+ /// `main`, and neither requires anything, so a solo project lands
+ /// instantly.
+ fn policy(config: &UserConfig, key: &NodePublicKey) -> String {
let node = config.node();
- let policy = format!(
+ format!(
"# Who may land what. Changing it is a landing on `policy`.\n\
\n\
# Each node's public key.\n\
@@ -176,18 +158,7 @@ impl Workspace {
[targets.main]\n\
authority = \"node:{node}\"\n\
# require = [{{ kind = \"ci.test\", verdict = \"pass\", issuer = \"group:runners\" }}]\n"
- );
- let policy = EncodedObject::blob(policy.as_bytes());
- let tree: Tree = [(
- EntryName::new("policy.toml").expect("a valid name"),
- TreeEntry {
- kind: EntryKind::File,
- id: policy.id(),
- },
- )]
- .into_iter()
- .collect();
- (policy, tree.encode())
+ )
}
/// Opens the working copy containing `start`.
@@ -1106,6 +1077,9 @@ pub enum WorkspaceError {
/// A statement cannot be issued.
#[error(transparent)]
Annotate(#[from] AnnotateError),
+ /// A landing failed.
+ #[error(transparent)]
+ Land(#[from] LandError),
}
impl WorkspaceError {