From 5ca0953e4c159f405459d3875481e117e0964f55 Mon Sep 17 00:00:00 2001 From: piquel Date: Mon, 23 Nov 2026 15:57:46 +0100 Subject: [PATCH] feat(cli): land and watch through the remote The chains of a remote's targets are copies of the remote's, which only the remote extends, even when this node is their authority. So `land`, `land --from` and `target new` go to the remote's queue for every target the remote has: `land` pushes the stack first, and each fetches the target's chain and the landed records after. Targets only this repository has still land here. A change with no `--onto` lands on the target its stack is on, which `Store::stack_target` finds. `targets` and `land --status` show the remote's targets and waiting landings with this repository's own, and `watch` long-polls the remote's events, or with `--local`, this node's. A landing is decided on the evidence the remote holds when it's tried: send a statement together with the one it supersedes, as `push` does. --- AGENTS.md | 2 +- README.md | 20 +++-- apps/origin-src/src/cli.rs | 9 ++- apps/origin-src/src/service.rs | 17 +--- apps/origin-src/src/targets/mod.rs | 20 +++++ apps/origin-src/src/workspace/land.rs | 111 +++++++++++++++++++------- apps/origin-src/src/workspace/ops.rs | 17 ++-- apps/origin-src/tests/sync.rs | 93 ++++++++++++++++++++- crates/origin-shared/src/landing.rs | 12 +++ docs/design.md | 13 +++ standard.toml | 1 - 11 files changed, 257 insertions(+), 58 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index c1df9e62..2b2119e4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -42,7 +42,7 @@ End-to-end tests run the `origin` binary with `ORIGIN_CONFIG_DIR` set to a temporary directory, which holds the user's `config.toml` and node key. The HTTP tests drive every SDK method against a real server. One fails while `docs/openapi.json` is stale: `just openapi` rewrites it. The sync -tests clone, push and fetch through `origin serve` and through local paths; +tests clone, push and land through `origin serve` and through local paths; `tests/common` holds the helpers every end-to-end test shares. ## Validation diff --git a/README.md b/README.md index a2a2260c..d844cfd5 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,7 @@ origin workspace list | rm origin op log [-n ] # what this node did, operation by operation, in every workspace origin undo # move this workspace's working copy back one operation -origin watch [--kind ] [--subject ] [--since ] # events, as they happen +origin watch [--kind ] [--subject ] [--since ] [--local] # events, as they happen origin clone [] [--target ] # follow a remote's target, starting a change on its tip origin remote [] # show or set the remote: http://host:port/, or a path @@ -97,9 +97,14 @@ snapshots only when a command reads them, starting with its target's tip. `push` shares revisions, their files and statements, and refuses a change the remote has a newer revision of, even one pushed while it sends: `fetch`, then `converge` it. A statement that needs one the remote lacks -stays, and the push says so. Fetching never changes your files; `pull` -then moves the working copy onto its target's new tip, like a landing -elsewhere does. +stays, and the push says so. A landing is decided on the evidence the +remote holds when it's tried: send a statement together with the one it +supersedes, as `push` does, or a landing waiting on the first may take it. +`land`, `land --from` and `target +new` go to the remote's queue for every target the remote has, after pushing +what lands, and `watch` long-polls the remote's events (`--local` for this +node's). Fetching never changes your files; `pull` then moves the working +copy onto its target's new tip, like a landing elsewhere does. Changes are named by a unique prefix of their id, or `@` for the working copy's. A revision is `@`, a change (for its head), or a unique prefix of @@ -142,9 +147,10 @@ demo = "repos/demo" The HTTP API, under `/api/v1`, puts records in batches, if the changes they revise are where the client saw them, and fetches them by id, walks snapshots for the trees and blobs a client lacks (the only way files leave -a server), in parts of at most 64 MiB each way, compares the records of changes, -lists statements, revisions, targets and their logs, lands changes and -targets, and streams events by long-poll: `GET +a server), in parts of at most 64 MiB each way, compares the records of +changes, lists statements, revisions, targets and their logs, lands +changes and targets, and streams +events by long-poll: `GET /api/v1/repos//events?cursor=&wait=30s` answers as soon as there are events after the cursor, with a JSON batch, the next cursor, and the generation of the op log it's of: pass it back as `generation`, and a diff --git a/apps/origin-src/src/cli.rs b/apps/origin-src/src/cli.rs index 5e93695a..4f1d0a44 100644 --- a/apps/origin-src/src/cli.rs +++ b/apps/origin-src/src/cli.rs @@ -216,7 +216,8 @@ enum WorkspaceCommand { changes: Vec, }, /// Print events as they happen, one per line. The first line is the cursor - /// to resume from. Runs until interrupted. + /// to resume from. Watches the remote's events if the repository has a + /// remote. Runs until interrupted. Watch { /// Only show events with this name, such as `check.requested`, or events /// about statements of this kind, such as `core.conflict` or `ci.*`. @@ -230,6 +231,9 @@ enum WorkspaceCommand { /// event kept. #[arg(long)] since: Option, + /// Watch this node's events instead of the remote's. + #[arg(long)] + local: bool, }, } @@ -571,7 +575,8 @@ impl WorkspaceCommand { kind, subject, since, - } => workspace.watch(kind, subject, since)?, + local, + } => workspace.watch(kind, subject, since, local)?, } Ok(()) } diff --git a/apps/origin-src/src/service.rs b/apps/origin-src/src/service.rs index 916be03d..5ae40648 100644 --- a/apps/origin-src/src/service.rs +++ b/apps/origin-src/src/service.rs @@ -631,8 +631,8 @@ impl OriginService { landed } - /// Returns the target the stack of `change` is on: the target of the acceptance - /// at the bottom of its head's stack. + /// Returns the target the stack of `change` is on: the target of its head's + /// stack. fn target_of(&self, index: &Index, change: ChangeId) -> Result { let head = match index.heads(change)[..] { [head] => head, @@ -645,18 +645,7 @@ impl OriginService { .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()))?) + Ok(self.store.stack_target(head)?) } /// Lists every landing waiting on every target, and why it waits. diff --git a/apps/origin-src/src/targets/mod.rs b/apps/origin-src/src/targets/mod.rs index 2b560245..eee20708 100644 --- a/apps/origin-src/src/targets/mod.rs +++ b/apps/origin-src/src/targets/mod.rs @@ -270,6 +270,26 @@ impl Store

{ .then_some(next)) } + /// Returns the target the stack of `revision` is on: the target of the + /// acceptance at the bottom of the stack, found by following bases. + /// + /// # Errors + /// + /// Fails if a record of the stack cannot be read, or the store doesn't + /// know the target's name. + pub fn stack_target(&self, revision: RevisionId) -> Result { + let mut base = self.get(revision)?.base; + let acceptance = loop { + match base { + Base::Revision(id) => base = self.get(id)?.base, + Base::Acceptance(id) => break id, + } + }; + let target = self.get(acceptance)?.body().target; + self.target_name(target)? + .ok_or(StoreError::NotFound(acceptance.into())) + } + /// The name of the target `id`, or `None` if it doesn't exist. /// /// # Errors diff --git a/apps/origin-src/src/workspace/land.rs b/apps/origin-src/src/workspace/land.rs index 2b02595e..bd48ef0b 100644 --- a/apps/origin-src/src/workspace/land.rs +++ b/apps/origin-src/src/workspace/land.rs @@ -3,21 +3,13 @@ //! //! They go through the repository's //! [`OriginService`](crate::service::OriginService), whose landing queue runs -//! in this process, as this node. After a landing, the working copy of the -//! workspace that ran it follows its change. If the change landed, or the -//! target already had it, the working copy starts a new change on the target's -//! tip, so later edits build on what the target has. If the queue rebased the -//! change, the working copy moves to the rebased revision. If the working copy -//! is on top of a change that landed, it is rebased onto the tip. -//! -//! Other workspaces don't move: they are behind their change until `origin -//! pull` moves them the same way, merging the edits made since. Where those -//! edits conflict, the files hold both versions between conflict markers, and a -//! `core.conflict` statement lists them. The working copy can't land until -//! those files change or `origin resolve` accepts them (see -//! [`conflict`](crate::conflict)). +//! in this process, as this node. If the repository has a remote that has the +//! target, they go to the remote instead, whose node must be the target's +//! authority: `land` pushes the stack first, then fetches the target's chain +//! and the stack's records. After a landing, the working copy follows its +//! change (see "Behind" in `docs/design.md`). -use std::mem; +use std::{mem, slice}; use origin_shared::api::{LandRequest, Landings, NewTarget}; use origin_shared::landing::{Blocked, Landing, Pending, Proposal}; @@ -29,6 +21,7 @@ use super::{Behind, WorkingCopy, Workspace, WorkspaceError}; use crate::conflict::Conflicts; use crate::index::Index; use crate::oplog::Why; +use crate::remote::Remote; use crate::service::Caller; use crate::tree::Merge; @@ -48,13 +41,36 @@ impl Workspace { ) -> Result<(), WorkspaceError> { let mut working_copy = self.save_draft()?; let change = working_copy.find_change(change.unwrap_or("@"))?; + let onto = if let Some(onto) = onto { + onto + } else { + let head = Self::single_head(&working_copy.index, change)?; + self.store.stack_target(head)? + }; let request = LandRequest { proposal: Proposal::Change(change), - onto, + onto: Some(onto.clone()), + }; + let Landings { onto, landings } = match self.remote_queue(&onto)? { + Some(remote) => { + let sync = self.sync(remote); + sync.push(&[change])?; + let landed = remote.land(&request)?; + sync.fetch_chains(slice::from_ref(&landed.onto))?; + let mut changes = vec![change]; + changes.extend(landed.landings.iter().filter_map( + |landing| match landing.proposal() { + Proposal::Change(change) => Some(*change), + Proposal::Target(_) => None, + }, + )); + sync.fetch_changes(&changes)?; + landed + } + None => self + .service(Some(mem::take(&mut working_copy.index)))? + .land(&Caller::Owner, &request)?, }; - 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,20 +101,31 @@ impl Workspace { proposal: Proposal::Target(from.clone()), onto: Some(onto.clone()), }; - let landed = self.service(None)?.land(&Caller::Owner, &request)?; + let landed = match self.remote_queue(onto)? { + Some(remote) => { + let landed = remote.land(&request)?; + self.sync(remote).fetch_chains(slice::from_ref(onto))?; + landed + } + None => 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 are waiting, and why. + /// `origin land --status`: lists the landings that are waiting, and why: first + /// in this node's queues, then in the remote's. /// /// # Errors /// /// Fails if the queues cannot be read. pub fn land_status(&self) -> Result<(), WorkspaceError> { - let pending = self.service(None)?.landings(&Caller::Owner)?; + let mut pending = self.service(None)?.landings(&Caller::Owner)?; + if let Some(remote) = self.remote()? { + pending.extend(remote.landings()?); + } if pending.is_empty() { println!("No landing waits."); } @@ -120,9 +147,16 @@ impl Workspace { name: name.clone(), from: from.clone(), }; - let head = self - .service(None)? - .create_target(&Caller::Owner, &request)?; + let head = match self.remote_queue(from)? { + Some(remote) => { + let head = remote.create_target(&request)?; + self.sync(remote).fetch_chains(slice::from_ref(name))?; + head + } + None => 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)?, @@ -133,13 +167,22 @@ impl Workspace { } /// `origin targets`: lists every target with its tip, its authority and what - /// landing on it requires. + /// landing on it requires. If the repository has a remote, lists the remote's + /// targets first, since this repository only holds those it follows, then this + /// repository's own. /// /// # Errors /// - /// Fails if the targets or the policy cannot be read. + /// Fails if the remote fails, or the targets or the policy cannot be read. pub fn targets(&self) -> Result<(), WorkspaceError> { - for target in self.service(None)?.targets(&Caller::Owner)? { + let mut targets = self.service(None)?.targets(&Caller::Owner)?; + if let Some(remote) = self.remote()? { + let remote = remote.targets()?; + targets.retain(|own| !remote.iter().any(|target| target.name == own.name)); + targets.extend(remote); + targets.sort_by(|a, b| a.name.cmp(&b.name)); + } + for target in targets { let authority = target .authority .map_or_else(|| "no authority".to_owned(), |node| format!("node:{node}")); @@ -156,6 +199,20 @@ impl Workspace { Ok(()) } + /// Returns the remote to submit landings on `target` to, or `None` if they land + /// here: when the repository has no remote, or `target` is this repository's + /// own, which the remote doesn't have. The chains of other targets are copies + /// of the remote's, which only the remote extends, even when this node is their + /// authority. + fn remote_queue(&self, target: &TargetName) -> Result, WorkspaceError> { + let Some(remote) = self.remote()? else { + return Ok(None); + }; + let own = self.store.head(target)?.is_some() + && !remote.targets()?.iter().any(|known| known.name == *target); + Ok((!own).then_some(remote)) + } + /// `origin new [description] --on `: starts a change on the tip of a /// target. /// diff --git a/apps/origin-src/src/workspace/ops.rs b/apps/origin-src/src/workspace/ops.rs index cd55c4c9..9b9356d8 100644 --- a/apps/origin-src/src/workspace/ops.rs +++ b/apps/origin-src/src/workspace/ops.rs @@ -204,20 +204,24 @@ impl Workspace { Err(WorkspaceError::NothingToUndo) } - /// `origin watch [--kind ]... [--subject ]... [--since - /// ]`: prints the events of those kinds about those subjects as they + /// `origin watch [--kind ]... [--subject ]... [--since ] + /// [--local]`: prints the events of those kinds about those subjects as they /// happen, one per line, from `since`, or from now. Without kinds or subjects, - /// prints every event. Runs until interrupted. + /// prints every event. The events are the remote's, long-polled, if the + /// repository has one, or this node's with `local`. Runs until interrupted. /// /// # Errors /// - /// Fails if the cursor expired, or the op log or a record cannot be read. + /// Fails if the cursor expired, the remote fails, or the op log or a record + /// cannot be read. pub fn watch( &self, kinds: Vec, subjects: Vec, since: Option, + local: bool, ) -> Result<(), WorkspaceError> { + let remote = if local { None } else { self.remote()? }; let service = self.service(None)?; let mut query = EventsQuery { cursor: since, @@ -228,7 +232,10 @@ impl Workspace { subject: List(subjects), }; loop { - let page = service.events(&Caller::Owner, &query)?; + let page = match remote { + Some(remote) => remote.events(&query)?, + None => service.events(&Caller::Owner, &query)?, + }; for event in &page.events { println!("{event}"); } diff --git a/apps/origin-src/tests/sync.rs b/apps/origin-src/tests/sync.rs index db58ac93..5d4a186b 100644 --- a/apps/origin-src/tests/sync.rs +++ b/apps/origin-src/tests/sync.rs @@ -1,12 +1,58 @@ //! End-to-end tests of sharing work: cloning, pushing, fetching and -//! pulling, over HTTP and through a local path. +//! pulling, and landing and watching against a remote, over HTTP and +//! through a local path. mod common; use std::fs; +use std::time::{Duration, Instant}; use common::{Repo, Server, User}; +#[test] +fn work_lands_through_the_server_and_reaches_other_clones() { + let server = Server::start(); + let (ada, bob) = (User::new("ada"), User::new("bob")); + let alice = Repo::clone(&ada, &server.url(), &[]); + assert!( + alice + .ok(&["status"]) + .ends_with("On top of: main #0\nNo changes.\n") + ); + alice.write("README.md", "hello\n"); + alice.write("src/lib.rs", "fn lib() {}\n"); + alice.ok(&["describe", "Add the library"]); + let change = alice.change(); + assert!(alice.ok(&["push"]).starts_with("Pushed ")); + assert_eq!(alice.ok(&["push"]), "Everything up to date.\n"); + let landed = alice.ok(&["land"]); + assert!( + landed.contains(&format!("Landed change {change}")), + "{landed}" + ); + assert!(landed.contains("on main #1"), "{landed}"); + + let bobs = Repo::clone(&bob, &server.url(), &[]); + assert_eq!(bobs.read("README.md"), "hello\n"); + assert_eq!(bobs.read("src/lib.rs"), "fn lib() {}\n"); + let log = bobs.ok(&["log"]); + assert!(log.contains(&format!("{change} Add the library")), "{log}"); + + bobs.write("notes.md", "bob\n"); + alice.write("README.md", "hello, world\n"); + alice.ok(&["land"]); + let pulled = bobs.ok(&["pull"]); + assert!(pulled.starts_with("`main`: #1 -> #2\n"), "{pulled}"); + assert_eq!(bobs.read("README.md"), "hello, world\n"); + assert_eq!(bobs.read("notes.md"), "bob\n"); + let status = bobs.ok(&["status"]); + assert!( + status.contains("On top of: main #2\nA notes.md\n"), + "{status}" + ); + assert!(bobs.ok(&["pull"]).ends_with("on the tip of `main`.\n")); +} + #[test] fn pushing_a_change_that_moved_on_the_server_is_refused() { let server = Server::start(); @@ -33,6 +79,28 @@ fn pushing_a_change_that_moved_on_the_server_is_refused() { assert!(alice.ok(&["push"]).starts_with("Pushed ")); } +#[test] +fn watch_follows_the_remote_events() { + let server = Server::start(); + let ada = User::new("ada"); + let alice = Repo::clone(&ada, &server.url(), &[]); + let watcher = Repo::clone(&ada, &server.url(), &[]); + let (mut watch, lines) = watcher.spawn(&["watch", "--kind", "target.advanced", "--since", "0"]); + alice.write("file", "content\n"); + alice.ok(&["land"]); + let deadline = Instant::now() + Duration::from_secs(20); + loop { + let line = lines + .recv_timeout(deadline.saturating_duration_since(Instant::now())) + .expect("the landing on main within the deadline"); + if line.contains("target.advanced target=main seq=1") { + break; + } + } + watch.kill().unwrap(); + watch.wait().unwrap(); +} + #[test] fn clones_make_the_directories_they_go_in() { let ada = User::new("ada"); @@ -67,6 +135,29 @@ fn clones_make_the_directories_they_go_in() { assert!(link.symlink_metadata().is_ok(), "the symlink stays"); } +#[test] +fn local_paths_are_remotes_served_in_process() { + let ada = User::new("ada"); + let origin = Repo::init(&ada); + origin.write("README.md", "hello\n"); + origin.ok(&["land"]); + + let url = origin.root().to_str().unwrap(); + let clone = Repo::clone(&ada, url, &[]); + assert_eq!(clone.read("README.md"), "hello\n"); + clone.write("src/lib.rs", "fn lib() {}\n"); + let landed = clone.ok(&["land"]); + assert!(landed.contains("on main #2"), "{landed}"); + let log = origin.ok(&["log", "main"]); + assert!(log.contains("◆ main #2"), "{log}"); + + let bobs = Repo::clone(&User::new("bob"), url, &[]); + assert_eq!(bobs.read("src/lib.rs"), "fn lib() {}\n"); + bobs.write("bob.txt", "bob\n"); + let error = bobs.fails(&["land"]); + assert!(error.contains("authority"), "{error}"); +} + #[test] fn clones_follow_one_target_and_fetch_others_on_demand() { let ada = User::new("ada"); diff --git a/crates/origin-shared/src/landing.rs b/crates/origin-shared/src/landing.rs index ab6e91d3..e5126654 100644 --- a/crates/origin-shared/src/landing.rs +++ b/crates/origin-shared/src/landing.rs @@ -65,6 +65,18 @@ pub enum Blocked { }, } +impl Landing { + /// Returns what the landing lands. + #[must_use] + pub fn proposal(&self) -> &Proposal { + match self { + Self::Landed { proposal, .. } + | Self::Unchanged(proposal) + | Self::Pending(Pending { proposal, .. }) => proposal, + } + } +} + impl fmt::Display for Proposal { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { diff --git a/docs/design.md b/docs/design.md index 82a31351..4c2ebe61 100644 --- a/docs/design.md +++ b/docs/design.md @@ -164,6 +164,19 @@ the exact content written there. ### Behind +After a landing, the working copy of the workspace that ran it follows its +change. If the change landed, or the target already had it, the working copy +starts a new change on the target's tip, so later edits build on what the target +has. If the queue rebased the change, the working copy moves to the rebased +revision. If the working copy is on top of a change that landed, it is rebased +onto the tip. + +Other workspaces don't move: they are behind their change until `origin pull` +moves them the same way, merging the edits made since. Where those edits +conflict, the files hold both versions between conflict markers, and a +`core.conflict` statement lists them. The working copy can't land until those +files change or `origin resolve` accepts them (see [Conflicts](#conflicts)). + A change can move on without the working copy. Its head may land from another workspace, or the queue may rebase it. The working copy is then *behind*: diff --git a/standard.toml b/standard.toml index 459c39d3..13060c93 100644 --- a/standard.toml +++ b/standard.toml @@ -110,7 +110,6 @@ paths = [ "apps/origin-src/src/store/mod.rs", "apps/origin-src/src/store/packs/mod.rs", "apps/origin-src/src/targets/mod.rs", - "apps/origin-src/src/workspace/land.rs", "apps/origin-src/src/workspace/mod.rs", "apps/origin-src/src/workspace/ops.rs", "apps/origin-src/src/workspace/registry.rs",