Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<repo>/events?cursor=<n>&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
Expand Down
51 changes: 42 additions & 9 deletions apps/origin-src/src/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -45,7 +45,10 @@ type Repos = State<Arc<Repositories>>;
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<Arc<Repositories>> {
Expand All @@ -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))
Expand Down Expand Up @@ -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<RepoName>,
Query(query): Query<PutQuery>,
caller: Caller,
body: Bytes,
) -> Result<Json<Stored>, 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<Inventory>),
(status = 404, description = "The repository does not exist", body = ApiError)
)
)]
async fn inventory(
repos: Repos,
Path(repo): Path<RepoName>,
caller: Caller,
Json(request): Json<InventoryRequest>,
) -> Result<Json<Vec<Inventory>>, HttpError> {
call(repos, repo, caller, move |service, caller| {
service.inventory(caller, &request)
})
.await
.map(Json)
Expand Down Expand Up @@ -380,7 +413,7 @@ async fn log(
Query(query): Query<LogQuery>,
) -> Result<Json<Vec<LogEntry>>, HttpError> {
call(repos, repo, caller, move |service, caller| {
service.log(caller, &query.target, query.since)
service.log(caller, &query)
})
.await
.map(Json)
Expand Down
3 changes: 3 additions & 0 deletions apps/origin-src/src/queue/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -428,6 +428,9 @@ pub enum LandError {
/// Its heads.
heads: Vec<RevisionId>,
},
/// 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),
Expand Down
15 changes: 15 additions & 0 deletions apps/origin-src/src/queue/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,9 @@ impl<P: Platform> 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,
Expand All @@ -167,6 +170,18 @@ impl<P: Platform> 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<LockedFile, LandError> {
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
Expand Down
136 changes: 119 additions & 17 deletions apps/origin-src/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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<Vec<Inventory>, 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
Expand All @@ -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<Stored, ServiceError> {
/// 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<Stored, ServiceError> {
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<Stored, ServiceError> {
// Objects this finds stored stay until what refers to them is.
let _held = self.store.hold_objects()?;
let held: HashMap<ObjectId, Option<ObjectKind>> = pack
Expand Down Expand Up @@ -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)?;
}
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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<Vec<LogEntry>, ServiceError> {
pub fn log(&self, _caller: &Caller, query: &LogQuery) -> Result<Vec<LogEntry>, 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,
Expand Down Expand Up @@ -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<origin_shared::RevisionId>,
},
/// A statement put isn't one the repository accepts: a promotion that
/// doesn't match its original.
#[error("statement {} cannot be put", .id.short())]
Expand Down Expand Up @@ -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(_)
Expand All @@ -789,6 +890,7 @@ impl ServiceError {
| LandError::NotAuthority { .. }
| LandError::WrongKey(_)
| LandError::Divergent { .. }
| LandError::Moved(_)
| LandError::Abandoned(_)
| LandError::Unresolved { .. }
| LandError::InvalidPolicy(_) => ErrorCode::Conflict,
Expand Down
Loading