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
8 changes: 5 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,9 +119,11 @@ key = "node.key" # its secret key, created if missing
demo = "repos/demo"
```

The HTTP API, under `/api/v1`, puts and fetches records in batches, 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 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
/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
72 changes: 59 additions & 13 deletions apps/origin-src/src/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,13 @@ use axum::response::{IntoResponse, Response};
use origin_shared::ChangeId;
use origin_shared::Head;
use origin_shared::api::{
Annotation, ApiError, ErrorCode, EventsQuery, FetchRecords, LandRequest, Landings, LogEntry,
LogQuery, NewTarget, RepoName, RepoSummary, Revisions, StatementsQuery, Stored, TargetInfo,
Annotation, ApiError, ErrorCode, EventsQuery, FetchRecords, FetchSnapshot, LandRequest,
Landings, LogEntry, LogQuery, MORE, NewTarget, RepoName, RepoSummary, Revisions,
StatementsQuery, Stored, TargetInfo,
};
use origin_shared::event::Page;
use origin_shared::landing::Pending;
use origin_shared::pack::{Pack, PackError};
use origin_shared::pack::{Pack, PackError, Part};
use utoipa::OpenApi;
use utoipa_axum::router::OpenApiRouter;
use utoipa_axum::routes;
Expand Down Expand Up @@ -51,6 +52,7 @@ impl Api {
OpenApiRouter::with_openapi(ApiDoc::openapi())
.routes(routes!(list_repos))
.routes(routes!(fetch_records))
.routes(routes!(fetch_snapshot))
.routes(routes!(put_records))
.routes(routes!(statements))
.routes(routes!(revisions))
Expand Down Expand Up @@ -160,33 +162,77 @@ async fn list_repos(State(repositories): Repos, caller: Caller) -> Json<Vec<Repo
Json(repositories.list(&caller))
}

/// Fetches objects by id, as a pack.
/// A part of a fetch, as a response: its pack, with the [`MORE`] header if
/// it stopped short.
struct PackResponse(Part);

impl IntoResponse for PackResponse {
fn into_response(self) -> Response {
let Part { pack, more } = self.0;
let mut response = (
[(header::CONTENT_TYPE, "application/octet-stream")],
pack.encode(),
)
.into_response();
if more {
response
.headers_mut()
.insert(MORE, header::HeaderValue::from_static("true"));
}
response
}
}

/// Fetches records by id, each with the blob it carries, as a pack.
#[utoipa::path(
post,
path = "/api/v1/repos/{repo}/records/fetch",
operation_id = "fetch_records",
params(("repo" = String, Path, description = "The repository")),
request_body = FetchRecords,
responses(
(status = 200, description = "The objects, in the order asked, as a pack: each a 32-byte id, a little-endian u64 length and the object's encoding", content_type = "application/octet-stream", body = Binary),
(status = 404, description = "The repository or an object does not exist", body = ApiError)
(status = 200, description = "The records, in the order asked, each followed by its description or payload if the repository has it, as a pack: each object a 32-byte id, a little-endian u64 length and the object's encoding. At most 64 MiB, but for a record alone", content_type = "application/octet-stream", body = Binary, headers(("origin-more" = bool, description = "Present if the pack stopped short: ask again for the records after the last it holds"))),
(status = 400, description = "An object is a blob or a tree, which only leave by walking a snapshot", body = ApiError),
(status = 404, description = "The repository or a record does not exist", body = ApiError)
)
)]
async fn fetch_records(
repos: Repos,
Path(repo): Path<RepoName>,
caller: Caller,
Json(request): Json<FetchRecords>,
) -> Result<Response, HttpError> {
let pack = call(repos, repo, caller, move |service, caller| {
) -> Result<PackResponse, HttpError> {
call(repos, repo, caller, move |service, caller| {
service.records(caller, &request.ids)
})
.await?;
Ok((
[(header::CONTENT_TYPE, "application/octet-stream")],
pack.encode(),
.await
.map(PackResponse)
}

/// Fetches the objects of a snapshot the caller lacks, as a pack: the only
/// way trees and blobs leave a repository.
#[utoipa::path(
post,
path = "/api/v1/repos/{repo}/snapshots/fetch",
operation_id = "fetch_snapshot",
params(("repo" = String, Path, description = "The repository")),
request_body = FetchSnapshot,
responses(
(status = 200, description = "The trees and blobs, parents before children, as a pack, of at most 64 MiB, but for an object alone", content_type = "application/octet-stream", body = Binary, headers(("origin-more" = bool, description = "Present if the pack stopped short: ask again, skipping the objects it holds"))),
(status = 404, description = "The repository or the snapshot does not exist", body = ApiError)
)
.into_response())
)]
async fn fetch_snapshot(
repos: Repos,
Path(repo): Path<RepoName>,
caller: Caller,
Json(request): Json<FetchSnapshot>,
) -> Result<PackResponse, HttpError> {
call(repos, repo, caller, move |service, caller| {
service.snapshot(caller, &request)
})
.await
.map(PackResponse)
}

/// Puts a batch of objects, as a pack: snapshots, revisions and
Expand Down
122 changes: 108 additions & 14 deletions apps/origin-src/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,22 +19,23 @@

use std::collections::hash_map::Entry;
use std::collections::{HashMap, HashSet};
use std::iter;
use std::path::PathBuf;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::Duration;

use origin_platform::Native;
use origin_shared::api::{
Annotation, ErrorCode, EventsQuery, LandRequest, Landings, LogEntry, NewTarget, RevisionEntry,
Revisions, Stored, TargetInfo,
Annotation, ErrorCode, EventsQuery, FetchSnapshot, LandRequest, Landings, LogEntry, NewTarget,
RevisionEntry, Revisions, Stored, TargetInfo,
};
use origin_shared::event::{Filter, Page};
use origin_shared::landing::{Pending, Proposal};
use origin_shared::object::DecodeError;
use origin_shared::pack::Pack;
use origin_shared::pack::{Pack, Packer, Part};
use origin_shared::{
Base, ChangeId, Head, NodeKey, Object, ObjectId, ObjectKind, Principal, PrincipalName,
RecordId, Statement, StatementId, TargetName,
RecordId, Statement, StatementId, TargetName, TreeId,
};

use crate::annotations::{AnnotateError, Annotations};
Expand Down Expand Up @@ -79,6 +80,8 @@ pub struct OriginService {
/// The record indexes kept open, but those in use: see the module.
indexes: Mutex<Vec<Index>>,
wakeup: Wakeup,
/// The most bytes a fetch's answer holds: [`Pack::LIMIT`], but in tests.
pack_limit: usize,
}

impl OriginService {
Expand All @@ -99,6 +102,7 @@ impl OriginService {
node,
indexes: Mutex::default(),
wakeup: Wakeup::default(),
pack_limit: Pack::LIMIT,
}
}

Expand Down Expand Up @@ -179,17 +183,99 @@ impl OriginService {
self.indexes.lock().unwrap_or_else(PoisonError::into_inner)
}

/// The objects `ids` name, in their order, as a pack.
/// The records `ids` name, in their order, as a pack: revisions,
/// statements and acceptances, each followed by the blob it carries, if
/// the repository has it: a revision's description, a statement's
/// payload. Snapshots only leave through [`OriginService::snapshot`].
/// The pack stops short at [`Pack::LIMIT`], before a record that
/// doesn't fit with its blob: the rest comes from asking for the ids
/// after the last record it has.
///
/// # Errors
///
/// Fails if the repository doesn't have one, or cannot read it.
pub fn records(&self, _caller: &Caller, ids: &[ObjectId]) -> Result<Pack, ServiceError> {
let objects = ids
/// Fails if the repository doesn't have one, one is a blob or a tree, or
/// it cannot read one.
pub fn records(&self, _caller: &Caller, ids: &[ObjectId]) -> Result<Part, ServiceError> {
let mut packer = Packer::new(self.pack_limit);
for &id in ids {
let object = self.store.read(id)?;
let carried = match object
.decode()
.map_err(|source| StoreError::Decode { id, source })?
{
Object::Blob(_) | Object::Tree(_) => return Err(ServiceError::NotARecord(id)),
Object::Revision(revision) => Some(revision.description.into()),
Object::Statement(statement) => statement.payload.map(Into::into),
Object::Acceptance(_) => None,
};
let carried = carried
.map(|id| self.store.try_read(id))
.transpose()?
.flatten();
let group: Vec<_> = iter::once(object).chain(carried).collect();
if !packer.fits(&group) {
return Ok(Part {
pack: packer.finish(),
more: true,
});
}
packer.extend(group);
}
Ok(Part {
pack: packer.finish(),
more: false,
})
}

/// The objects of the snapshot the request names that the caller lacks,
/// as a pack, parents before children: those none of the snapshots it
/// has holds at the same path, under the paths it asks for, but the
/// first `skip`. See [`Store::added`]. The pack stops short at
/// [`Pack::LIMIT`]: the rest comes from asking again, skipping what
/// came.
///
/// # Errors
///
/// Fails if the repository doesn't have the snapshot, or cannot read
/// it.
pub fn snapshot(
&self,
_caller: &Caller,
request: &FetchSnapshot,
) -> Result<Part, ServiceError> {
let is_tree = |id: TreeId| -> Result<bool, StoreError> {
let object = self.store.try_read(id.into())?;
Ok(object.is_some_and(|object| object.kind().ok() == Some(ObjectKind::Tree)))
};
if !is_tree(request.snapshot)? {
return Err(ServiceError::UnknownSnapshot(request.snapshot));
}
let mut have = Vec::new();
for &id in &request.have {
if is_tree(id)? {
have.push(id);
}
}
let added = self.store.added(request.snapshot, &have, &request.paths)?;
let skip = usize::try_from(request.skip).unwrap_or(usize::MAX);
let ids: Vec<ObjectId> = added
.iter()
.map(|&id| self.store.read(id))
.collect::<Result<_, _>>()?;
Ok(Pack { objects })
.skip(skip)
.map(|placed| placed.entry.id)
.collect();
let mut packer = Packer::new(self.pack_limit);
let mut more = false;
self.store.read_each(&ids, |object| {
more = !packer.fits([&object]);
if !more {
packer.extend([object]);
}
Ok::<_, StoreError>(!more)
})?;
Ok(Part {
pack: packer.finish(),
more,
})
}

/// Writes the objects of `pack`: snapshots, revisions and statements.
Expand Down Expand Up @@ -615,6 +701,12 @@ pub enum ServiceError {
/// No target has this name.
#[error("no target is named `{0}`")]
UnknownTarget(TargetName),
/// The repository has no such snapshot.
#[error("snapshot {0} not found")]
UnknownSnapshot(TreeId),
/// A blob or a tree was fetched as a record.
#[error("{0} is not a record: fetch snapshots by walking them")]
NotARecord(ObjectId),
/// A target was proposed for landing without a target to land on.
#[error("landing a target needs a target to land on")]
NoTarget,
Expand Down Expand Up @@ -675,10 +767,12 @@ impl ServiceError {
#[must_use]
pub fn code(&self) -> ErrorCode {
match self {
Self::UnknownRepository(_) | Self::UnknownChange(_) | Self::UnknownTarget(_) => {
ErrorCode::NotFound
}
Self::UnknownRepository(_)
| Self::UnknownChange(_)
| Self::UnknownTarget(_)
| Self::UnknownSnapshot(_) => ErrorCode::NotFound,
Self::NoTarget
| Self::NotARecord(_)
| Self::Malformed { .. }
| Self::Acceptance(_)
| Self::Missing { .. }
Expand Down
55 changes: 55 additions & 0 deletions apps/origin-src/src/store/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -480,6 +480,61 @@ impl<P: Platform> Store<P> {
self.try_read(id)?.ok_or(StoreError::NotFound(id))
}

/// Reads objects the store must have, in order, from every core.
///
/// # Errors
///
/// Fails like [`Store::read`].
pub fn read_all(&self, ids: &[ObjectId]) -> Result<Vec<EncodedObject>, StoreError> {
let chunks = Self::on_every_core(ids, |chunk| {
chunk
.iter()
.map(|&id| self.read(id))
.collect::<Result<Vec<_>, _>>()
});
let mut objects = Vec::with_capacity(ids.len());
for chunk in chunks {
objects.extend(chunk?);
}
Ok(objects)
}

/// Reads the objects `ids` names, in order, handing each to `each` until
/// it returns `false`. They're read from every core a chunk at a time,
/// chunks growing while their objects are small and shrinking while
/// they're large, so a chunk holds a few MiB.
///
/// # Errors
///
/// Fails like [`Store::read`], or as `each` does.
pub fn read_each<E: From<StoreError>>(
&self,
ids: &[ObjectId],
mut each: impl FnMut(EncodedObject) -> Result<bool, E>,
) -> Result<(), E> {
/// The bytes a chunk aims for.
const TARGET: usize = 8 << 20;
let mut size = 16;
let mut rest = ids;
while !rest.is_empty() {
let (chunk, after) = rest.split_at(size.min(rest.len()));
rest = after;
let objects = self.read_all(chunk)?;
let bytes: usize = objects.iter().map(|object| object.bytes().len()).sum();
if bytes < TARGET / 2 {
size = (size * 2).min(4096);
} else if bytes > TARGET * 2 {
size = (size / 2).max(1);
}
for object in objects {
if !each(object)? {
return Ok(());
}
}
}
Ok(())
}

/// Reads and decodes the record `id` names.
///
/// # Errors
Expand Down
Loading