From d615933e8ea25f3fcdb772b94d7b6511cb7147e0 Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 14:38:17 +0100 Subject: [PATCH] feat(service): add OriginService, the one API over a repository The landing queue, statements and targets only worked on the command line, against the repository it ran in. A server needs the same operations, and they shouldn't be written twice: once for the command line, once for each transport. `OriginService` is the one API over a repository. It lists statements, with whether each holds, a change's revisions and heads, targets with their authority and requirements, and a target's log from a position on; it lands changes and targets, lists the landings that wait, and creates targets. Its errors carry an `ErrorCode`, so a transport can tell clients what kind of failure it was. Every method takes the `Caller`, which nothing checks yet, so permissions only have to add the checks. A service is meant to live as long as its process. It keeps a few indexes open, catching one up before each call instead of reading it whole, and opens another when they're all in use, so a landing never blocks readers or landings on other targets. The command line's `statements`, `land`, `target new`, `targets`, `log` and `evolog` now go through the service in-process, passing it the index they just read. `log -n` reads only the acceptances it shows, and the first `policy.toml` moves to `Policy::initial`, since a server creates repositories too. --- apps/origin-src/src/lib.rs | 1 + apps/origin-src/src/policy.rs | 26 ++ apps/origin-src/src/service.rs | 423 ++++++++++++++++++++++ apps/origin-src/src/targets.rs | 42 ++- apps/origin-src/src/workspace/annotate.rs | 28 +- apps/origin-src/src/workspace/land.rs | 101 +++--- apps/origin-src/src/workspace/mod.rs | 95 +++-- 7 files changed, 588 insertions(+), 128 deletions(-) create mode 100644 apps/origin-src/src/service.rs diff --git a/apps/origin-src/src/lib.rs b/apps/origin-src/src/lib.rs index 73b4cb26..6dffb046 100644 --- a/apps/origin-src/src/lib.rs +++ b/apps/origin-src/src/lib.rs @@ -15,6 +15,7 @@ pub mod oplog; pub mod output; pub mod policy; pub mod queue; +pub mod service; 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 6029fc1c..cd794c6c 100644 --- a/apps/origin-src/src/policy.rs +++ b/apps/origin-src/src/policy.rs @@ -370,6 +370,32 @@ impl TryFrom for Policy { } impl Policy { + /// The first `policy.toml` of a repository: `node`, whose public key is + /// `key`, is the authority of `policy` and `main`, and neither requires + /// anything, so a solo project lands instantly. + #[must_use] + pub fn initial(node: &PrincipalName, key: &NodePublicKey) -> String { + format!( + "# Who may land what. Changing it is a landing on `policy`.\n\ + \n\ + # Each node's public key.\n\ + [nodes]\n\ + \"{node}\" = \"{key}\"\n\ + \n\ + # Groups of users and nodes, for requirements:\n\ + # [groups]\n\ + # runners = [\"node:ci-1\"]\n\ + \n\ + # The node ordering each target, and the statements landing needs.\n\ + [targets.policy]\n\ + authority = \"node:{node}\"\n\ + \n\ + [targets.main]\n\ + authority = \"node:{node}\"\n\ + # require = [{{ kind = \"ci.test\", verdict = \"pass\", issuer = \"group:runners\" }}]\n" + ) + } + /// Checks that the group `principals` names, if any, is defined. fn check(&self, principals: Principals) -> Result { match &principals { diff --git a/apps/origin-src/src/service.rs b/apps/origin-src/src/service.rs new file mode 100644 index 00000000..aba0066e --- /dev/null +++ b/apps/origin-src/src/service.rs @@ -0,0 +1,423 @@ +//! `OriginService`: everything a repository can be asked, independent of +//! transport. +//! +//! It is the one API over a repository. The HTTP routes only translate +//! requests into its methods, and the command line calls them in-process +//! for the repository it runs in, so a local repository and a remote one +//! answer the same way. Plugins use it the same two ways. +//! +//! A service is meant to live as long as its process: it keeps the record +//! index open, catching it up with the op log before each use instead of +//! reading it whole. Calls don't wait for each other to use the index: each takes +//! one of the indexes kept open, or opens another if they're all in use. +//! Landings on one target still go one at a time, through the target's +//! queue lock. +//! +//! Every method takes the [`Caller`]. Nothing is checked yet: every caller +//! may read and write everything. + +use std::path::PathBuf; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; + +use origin_platform::Native; +use origin_shared::api::{ + Annotation, ErrorCode, LandRequest, Landings, LogEntry, NewTarget, RevisionEntry, Revisions, + TargetInfo, +}; +use origin_shared::landing::{Pending, Proposal}; +use origin_shared::{Base, ChangeId, Head, NodeKey, PrincipalName, RecordId, TargetName}; + +use crate::annotations::Annotations; +use crate::index::Index; +use crate::policy::{Policy, PolicyError}; +use crate::queue::{LandError, Queue}; +use crate::store::{Store, StoreError}; + +/// Who calls the service. Permissions will decide what each may do by it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Caller { + /// The node's own user, through the command line. + Owner, + /// A client of a server that didn't authenticate. + Anonymous, +} + +/// A node: its name, and the key it signs acceptances with as the +/// authority of the targets its repositories' policies name it for. A +/// server's repositories share their node. +#[derive(Clone, Debug)] +pub struct Node { + /// The node's name. + pub name: PrincipalName, + /// Its key. + pub key: Arc, +} + +/// One repository, served by its node. +#[derive(Debug)] +pub struct OriginService { + store: Store, + node: Node, + /// The record indexes kept open, but those in use: see the module. + indexes: Mutex>, +} + +impl OriginService { + /// The most indexes kept open for calls to take. + const KEPT_INDEXES: usize = 8; + + /// Serves the repository in `store` as `node`. + #[must_use] + pub fn new(store: Store, node: Node) -> Self { + Self { + store, + node, + indexes: Mutex::default(), + } + } + + /// The service, with `index`, just read, as its index. + #[must_use] + pub fn with_index(self, index: Index) -> Self { + Self { + indexes: Mutex::new(vec![index]), + ..self + } + } + + /// Creates a repository without a working copy, as a server hosts them, + /// in `root`, which must not exist or be empty: its store, and the + /// targets `policy`, holding `policy` as its `policy.toml`, and `main`. + /// + /// # Errors + /// + /// Fails if `root` isn't empty, the policy doesn't make `node` the + /// authority of both targets, or the repository cannot be written. + pub fn create(root: PathBuf, node: Node, policy: &str) -> Result { + let not_empty = std::fs::read_dir(&root).is_ok_and(|mut entries| entries.next().is_some()); + if not_empty { + return Err(ServiceError::NotEmpty(root)); + } + let store = Store::new(root, Native::default()); + store.init()?; + Queue::new(&store, &node.key, node.name.clone()).init(policy)?; + Ok(Self::new(store, node)) + } + + /// Opens the repository without a working copy in `root`, which + /// [`OriginService::create`] made. + /// + /// # Errors + /// + /// Fails if `root` has no repository, or is on a network file system. + pub fn open(root: PathBuf, node: Node) -> Result { + let store = Store::open_writable(root, Native::default())?; + if store.head(&TargetName::POLICY)?.is_none() { + return Err(ServiceError::NotARepository(store.root().to_owned())); + } + Ok(Self::new(store, node)) + } + + /// The repository's storage. + #[must_use] + pub fn store(&self) -> &Store { + &self.store + } + + /// Runs `call` with the statements of the repository, through one of the + /// indexes kept open, caught up first, or a new one if they're all in + /// use. + fn annotations<'s, T>( + &'s self, + call: impl FnOnce(&mut Annotations<'s>) -> Result, + ) -> Result { + let kept = self.kept_indexes().pop(); + // A failed refresh drops the index, to read whole next time. + let index = match kept { + Some(mut index) => { + index.refresh(&self.store)?; + index + } + None => Index::open(&self.store)?, + }; + let mut annotations = Annotations::new(&self.store, index); + let result = call(&mut annotations); + let mut kept = self.kept_indexes(); + if kept.len() < Self::KEPT_INDEXES { + kept.push(annotations.into_index()); + } + result + } + + fn kept_indexes(&self) -> MutexGuard<'_, Vec> { + self.indexes.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// The statements about `subject`, in the order the repository received + /// them. + /// + /// # Errors + /// + /// Fails if the index or a statement cannot be read. + pub fn statements( + &self, + _caller: &Caller, + subject: RecordId, + ) -> Result, ServiceError> { + self.annotations(|annotations| Ok(annotations.about(subject)?)) + } + + /// The revisions of `change`, and its heads. + /// + /// # Errors + /// + /// Fails if the repository has no revision of the change, or cannot + /// read one. + pub fn revisions(&self, _caller: &Caller, change: ChangeId) -> Result { + let (ids, heads) = self.annotations(|annotations| { + let index = annotations.index(); + Ok((index.revisions(change).to_vec(), index.heads(change))) + })?; + if ids.is_empty() { + return Err(ServiceError::UnknownChange(change)); + } + let revisions = ids + .into_iter() + .map(|id| { + Ok(RevisionEntry { + id, + revision: self.store.get(id)?, + }) + }) + .collect::>()?; + Ok(Revisions { revisions, heads }) + } + + /// Every target, by name, with its tip, and its authority and + /// requirements under the policy in force. + /// + /// # Errors + /// + /// Fails if the targets or the policy cannot be read. + pub fn targets(&self, _caller: &Caller) -> Result, ServiceError> { + let policy = Policy::load(&self.store)?; + let mut names = self.store.targets()?; + names.sort(); + let mut targets = Vec::new(); + for name in names { + let Some(head) = self.store.head(&name)? else { + continue; + }; + targets.push(TargetInfo { + authority: policy.authority(&name).cloned(), + requirements: policy.requirements(&name).to_vec(), + head, + name, + }); + } + Ok(targets) + } + + /// The acceptances of `target` from position `since` on, oldest first. + /// + /// # Errors + /// + /// Fails if the target doesn't exist, or its log or an acceptance + /// cannot be read. + pub fn log( + &self, + _caller: &Caller, + target: &TargetName, + since: u64, + ) -> Result, ServiceError> { + if self.store.head(target)?.is_none() { + return Err(ServiceError::UnknownTarget(target.clone())); + } + self.store + .log_since(target, since)? + .into_iter() + .map(|id| { + Ok(LogEntry { + id, + acceptance: self.store.get(id)?, + }) + }) + .collect() + } + + /// Lands what `request` proposes, with this node as the authority: a + /// change with the changes below it the target doesn't have yet, or + /// another target's tip. A change lands by default on the target its + /// stack is on. + /// + /// # Errors + /// + /// Fails if the change or a target doesn't exist, a target was given + /// no target to land on, this node isn't the target's authority, the + /// change can't land as it is (see [`LandError`]), or the records + /// cannot be read or written. + pub fn land(&self, _caller: &Caller, request: &LandRequest) -> Result { + let queue = Queue::new(&self.store, &self.node.key, self.node.name.clone()); + self.annotations(|annotations| { + let landed = match &request.proposal { + Proposal::Change(change) => { + let onto = match &request.onto { + Some(onto) => onto.clone(), + None => self.target_of(annotations.index(), *change)?, + }; + let landings = queue.land_change(annotations, *change, &onto)?; + Landings { onto, landings } + } + Proposal::Target(source) => { + let onto = request.onto.clone().ok_or(ServiceError::NoTarget)?; + let landing = queue.land_target(annotations, source, &onto)?; + Landings { + onto, + landings: vec![landing], + } + } + }; + Ok(landed) + }) + } + + /// The target the stack of `change` is on: that of the acceptance at + /// the bottom of its head's stack. + fn target_of(&self, index: &Index, change: ChangeId) -> Result { + let head = match index.heads(change)[..] { + [head] => head, + [] => return Err(ServiceError::UnknownChange(change)), + ref heads => { + return Err(LandError::Divergent { + change, + heads: heads.to_vec(), + } + .into()); + } + }; + let mut base = self.store.get(head)?.base; + let acceptance = loop { + match base { + Base::Revision(id) => base = self.store.get(id)?.base, + Base::Acceptance(id) => break id, + } + }; + let target = self.store.get(acceptance)?.body().target; + Ok(self + .store + .target_name(target)? + .ok_or(StoreError::NotFound(acceptance.into()))?) + } + + /// Every landing that waits, on every target, and why. + /// + /// # Errors + /// + /// Fails if the queues cannot be read. + pub fn landings(&self, _caller: &Caller) -> Result, ServiceError> { + Ok(Queue::pending(&self.store)?) + } + + /// Creates a target at the tip of another, with this node as its + /// authority. + /// + /// # Errors + /// + /// Fails if the name is taken, the other target doesn't exist, the + /// policy wouldn't make this node the new target's authority, or the + /// records cannot be written. + pub fn create_target( + &self, + _caller: &Caller, + request: &NewTarget, + ) -> Result { + let queue = Queue::new(&self.store, &self.node.key, self.node.name.clone()); + Ok(queue.create_target(&request.name, &request.from)?) + } +} + +/// A failed service call. +#[derive(Debug, thiserror::Error)] +pub enum ServiceError { + /// A directory holds no repository. + #[error("{} is not an origin repository", .0.display())] + NotARepository(PathBuf), + /// `create` was pointed at a directory with files in it. + #[error("{} is not empty", .0.display())] + NotEmpty(PathBuf), + /// No revision of the change is known. + #[error("change {} has no revisions", .0.short())] + UnknownChange(ChangeId), + /// No target has this name. + #[error("no target is named `{0}`")] + UnknownTarget(TargetName), + /// A target was proposed for landing without a target to land on. + #[error("landing a target needs a target to land on")] + NoTarget, + /// A landing failed. + #[error(transparent)] + Land(#[from] LandError), + /// The policy cannot be read. + #[error(transparent)] + Policy(#[from] PolicyError), + /// Records cannot be read or written. + #[error(transparent)] + Store(#[from] StoreError), +} + +impl ServiceError { + /// What kind of failure it is, for clients to tell apart. + #[must_use] + pub fn code(&self) -> ErrorCode { + match self { + Self::UnknownChange(_) | Self::UnknownTarget(_) => ErrorCode::NotFound, + Self::NoTarget => ErrorCode::BadRequest, + Self::Land(error) => match error { + LandError::UnknownTarget(_) | LandError::UnknownChange(_) => ErrorCode::NotFound, + LandError::TargetExists(_) + | LandError::SameTarget(_) + | LandError::NoAuthority(_) + | LandError::NotAuthority { .. } + | LandError::WrongKey(_) + | LandError::Divergent { .. } + | LandError::Abandoned(_) + | LandError::Unresolved { .. } + | LandError::InvalidPolicy(_) => ErrorCode::Conflict, + LandError::Store(error) => Self::store_code(error), + LandError::Policy(_) | LandError::Annotate(_) => ErrorCode::Internal, + }, + Self::Store(error) => Self::store_code(error), + Self::NotARepository(_) | Self::NotEmpty(_) | Self::Policy(_) => ErrorCode::Internal, + } + } + + fn store_code(error: &StoreError) -> ErrorCode { + match error { + StoreError::NotFound(_) => ErrorCode::NotFound, + StoreError::Expired { .. } => ErrorCode::Expired, + StoreError::Conflict { .. } => ErrorCode::Conflict, + _ => ErrorCode::Internal, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn calls_using_the_index_do_not_wait_for_each_other() { + let dir = tempfile::tempdir().unwrap(); + let node = Node { + name: "hosted".parse().unwrap(), + key: Arc::new(NodeKey::from_bytes(&[7; 32])), + }; + let policy = Policy::initial(&node.name, &node.key.public()); + let service = OriginService::create(dir.path().join("repo"), node, &policy).unwrap(); + // A landing holds an index all along: a read meanwhile takes another. + service + .annotations(|_| service.annotations(|_| Ok(()))) + .unwrap(); + assert_eq!(service.kept_indexes().len(), 2, "both kept for later calls"); + } +} diff --git a/apps/origin-src/src/targets.rs b/apps/origin-src/src/targets.rs index 072247bd..49431a1d 100644 --- a/apps/origin-src/src/targets.rs +++ b/apps/origin-src/src/targets.rs @@ -150,18 +150,44 @@ impl Store

{ /// /// Fails if the target's files cannot be read or are malformed. pub fn log(&self, target: &TargetName) -> Result, StoreError> { + self.log_since(target, 0) + } + + /// The acceptances of `target` from position `since` on, oldest first. + /// Reads only those lines of the log. + /// + /// # Errors + /// + /// Fails if the target's files cannot be read or are malformed. + pub fn log_since( + &self, + target: &TargetName, + since: u64, + ) -> Result, StoreError> { let files = self.target_files(target.id()); let Some(head) = files.read_head()? else { return Ok(Vec::new()); }; - let bytes = TargetFiles::read(&files.log())?.unwrap_or_default(); - let mut log = files.parse_log(&bytes)?; - // The log can be ahead of the head while an append is in progress. - let published = usize::try_from(head.seq + 1).unwrap_or(usize::MAX); - if log.len() < published || log[published - 1] != head.acceptance { - return Err(StoreError::Malformed(files.log())); + if since > head.seq { + return Ok(Vec::new()); + } + // The log can be ahead of the head while an append is in progress: + // read only up to the head. + let path = files.log(); + let line = TargetFiles::LINE as u64; + let len = usize::try_from((head.seq + 1 - since) * line) + .map_err(|_| StoreError::Malformed(path.clone()))?; + let mut bytes = vec![0; len]; + File::open(&path) + .and_then(|log| log.read_exact_at(&mut bytes, since * line)) + .map_err(|source| match source.kind() { + io::ErrorKind::UnexpectedEof => StoreError::Malformed(path.clone()), + _ => StoreError::io(&path, source), + })?; + let log = files.parse_log(&bytes)?; + if log.last() != Some(&head.acceptance) { + return Err(StoreError::Malformed(path)); } - log.truncate(published); Ok(log) } @@ -436,6 +462,8 @@ mod tests { assert_eq!(store.acceptance_at(main.id(), seq).unwrap(), Some(id)); } assert_eq!(store.acceptance_at(main.id(), 3).unwrap(), None); + assert_eq!(store.log_since(&main, 1).unwrap(), ids[1..]); + assert_eq!(store.log_since(&main, 3).unwrap(), []); let last = store.get(ids[2]).unwrap(); assert_eq!(last.body().prev, Some(ids[1])); last.verify(&key().public()).unwrap(); diff --git a/apps/origin-src/src/workspace/annotate.rs b/apps/origin-src/src/workspace/annotate.rs index 827a2919..9d95bae5 100644 --- a/apps/origin-src/src/workspace/annotate.rs +++ b/apps/origin-src/src/workspace/annotate.rs @@ -16,6 +16,7 @@ use super::{WorkingCopy, Workspace, WorkspaceError}; use crate::annotations::{AnnotateError, Annotations}; use crate::index::{FindError, Index}; use crate::policy::Policy; +use crate::service::{Caller, OriginService}; use crate::store::StoreError; use crate::tree::Snapshots; @@ -235,29 +236,32 @@ impl Workspace { pub fn statements(&mut self, rev: &str) -> Result<(), WorkspaceError> { let working_copy = self.snapshot()?; let revision = working_copy.find_revision(rev)?; - let annotations = Annotations::new(&self.store, working_copy.index); + let service = self.service(Some(working_copy.index))?; let subject = RecordId::Revision(revision); - if annotations.index().statements(subject).is_empty() { + if !self.print_statements(&service, subject, "", &mut HashSet::new())? { println!("No statements about revision {}", revision.short()); } - self.print_statements(&annotations, subject, "", &mut HashSet::new()) + Ok(()) } - /// Prints the statements about `subject`, each one's lines after - /// `indent`, then the statements about it, indented further. `shown` - /// keeps a statement from printing twice, so a malformed store's cycle - /// ends. + /// Prints the statements about `subject` the user sees, as `service` + /// lists them, each one's lines after `indent`, then the statements + /// about it, indented further. `shown` keeps a statement from printing + /// twice, so a malformed store's cycle ends. Returns whether it printed + /// any. fn print_statements( &self, - annotations: &Annotations, + service: &OriginService, subject: RecordId, indent: &str, shown: &mut HashSet, - ) -> Result<(), WorkspaceError> { - for annotation in annotations.about(subject)? { + ) -> Result { + let mut printed = false; + for annotation in service.statements(&Caller::Owner, subject)? { if !shown.insert(annotation.id) { continue; } + printed = true; let statement = &annotation.statement; let verdict = match statement.verdict { Some(verdict) => format!(" {verdict}"), @@ -298,9 +302,9 @@ impl Workspace { } let deeper = format!("{indent} "); let about = RecordId::Statement(annotation.id); - self.print_statements(annotations, about, &deeper, shown)?; + self.print_statements(service, about, &deeper, shown)?; } - Ok(()) + Ok(printed) } /// A payload's first line if it's text, its size otherwise, or that this diff --git a/apps/origin-src/src/workspace/land.rs b/apps/origin-src/src/workspace/land.rs index c319035a..0dc23738 100644 --- a/apps/origin-src/src/workspace/land.rs +++ b/apps/origin-src/src/workspace/land.rs @@ -1,7 +1,9 @@ //! The target commands: `land`, `target new` and `targets`, and starting a //! change on a target with `new --on`. //! -//! The queue runs in this process, as this node. After a landing, the +//! They go through the repository's +//! [`OriginService`](crate::service::OriginService), whose queue runs in +//! this process, as this node. After a landing, the //! working copy of the workspace that ran it follows its change: when it //! landed, or the target already had it, the working copy starts a new //! change on the target's tip, so later edits are made on what the target @@ -18,18 +20,17 @@ use std::mem; +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, }; use super::{Behind, WorkingCopy, Workspace, WorkspaceError}; -use crate::annotations::Annotations; use crate::conflict::Conflicts; use crate::index::Index; use crate::oplog::Why; -use crate::policy::Policy; -use crate::queue::Queue; +use crate::service::Caller; use crate::tree::Merge; impl Workspace { @@ -48,17 +49,13 @@ impl Workspace { ) -> Result<(), WorkspaceError> { let mut working_copy = self.save_draft()?; let change = working_copy.find_change(change.unwrap_or("@"))?; - let onto = match onto { - Some(onto) => onto, - None => self.target_of(Self::single_head(&working_copy.index, change)?)?, + let request = LandRequest { + proposal: Proposal::Change(change), + onto, }; - let key = self.config.node_key()?; - let mut annotations = Annotations::new(&self.store, mem::take(&mut working_copy.index)); - let landings = Queue::new(&self.store, &key, self.config.node().clone()).land_change( - &mut annotations, - change, - &onto, - )?; + let Landings { onto, landings } = self + .service(Some(mem::take(&mut working_copy.index)))? + .land(&Caller::Owner, &request)?; for landing in &landings { self.print_landing(landing, &onto)?; } @@ -85,13 +82,15 @@ impl Workspace { /// Fails if a target doesn't exist, this node isn't the authority of /// `onto`, or the records cannot be read or written. pub fn land_target(&self, from: &TargetName, onto: &TargetName) -> Result<(), WorkspaceError> { - let key = self.config.node_key()?; - let landing = Queue::new(&self.store, &key, self.config.node().clone()).land_target( - &mut Annotations::open(&self.store)?, - from, - onto, - )?; - self.print_landing(&landing, onto) + let request = LandRequest { + proposal: Proposal::Target(from.clone()), + onto: Some(onto.clone()), + }; + let landed = self.service(None)?.land(&Caller::Owner, &request)?; + for landing in &landed.landings { + self.print_landing(landing, onto)?; + } + Ok(()) } /// `origin land --status`: lists the landings that wait, and why. @@ -100,7 +99,7 @@ impl Workspace { /// /// Fails if the queues cannot be read. pub fn land_status(&self) -> Result<(), WorkspaceError> { - let pending = Queue::pending(&self.store)?; + let pending = self.service(None)?.landings(&Caller::Owner)?; if pending.is_empty() { println!("No landing waits."); } @@ -118,16 +117,19 @@ impl Workspace { /// Fails if the name is taken, `from` doesn't exist, this node wouldn't /// be the target's authority, or the records cannot be written. pub fn target_new(&self, name: &TargetName, from: &TargetName) -> Result<(), WorkspaceError> { - let key = self.config.node_key()?; - Queue::new(&self.store, &key, self.config.node().clone()).create_target(name, from)?; - let tip = self - .store - .head(from)? - .ok_or_else(|| WorkspaceError::UnknownTarget(from.clone()))?; - println!( - "Created target `{name}` at {}", - self.describe_acceptance(tip.acceptance)? - ); + let request = NewTarget { + name: name.clone(), + from: from.clone(), + }; + let head = self + .service(None)? + .create_target(&Caller::Owner, &request)?; + let landed = self.store.get(head.acceptance)?.body().landed.clone(); + let from = match landed[..] { + [Source::Target(from)] => self.describe_acceptance(from)?, + _ => format!("`{from}`"), + }; + println!("Created target `{name}` at {from}"); Ok(()) } @@ -138,22 +140,17 @@ impl Workspace { /// /// Fails if the targets or the policy cannot be read. pub fn targets(&self) -> Result<(), WorkspaceError> { - let policy = Policy::load(&self.store)?; - let mut targets = self.store.targets()?; - targets.sort(); - for target in targets { - let Some(tip) = self.store.head(&target)? else { - continue; - }; - let authority = policy - .authority(&target) + for target in self.service(None)?.targets(&Caller::Owner)? { + let authority = target + .authority .map_or_else(|| "no authority".to_owned(), |node| format!("node:{node}")); println!( - "{target} #{} {} ({authority})", - tip.seq, - tip.acceptance.short() + "{} #{} {} ({authority})", + target.name, + target.head.seq, + target.head.acceptance.short() ); - for requirement in policy.requirements(&target) { + for requirement in &target.requirements { println!(" requires {requirement}"); } } @@ -285,20 +282,6 @@ impl Workspace { Ok(true) } - /// The target a revision's stack is on: that of the acceptance at its - /// bottom. - fn target_of(&self, revision: RevisionId) -> Result { - let mut base = self.store.get(revision)?.base; - loop { - match base { - Base::Revision(id) => base = self.store.get(id)?.base, - Base::Acceptance(id) => { - return self.target_name(self.store.get(id)?.body().target); - } - } - } - } - /// Moves the working copy onto `rebased`, the landing queue's rebase of /// it, with the edits made since in a revision after it. fn move_onto( diff --git a/apps/origin-src/src/workspace/mod.rs b/apps/origin-src/src/workspace/mod.rs index d7f70bf9..98faa9e5 100644 --- a/apps/origin-src/src/workspace/mod.rs +++ b/apps/origin-src/src/workspace/mod.rs @@ -75,12 +75,14 @@ use std::fs; use std::io; use std::mem; use std::path::{Path, PathBuf}; +use std::sync::Arc; use origin_platform::{LockedFile, Native}; +use origin_shared::api::{RevisionEntry, Revisions}; use origin_shared::{ - AcceptanceId, Base, BlobId, ChangeId, EncodedObject, Kind, NodePublicKey, Principal, Record, - RecordId, RepoPath, Revision, RevisionId, Source, Statement, StatementId, TargetId, TargetName, - Tree, TreeId, + AcceptanceId, Base, BlobId, ChangeId, EncodedObject, Kind, Principal, Record, RecordId, + RepoPath, Revision, RevisionId, Source, Statement, StatementId, TargetId, TargetName, Tree, + TreeId, }; use crate::ancestry::Ancestry; @@ -90,8 +92,9 @@ use crate::conflict::Conflicts; use crate::index::{FindChangeError, FindError, Index}; use crate::oplog::{Actor, Effect, Move, Why}; use crate::output::FileDiff; -use crate::policy::PolicyError; +use crate::policy::{Policy, PolicyError}; use crate::queue::{LandError, Queue}; +use crate::service::{Caller, Node, OriginService, ServiceError}; use crate::store::{Store, StoreError}; use crate::worktree::{CloneSource, SnapshotError, StatCache, Worktree}; @@ -247,7 +250,7 @@ impl Workspace { let store = Store::new(meta, Native::default()).with_actor(actor.in_workspace(&root)); store.init()?; - let policy = Self::policy(&config, &key.public()); + let policy = Policy::initial(config.node(), &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""); @@ -281,32 +284,6 @@ impl Workspace { Ok(workspace) } - /// 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(); - format!( - "# Who may land what. Changing it is a landing on `policy`.\n\ - \n\ - # Each node's public key.\n\ - [nodes]\n\ - \"{node}\" = \"{key}\"\n\ - \n\ - # Groups of users and nodes, for requirements:\n\ - # [groups]\n\ - # runners = [\"node:ci-1\"]\n\ - \n\ - # The node ordering each target, and the statements landing needs.\n\ - [targets.policy]\n\ - authority = \"node:{node}\"\n\ - \n\ - [targets.main]\n\ - authority = \"node:{node}\"\n\ - # require = [{{ kind = \"ci.test\", verdict = \"pass\", issuer = \"group:runners\" }}]\n" - ) - } - /// Opens the working copy containing `start`, for `actor` to write in. /// /// # Errors @@ -442,6 +419,21 @@ impl Workspace { &self.root } + /// The service of this repository, run by this node, which the commands + /// that the API also offers go through. It finds records through + /// `index`, if the command just read it, or else reads it once needed. + fn service(&self, index: Option) -> Result { + let node = Node { + name: self.config.node().clone(), + key: Arc::new(self.config.node_key()?), + }; + let service = OriginService::new(self.store.clone(), node); + Ok(match index { + Some(index) => service.with_index(index), + None => service, + }) + } + /// Snapshots the working copy into a draft, recording nothing, for the /// commands that only read it. fn snapshot(&mut self) -> Result { @@ -1278,10 +1270,12 @@ impl Workspace { Some(target) => target, None => self.target_name(on)?, }; - let log = self.store.log(&target)?; - if log.is_empty() { - return Err(WorkspaceError::UnknownTarget(target)); - } + // Only the last `limit` acceptances are read. + let since = match (limit, self.store.head(&target)?) { + (Some(limit), Some(head)) => (head.seq + 1).saturating_sub(limit as u64), + _ => 0, + }; + let log = self.service(None)?.log(&Caller::Owner, &target, since)?; if target.id() == on { for (id, revision) in &stack { let marker = if *id == working_copy.id { '@' } else { '○' }; @@ -1292,14 +1286,10 @@ impl Workspace { ); } } - let shown = log - .iter() - .enumerate() - .rev() - .take(limit.unwrap_or(usize::MAX)); - for (seq, &id) in shown { - println!("◆ {target} #{seq} {}", id.short()); - for source in &self.store.get(id)?.body().landed { + for entry in log.iter().rev() { + let body = entry.acceptance.body(); + println!("◆ {target} #{} {}", body.seq, entry.id.short()); + for source in &body.landed { match *source { Source::Revision(id) => { let revision = self.store.get(id)?; @@ -1325,16 +1315,18 @@ impl Workspace { /// /// Fails if the change cannot be found, or a record cannot be read. pub fn evolog(&mut self, change: &str) -> Result<(), WorkspaceError> { - let working_copy = self.snapshot()?; - let index = &working_copy.index; + let mut working_copy = self.snapshot()?; let change = working_copy.find_change(change)?; - let heads = index.heads(change); - println!("Change {}{}", change.short(), self.flags(index, change)?); - for &id in index.revisions(change).iter().rev() { - let revision: Revision = self.store.get(id)?; + let flags = self.flags(&working_copy.index, change)?; + let Revisions { revisions, heads } = self + .service(Some(mem::take(&mut working_copy.index)))? + .revisions(&Caller::Owner, change)?; + println!("Change {}{flags}", change.short()); + for RevisionEntry { id, revision } in revisions.iter().rev() { + let id = *id; let marker = if id == working_copy.id { '@' } else { '○' }; let head = if heads.contains(&id) { " (head)" } else { "" }; - println!("{marker} {} {}{head}", id.short(), self.summary(&revision)?); + println!("{marker} {} {}{head}", id.short(), self.summary(revision)?); if revision.predecessors.len() > 1 { println!(" converges {}", Self::list(&revision.predecessors)); } @@ -1625,6 +1617,9 @@ pub enum WorkspaceError { /// A landing failed. #[error(transparent)] Land(#[from] LandError), + /// The repository's service refused a call. + #[error(transparent)] + Service(#[from] ServiceError), /// `undo` found no operation of this workspace to take back. #[error("nothing to undo: no operation moved this workspace's working copy")] NothingToUndo,