From a706f08ce38eac04c294993a7cdbcae88dffd7bd Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 16:03:51 +0100 Subject: [PATCH] feat(api): put records only onto the heads the client saw A push made from a stale view of a change would make it diverge on the server. `PUT records?expect==+,...` makes a put a compare-and-swap: the server checks that each change it names still has those heads while it publishes the revisions, and refuses with a conflict otherwise, publishing no record (snapshots, which change nothing, stay). The check and the publication hold one lock, `Store::lock_pushes`, which every put of revisions takes, and so does the landing queue before it publishes a rebase, once the head it rebased is still the change's only one: a push and a rebase never both move a change. A rebase that finds the change moved fails with `LandError::Moved`. `POST changes/inventory` tells a client what the server holds of some changes, their revisions, heads and statements by id, so it knows what to send and which heads to expect. And `GET log` takes a `limit`, so a client can check the server has one acceptance without reading the whole chain. --- README.md | 11 ++- apps/origin-src/src/http.rs | 51 ++++++++-- apps/origin-src/src/queue/mod.rs | 3 + apps/origin-src/src/queue/session.rs | 15 +++ apps/origin-src/src/service.rs | 136 ++++++++++++++++++++++---- apps/origin-src/src/store/mod.rs | 23 +++++ apps/origin-src/src/workspace/mod.rs | 11 ++- apps/origin-src/tests/http.rs | 61 +++++++++++- crates/origin-client/src/lib.rs | 25 +++-- crates/origin-shared/src/api.rs | 102 +++++++++++++++++++- docs/openapi.json | 137 ++++++++++++++++++++++++++- 11 files changed, 529 insertions(+), 46 deletions(-) diff --git a/README.md b/README.md index e29984ba..e319d8d6 100644 --- a/README.md +++ b/README.md @@ -119,11 +119,12 @@ key = "node.key" # its secret key, created if missing demo = "repos/demo" ``` -The HTTP API, under `/api/v1`, puts records in batches 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, lists statements, -revisions, targets and their logs, lands changes and targets, and streams -events by long-poll: `GET +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, 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 and the next cursor. [`docs/openapi.json`](docs/openapi.json) describes it, and diff --git a/apps/origin-src/src/http.rs b/apps/origin-src/src/http.rs index e97e63a5..01579d67 100644 --- a/apps/origin-src/src/http.rs +++ b/apps/origin-src/src/http.rs @@ -15,9 +15,9 @@ use axum::response::{IntoResponse, Response}; use origin_shared::ChangeId; use origin_shared::Head; use origin_shared::api::{ - Annotation, ApiError, ErrorCode, EventsQuery, FetchRecords, FetchSnapshot, LandRequest, - Landings, LogEntry, LogQuery, MORE, NewTarget, RepoName, RepoSummary, Revisions, - StatementsQuery, Stored, TargetInfo, + Annotation, ApiError, ErrorCode, EventsQuery, FetchRecords, FetchSnapshot, Inventory, + InventoryRequest, LandRequest, Landings, LogEntry, LogQuery, MORE, NewTarget, PutQuery, + RepoName, RepoSummary, Revisions, StatementsQuery, Stored, TargetInfo, }; use origin_shared::event::Page; use origin_shared::landing::Pending; @@ -45,7 +45,10 @@ type Repos = State>; pub struct Api; impl Api { - /// The largest request accepted, which bounds a batch of records put. + /// The largest request accepted, which bounds an object put: clients + /// split larger pushes into requests of at most + /// [`Pack::LIMIT`](origin_shared::pack::Pack::LIMIT), so only a single + /// object larger than that takes a request of its own this large. const MAX_REQUEST: usize = 1 << 30; fn documented() -> OpenApiRouter> { @@ -54,6 +57,7 @@ impl Api { .routes(routes!(fetch_records)) .routes(routes!(fetch_snapshot)) .routes(routes!(put_records)) + .routes(routes!(inventory)) .routes(routes!(statements)) .routes(routes!(revisions)) .routes(routes!(targets, create_target)) @@ -237,28 +241,57 @@ async fn fetch_snapshot( /// Puts a batch of objects, as a pack: snapshots, revisions and /// statements, each needing only objects the batch or the repository has, -/// of the kinds it names. +/// of the kinds it names. With `expect`, only if the changes it names have +/// the heads it says when the records are published. #[utoipa::path( put, path = "/api/v1/repos/{repo}/records", operation_id = "put_records", - params(("repo" = String, Path, description = "The repository")), + params(("repo" = String, Path, description = "The repository"), PutQuery), request_body(content = Binary, content_type = "application/octet-stream", description = "The objects, as a pack"), responses( (status = 200, description = "The objects are durable", body = Stored), (status = 400, description = "The pack is invalid, holds an acceptance, or needs objects the repository doesn't have, or has as another kind", body = ApiError), - (status = 404, description = "The repository does not exist", body = ApiError) + (status = 404, description = "The repository does not exist", body = ApiError), + (status = 409, description = "A change of `expect` has other heads now", body = ApiError) ) )] async fn put_records( repos: Repos, Path(repo): Path, + Query(query): Query, caller: Caller, body: Bytes, ) -> Result, HttpError> { let pack = Pack::decode(&body).map_err(HttpError::Pack)?; call(repos, repo, caller, move |service, caller| { - service.put_records(caller, pack) + service.push(caller, pack, &query.expect.0) + }) + .await + .map(Json) +} + +/// Lists what the repository holds of some changes: their revisions, +/// heads and statements, by id. +#[utoipa::path( + post, + path = "/api/v1/repos/{repo}/changes/inventory", + operation_id = "inventory", + params(("repo" = String, Path, description = "The repository")), + request_body = InventoryRequest, + responses( + (status = 200, description = "An inventory for each change, in the order asked: empty for a change the repository never heard of", body = Vec), + (status = 404, description = "The repository does not exist", body = ApiError) + ) +)] +async fn inventory( + repos: Repos, + Path(repo): Path, + caller: Caller, + Json(request): Json, +) -> Result>, HttpError> { + call(repos, repo, caller, move |service, caller| { + service.inventory(caller, &request) }) .await .map(Json) @@ -380,7 +413,7 @@ async fn log( Query(query): Query, ) -> Result>, HttpError> { call(repos, repo, caller, move |service, caller| { - service.log(caller, &query.target, query.since) + service.log(caller, &query) }) .await .map(Json) diff --git a/apps/origin-src/src/queue/mod.rs b/apps/origin-src/src/queue/mod.rs index 70485271..bfa71ed8 100644 --- a/apps/origin-src/src/queue/mod.rs +++ b/apps/origin-src/src/queue/mod.rs @@ -428,6 +428,9 @@ pub enum LandError { /// Its heads. heads: Vec, }, + /// A revision of the change was published while it was rebased. + #[error("change {} moved while it was landing: land it again", .0.short())] + Moved(ChangeId), /// The change was given up. #[error("change {} was abandoned, so it cannot land", .0.short())] Abandoned(ChangeId), diff --git a/apps/origin-src/src/queue/session.rs b/apps/origin-src/src/queue/session.rs index c567ee00..2bd03077 100644 --- a/apps/origin-src/src/queue/session.rs +++ b/apps/origin-src/src/queue/session.rs @@ -147,6 +147,9 @@ impl Session<'_, '_, P> { revision: None, }); } + // Held until the rebased revision is published, so no push makes + // the change diverge meanwhile. + let _publishing = self.publishing(revision.change, id)?; let rebased = Revision { predecessors: vec![id], base: tip, @@ -167,6 +170,18 @@ impl Session<'_, '_, P> { }) } + /// Takes the lock every publication of revisions takes (see + /// [`Store::lock_pushes`]), once `head` is still the only head of + /// `change`. + fn publishing(&mut self, change: ChangeId, head: RevisionId) -> Result { + let lock = self.store().lock_pushes()?; + self.annotations.refresh()?; + if self.annotations.index().heads(change) != [head] { + return Err(LandError::Moved(change)); + } + Ok(lock) + } + /// Checks the policy for `candidate`, and lands it if its evidence is /// there, or keeps it waiting. Writes the records in layers, each /// durable before the next refers to it: the trees, then the rebased diff --git a/apps/origin-src/src/service.rs b/apps/origin-src/src/service.rs index 7c99a451..533e731f 100644 --- a/apps/origin-src/src/service.rs +++ b/apps/origin-src/src/service.rs @@ -26,8 +26,9 @@ use std::time::Duration; use origin_platform::Native; use origin_shared::api::{ - Annotation, ErrorCode, EventsQuery, FetchSnapshot, LandRequest, Landings, LogEntry, NewTarget, - RevisionEntry, Revisions, Stored, TargetInfo, + Annotation, ErrorCode, EventsQuery, Expected, FetchSnapshot, Inventory, InventoryRequest, + LandRequest, Landings, LogEntry, LogQuery, NewTarget, RevisionEntry, Revisions, Stored, + TargetInfo, }; use origin_shared::event::{Filter, Page}; use origin_shared::landing::{Pending, Proposal}; @@ -278,6 +279,45 @@ impl OriginService { }) } + /// What the repository holds of each change: its revisions and heads, + /// and the statements about them, by id. A change it never heard of + /// has none. + /// + /// # Errors + /// + /// Fails if the index cannot be read. + pub fn inventory( + &self, + _caller: &Caller, + request: &InventoryRequest, + ) -> Result, ServiceError> { + self.annotations(|annotations| { + let index = annotations.index(); + Ok(request + .changes + .iter() + .map(|&change| { + let revisions = index.revisions(change).to_vec(); + let mut subjects: Vec<_> = + revisions.iter().copied().map(RecordId::Revision).collect(); + let mut statements = Vec::new(); + while let Some(subject) = subjects.pop() { + for &statement in index.statements(subject) { + statements.push(statement); + subjects.push(RecordId::Statement(statement)); + } + } + Inventory { + change, + heads: index.heads(change), + revisions, + statements, + } + }) + .collect()) + }) + } + /// Writes the objects of `pack`: snapshots, revisions and statements. /// Each must be well formed, and the repository must have, or the /// pack hold, everything it needs, of the kind it names: a tree's @@ -296,10 +336,29 @@ impl OriginService { /// /// Fails if an object is malformed, an acceptance, or needs an object /// neither the pack nor the repository has, or one of another kind, if - /// a promotion doesn't - /// match its original, which leaves the other records stored, or if - /// the objects cannot be written. - pub fn put_records(&self, _caller: &Caller, pack: Pack) -> Result { + /// a promotion doesn't match its original, which leaves the other + /// records stored, or if the objects cannot be written. + pub fn put_records(&self, caller: &Caller, pack: Pack) -> Result { + self.push(caller, pack, &[]) + } + + /// Puts `pack` like [`OriginService::put_records`], if each change of + /// `expect` has the heads it names when its records are published: a + /// compare-and-swap, which every other publication of revisions waits + /// for, puts and the landing queue's rebases alike. So of two pushes + /// made from the same view of a change, or a push and a rebase, the + /// second is refused instead of making it diverge. + /// + /// # Errors + /// + /// Fails like [`OriginService::put_records`], or if a change of + /// `expect` moved, which publishes no record, only snapshots. + pub fn push( + &self, + _caller: &Caller, + pack: Pack, + expect: &[Expected], + ) -> Result { // Objects this finds stored stay until what refers to them is. let _held = self.store.hold_objects()?; let held: HashMap> = pack @@ -361,10 +420,22 @@ impl OriginService { self.check_kinds(&stored)?; dependencies.commit()?; let mut new = 0; + if !snapshots.is_empty() { + new += self.store.write_all(&snapshots)?; + } + // Held until the records are published, so nothing else moves the + // changes in between: see `Store::lock_pushes`. + let _pushing = if !revisions.is_empty() || !expect.is_empty() { + let lock = self.store.lock_pushes()?; + self.check_heads(expect)?; + Some(lock) + } else { + None + }; // Each layer durable before the next, as a workspace writes them: // statements before the revisions they're about, so a crash never // publishes a revision without its `core.conflict`. - for layer in [snapshots, statements, revisions] { + for layer in [statements, revisions] { if !layer.is_empty() { new += self.store.write_all(&layer)?; } @@ -396,6 +467,23 @@ impl OriginService { Ok(Stored { new: new as u64 }) } + /// Checks that each change of `expect` has the heads it names. + fn check_heads(&self, expect: &[Expected]) -> Result<(), ServiceError> { + self.annotations(|annotations| { + for expected in expect { + let heads = annotations.index().heads(expected.change); + let now: HashSet<_> = heads.iter().collect(); + if now != expected.heads.iter().collect() { + return Err(ServiceError::Moved { + change: expected.change, + heads, + }); + } + } + Ok(()) + }) + } + /// Checks that each object of `stored`, which the repository has, is of /// the kind the object of the pack needing it names, reading them from /// every core. @@ -481,24 +569,23 @@ impl OriginService { Ok(targets) } - /// The acceptances of `target` from position `since` on, oldest first. + /// The acceptances of the query's target from position `since` on, + /// oldest first, up to its `limit`. /// /// # 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> { + pub fn log(&self, _caller: &Caller, query: &LogQuery) -> Result, ServiceError> { + let target = &query.target; if self.store.head(target)?.is_none() { return Err(ServiceError::UnknownTarget(target.clone())); } - self.store - .log_since(target, since)? - .into_iter() + let mut ids = self.store.log_since(target, query.since)?; + if let Some(limit) = query.limit { + ids.truncate(usize::try_from(limit).unwrap_or(usize::MAX)); + } + ids.into_iter() .map(|id| { Ok(LogEntry { id, @@ -742,6 +829,19 @@ pub enum ServiceError { /// The kind it must be. kind: ObjectKind, }, + /// A push expected a change's heads to be where they no longer are. + #[error( + "change {} moved on the remote since it was fetched: run `origin fetch`, then \ + `origin converge {}` if it diverged", + change.short(), + change.short() + )] + Moved { + /// The change. + change: ChangeId, + /// Its heads now. + heads: Vec, + }, /// A statement put isn't one the repository accepts: a promotion that /// doesn't match its original. #[error("statement {} cannot be put", .id.short())] @@ -781,6 +881,7 @@ impl ServiceError { AnnotateError::Store(error) => Self::store_code(error), _ => ErrorCode::BadRequest, }, + Self::Moved { .. } => ErrorCode::Conflict, Self::Land(error) => match error { LandError::UnknownTarget(_) | LandError::UnknownChange(_) => ErrorCode::NotFound, LandError::TargetExists(_) @@ -789,6 +890,7 @@ impl ServiceError { | LandError::NotAuthority { .. } | LandError::WrongKey(_) | LandError::Divergent { .. } + | LandError::Moved(_) | LandError::Abandoned(_) | LandError::Unresolved { .. } | LandError::InvalidPolicy(_) => ErrorCode::Conflict, diff --git a/apps/origin-src/src/store/mod.rs b/apps/origin-src/src/store/mod.rs index 4dc03515..405aec97 100644 --- a/apps/origin-src/src/store/mod.rs +++ b/apps/origin-src/src/store/mod.rs @@ -362,6 +362,29 @@ impl Store

{ Ok(LockedFile::open(&self.platform, &path, LockMode::Shared)?) } + /// The file whose lock makes checking a change's heads and publishing + /// revisions that move them one step. + const PUSH_LOCK: &str = "push"; + + /// Waits for the publication of revisions in progress, and keeps + /// others waiting while it's held: every put of revisions takes it, + /// checking the heads a push expects first (see + /// [`OriginService::push`](crate::service::OriginService::push)), and + /// the landing queue, checking that the head it rebases still is the + /// change's only one. + /// + /// # Errors + /// + /// Fails if the lock file cannot be opened. + pub fn lock_pushes(&self) -> Result { + let path = self.root.join(Self::PUSH_LOCK); + Ok(LockedFile::open( + &self.platform, + &path, + LockMode::Exclusive, + )?) + } + /// Waits for the writers holding objects, and keeps new ones waiting /// while it's held: garbage collection holds it while it finds what /// nothing refers to, and deletes it. diff --git a/apps/origin-src/src/workspace/mod.rs b/apps/origin-src/src/workspace/mod.rs index 98faa9e5..0e2b31ae 100644 --- a/apps/origin-src/src/workspace/mod.rs +++ b/apps/origin-src/src/workspace/mod.rs @@ -78,7 +78,7 @@ use std::path::{Path, PathBuf}; use std::sync::Arc; use origin_platform::{LockedFile, Native}; -use origin_shared::api::{RevisionEntry, Revisions}; +use origin_shared::api::{LogQuery, RevisionEntry, Revisions}; use origin_shared::{ AcceptanceId, Base, BlobId, ChangeId, EncodedObject, Kind, Principal, Record, RecordId, RepoPath, Revision, RevisionId, Source, Statement, StatementId, TargetId, TargetName, Tree, @@ -1275,7 +1275,14 @@ impl Workspace { (Some(limit), Some(head)) => (head.seq + 1).saturating_sub(limit as u64), _ => 0, }; - let log = self.service(None)?.log(&Caller::Owner, &target, since)?; + // Bounded too, so acceptances landed since reading the head aren't + // printed. + let query = LogQuery { + target: target.clone(), + since, + limit: limit.map(|limit| u64::try_from(limit).unwrap_or(u64::MAX)), + }; + let log = self.service(None)?.log(&Caller::Owner, &query)?; if target.id() == on { for (id, revision) in &stack { let marker = if *id == working_copy.id { '@' } else { '○' }; diff --git a/apps/origin-src/tests/http.rs b/apps/origin-src/tests/http.rs index 15801b69..7c38d1c6 100644 --- a/apps/origin-src/tests/http.rs +++ b/apps/origin-src/tests/http.rs @@ -7,8 +7,8 @@ use std::time::{Duration, Instant}; use origin_client::{Client, Error, Repo}; use origin_shared::api::{ - ErrorCode, EventsQuery, FetchRecords, FetchSnapshot, LandRequest, List, LogQuery, NewTarget, - RepoName, StatementsQuery, + ErrorCode, EventsQuery, Expected, FetchRecords, FetchSnapshot, InventoryRequest, LandRequest, + List, LogQuery, NewTarget, PutQuery, RepoName, StatementsQuery, }; use origin_shared::event::EventKind; use origin_shared::landing::{Blocked, Landing, Proposal}; @@ -236,6 +236,7 @@ async fn puts_and_fetches_records() { .log(&LogQuery { target: TargetName::MAIN, since: 0, + limit: None, }) .await .unwrap(); @@ -322,6 +323,43 @@ async fn puts_refuse_objects_named_as_another_kind() { assert_eq!(refused(vec![tree.encode()]).await, ErrorCode::BadRequest); } +#[tokio::test] +async fn pushes_compare_and_swap_the_heads_they_saw() { + let server = Server::start().await; + let repo = &server.demo; + let base = main_tip(repo).await; + let expect = |heads: &[RevisionId]| PutQuery { + expect: List(vec![Expected { + change: change(1), + heads: heads.to_vec(), + }]), + }; + let first = Made::revision(change(1), base, Vec::new(), &[("a", "first")]); + repo.push_records(&first.pack(), &expect(&[])) + .await + .unwrap(); + + // Two pushes made from the same view of the change: the second is + // refused, and publishes no record. + let left = Made::revision(change(1), base, vec![first.id], &[("a", "left")]); + let right = Made::revision(change(1), base, vec![first.id], &[("a", "right")]); + repo.push_records(&left.pack(), &expect(&[first.id])) + .await + .unwrap(); + let error = repo + .push_records(&right.pack(), &expect(&[first.id])) + .await + .unwrap_err(); + assert_eq!(code(error), ErrorCode::Conflict); + let request = InventoryRequest { + changes: vec![change(1)], + }; + assert_eq!(repo.inventory(&request).await.unwrap()[0].heads, [left.id]); + repo.push_records(&right.pack(), &expect(&[left.id])) + .await + .unwrap(); +} + #[tokio::test] async fn promotions_must_match_their_original() { let server = Server::start().await; @@ -478,6 +516,24 @@ async fn reads_statements_and_revisions() { let error = repo.revisions(change(9)).await.unwrap_err(); assert_eq!(code(error), ErrorCode::NotFound); + + let inventories = repo + .inventory(&InventoryRequest { + changes: vec![change(1), change(9)], + }) + .await + .unwrap(); + let [known, unknown] = &inventories[..] else { + panic!("{inventories:?}") + }; + assert_eq!(known.revisions, ids); + assert_eq!(known.heads, [left.id, right.id]); + let mut statements = known.statements.clone(); + statements.sort(); + let mut expected = vec![statement.id().into(), flagged[0].id]; + expected.sort(); + assert_eq!(statements, expected); + assert!(unknown.revisions.is_empty() && unknown.statements.is_empty()); } #[tokio::test] @@ -512,6 +568,7 @@ async fn lands_changes_and_targets() { .log(&LogQuery { target: TargetName::MAIN, since: 1, + limit: Some(1), }) .await .unwrap(); diff --git a/crates/origin-client/src/lib.rs b/crates/origin-client/src/lib.rs index 77a1fe36..68523f5f 100644 --- a/crates/origin-client/src/lib.rs +++ b/crates/origin-client/src/lib.rs @@ -19,9 +19,9 @@ //! in `docs/openapi.json`, for other languages. use origin_shared::api::{ - Annotation, ApiError, EventsQuery, FetchRecords, FetchSnapshot, LandRequest, Landings, - LogEntry, LogQuery, MORE, NewTarget, RepoName, RepoSummary, Revisions, StatementsQuery, Stored, - TargetInfo, + Annotation, ApiError, EventsQuery, FetchRecords, FetchSnapshot, Inventory, InventoryRequest, + LandRequest, Landings, LogEntry, LogQuery, MORE, NewTarget, PutQuery, RepoName, RepoSummary, + Revisions, StatementsQuery, Stored, TargetInfo, }; use origin_shared::event::Page; use origin_shared::landing::Pending; @@ -32,15 +32,15 @@ use serde::de::DeserializeOwned; /// Defines endpoints as methods. Each sends one request, built from an HTTP /// method, a path relative to its owner's, which can name the arguments -/// like `format!` does, and optionally a body applied by a -/// [`RequestBuilder`] method (`query`, `json` or `body`), then reads the -/// response with a [`Response`] method. +/// like `format!` does, and what [`RequestBuilder`] methods (`query`, +/// `json` or `body`) apply, then reads the response with a [`Response`] +/// method. macro_rules! endpoints { ($( impl $owner:ident {$( $(#[doc = $doc:literal])* fn $name:ident($($arg:ident: $type:ty),*) -> $output:ty = - $method:ident $path:literal $(, $send:ident($body:expr))? => $read:ident; + $method:ident $path:literal $(, $send:ident($body:expr))* => $read:ident; )*} )*) => {$( impl $owner {$( @@ -50,7 +50,7 @@ macro_rules! endpoints { /// /// Fails if the server cannot be reached or refuses the request. pub async fn $name(&self, $($arg: $type),*) -> Result<$output, Error> { - let request = self.request(Method::$method, &format!($path))$(.$send($body))?; + let request = self.request(Method::$method, &format!($path))$(.$send($body))*; Response::send(request).await?.$read().await } )*} @@ -81,10 +81,19 @@ endpoints! { /// Puts a batch of objects: snapshots, revisions and statements, /// each needing only objects the batch or the repository has. fn put_records(pack: &Pack) -> Stored = PUT "records", body(pack.encode()) => json; + /// Puts a batch of objects like `put_records`, if each change the + /// query names has the heads it says when its revisions are + /// published: a compare-and-swap, refused with a conflict. + fn push_records(pack: &Pack, query: &PutQuery) -> Stored = + PUT "records", query(query), body(pack.encode()) => json; /// The statements about a record, in the order the repository /// received them. fn statements(query: &StatementsQuery) -> Vec = GET "statements", query(query) => json; + /// What the server holds of some changes: their revisions, heads + /// and statements, by id. + fn inventory(request: &InventoryRequest) -> Vec = + POST "changes/inventory", json(request) => json; /// The revisions of a change, and its heads. fn revisions(change: ChangeId) -> Revisions = GET "changes/{change}/revisions" => json; /// Every target, with its tip, authority and requirements. diff --git a/crates/origin-shared/src/api.rs b/crates/origin-shared/src/api.rs index 8b91759c..4f6cd521 100644 --- a/crates/origin-shared/src/api.rs +++ b/crates/origin-shared/src/api.rs @@ -11,8 +11,8 @@ use crate::landing::{Landing, Proposal}; use crate::policy::{KindPattern, Requirement}; use crate::text::Period; use crate::{ - Acceptance, AcceptanceId, Head, ObjectId, PrincipalName, RecordId, RepoPath, Revision, - RevisionId, Statement, StatementId, TargetName, TreeId, + Acceptance, AcceptanceId, ChangeId, Head, ObjectId, PrincipalName, RecordId, RepoPath, + Revision, RevisionId, Statement, StatementId, TargetName, TreeId, }; /// The name of a repository on a server: ASCII letters, digits, `.`, `_` @@ -142,6 +142,85 @@ fn is_zero(value: &u64) -> bool { *value == 0 } +/// Asks what a repository holds of some changes. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, ToSchema)] +pub struct InventoryRequest { + /// The changes. + pub changes: Vec, +} + +/// What a repository holds of a change: its records, by id, to compare +/// with another node's. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, ToSchema)] +pub struct Inventory { + /// The change. + pub change: ChangeId, + /// Its revisions, in the order the repository received them: none if it + /// has never heard of the change. + pub revisions: Vec, + /// Those no other revision of the change evolves from. + pub heads: Vec, + /// The statements about its revisions, and about those statements, in + /// no particular order. + pub statements: Vec, +} + +/// Asks for a batch of objects to be put only if the changes named are where +/// the caller saw them: a compare-and-swap, so a push made from a stale view +/// of a change is refused instead of making it diverge. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, IntoParams)] +#[into_params(parameter_in = Query)] +pub struct PutQuery { + /// The heads of changes as the caller saw them, comma-separated, each + /// `=+`, or `=` for a change the repository + /// didn't have. The batch is refused if one's heads differ now. + #[serde(default, skip_serializing_if = "List::is_empty")] + #[param(value_type = Option)] + pub expect: List, +} + +/// The heads of a change as someone saw them, written +/// `=+`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Expected { + /// The change. + pub change: ChangeId, + /// Its heads: none if the repository didn't have it. + pub heads: Vec, +} + +impl fmt::Display for Expected { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}=", self.change)?; + for (i, head) in self.heads.iter().enumerate() { + let separator = if i == 0 { "" } else { "+" }; + write!(f, "{separator}{head}")?; + } + Ok(()) + } +} + +impl FromStr for Expected { + type Err = String; + + fn from_str(input: &str) -> Result { + let invalid = |error: crate::ParseIdError| format!("invalid heads {input:?}: {error}"); + let (change, heads) = input + .split_once('=') + .ok_or_else(|| format!("invalid heads {input:?}: expected =+"))?; + let heads = heads + .split('+') + .filter(|head| !head.is_empty()) + .map(str::parse) + .collect::>() + .map_err(invalid)?; + Ok(Self { + change: change.parse().map_err(invalid)?, + heads, + }) + } +} + /// What putting a batch of records did. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, ToSchema)] pub struct Stored { @@ -217,6 +296,8 @@ pub struct LogQuery { /// default. #[serde(default)] pub since: u64, + /// Return at most this many acceptances: all by default. + pub limit: Option, } /// One acceptance of a target's log. @@ -374,6 +455,23 @@ mod tests { } } + #[test] + fn expected_heads_round_trip() { + let change = ChangeId::from_bytes([1; 16]); + let heads = [ + RevisionId::from_bytes([2; 32]), + RevisionId::from_bytes([3; 32]), + ]; + for heads in [&heads[..], &heads[..1], &[]] { + let expected = Expected { + change, + heads: heads.to_vec(), + }; + assert_eq!(expected.to_string().parse::(), Ok(expected)); + } + assert!("nonsense".parse::().is_err()); + } + #[test] fn lists_are_comma_separated() { let list: List = serde_json::from_str("\"ci.*,review\"").unwrap(); diff --git a/docs/openapi.json b/docs/openapi.json index 0fc98ded..87d85bbb 100644 --- a/docs/openapi.json +++ b/docs/openapi.json @@ -48,6 +48,58 @@ } } }, + "/api/v1/repos/{repo}/changes/inventory": { + "post": { + "summary": "Lists what the repository holds of some changes: their revisions,\nheads and statements, by id.", + "operationId": "inventory", + "parameters": [ + { + "name": "repo", + "in": "path", + "description": "The repository", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InventoryRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "An inventory for each change, in the order asked: empty for a change the repository never heard of", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Inventory" + } + } + } + } + }, + "404": { + "description": "The repository does not exist", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + } + } + } + }, "/api/v1/repos/{repo}/changes/{change}/revisions": { "get": { "summary": "Lists the revisions of a change, and its heads.", @@ -338,6 +390,17 @@ "format": "int64", "minimum": 0 } + }, + { + "name": "limit", + "in": "query", + "description": "Return at most this many acceptances: all by default.", + "required": false, + "schema": { + "type": "integer", + "format": "int64", + "minimum": 0 + } } ], "responses": { @@ -369,7 +432,7 @@ }, "/api/v1/repos/{repo}/records": { "put": { - "summary": "Puts a batch of objects, as a pack: snapshots, revisions and\nstatements, each needing only objects the batch or the repository has,\nof the kinds it names.", + "summary": "Puts a batch of objects, as a pack: snapshots, revisions and\nstatements, each needing only objects the batch or the repository has,\nof the kinds it names. With `expect`, only if the changes it names have\nthe heads it says when the records are published.", "operationId": "put_records", "parameters": [ { @@ -380,6 +443,15 @@ "schema": { "type": "string" } + }, + { + "name": "expect", + "in": "query", + "description": "The heads of changes as the caller saw them, comma-separated, each\n`=+`, or `=` for a change the repository\ndidn't have. The batch is refused if one's heads differ now.", + "required": false, + "schema": { + "type": "string" + } } ], "requestBody": { @@ -423,6 +495,16 @@ } } } + }, + "409": { + "description": "A change of `expect` has other heads now", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } } } } @@ -1225,6 +1307,59 @@ } } }, + "Inventory": { + "type": "object", + "description": "What a repository holds of a change: its records, by id, to compare\nwith another node's.", + "required": [ + "change", + "revisions", + "heads", + "statements" + ], + "properties": { + "change": { + "$ref": "#/components/schemas/ChangeId", + "description": "The change." + }, + "heads": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RevisionId" + }, + "description": "Those no other revision of the change evolves from." + }, + "revisions": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RevisionId" + }, + "description": "Its revisions, in the order the repository received them: none if it\nhas never heard of the change." + }, + "statements": { + "type": "array", + "items": { + "$ref": "#/components/schemas/StatementId" + }, + "description": "The statements about its revisions, and about those statements, in\nno particular order." + } + } + }, + "InventoryRequest": { + "type": "object", + "description": "Asks what a repository holds of some changes.", + "required": [ + "changes" + ], + "properties": { + "changes": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ChangeId" + }, + "description": "The changes." + } + } + }, "Kind": { "type": "string", "examples": [