diff --git a/README.md b/README.md index af62c6d6..e29984ba 100644 --- a/README.md +++ b/README.md @@ -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//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 f028238a..e97e63a5 100644 --- a/apps/origin-src/src/http.rs +++ b/apps/origin-src/src/http.rs @@ -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; @@ -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)) @@ -160,7 +162,28 @@ async fn list_repos(State(repositories): Repos, caller: Caller) -> Json 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", @@ -168,8 +191,9 @@ async fn list_repos(State(repositories): Repos, caller: Caller) -> Json, caller: Caller, Json(request): Json, -) -> Result { - let pack = call(repos, repo, caller, move |service, caller| { +) -> Result { + 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, + caller: Caller, + Json(request): Json, +) -> Result { + 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 diff --git a/apps/origin-src/src/service.rs b/apps/origin-src/src/service.rs index 096ebd4b..7c99a451 100644 --- a/apps/origin-src/src/service.rs +++ b/apps/origin-src/src/service.rs @@ -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}; @@ -79,6 +80,8 @@ pub struct OriginService { /// The record indexes kept open, but those in use: see the module. indexes: Mutex>, wakeup: Wakeup, + /// The most bytes a fetch's answer holds: [`Pack::LIMIT`], but in tests. + pack_limit: usize, } impl OriginService { @@ -99,6 +102,7 @@ impl OriginService { node, indexes: Mutex::default(), wakeup: Wakeup::default(), + pack_limit: Pack::LIMIT, } } @@ -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 { - 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 { + 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 { + let is_tree = |id: TreeId| -> Result { + 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 = added .iter() - .map(|&id| self.store.read(id)) - .collect::>()?; - 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. @@ -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, @@ -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 { .. } diff --git a/apps/origin-src/src/store/mod.rs b/apps/origin-src/src/store/mod.rs index 523e349f..4dc03515 100644 --- a/apps/origin-src/src/store/mod.rs +++ b/apps/origin-src/src/store/mod.rs @@ -480,6 +480,61 @@ impl Store

{ 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, StoreError> { + let chunks = Self::on_every_core(ids, |chunk| { + chunk + .iter() + .map(|&id| self.read(id)) + .collect::, _>>() + }); + 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>( + &self, + ids: &[ObjectId], + mut each: impl FnMut(EncodedObject) -> Result, + ) -> 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 diff --git a/apps/origin-src/src/tree.rs b/apps/origin-src/src/tree.rs index 19e144d1..87699f55 100644 --- a/apps/origin-src/src/tree.rs +++ b/apps/origin-src/src/tree.rs @@ -433,6 +433,108 @@ impl Store

{ } } +/// An object of a snapshot, and where it is: [`Store::added`] lists them. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Placed { + /// Its path: the root for the snapshot's own tree. + pub path: RepoPath, + /// The object, and its kind. + pub entry: TreeEntry, +} + +/// Which part of a snapshot [`Store::added`] walks. +struct Scope<'p>(&'p [RepoPath]); + +impl Scope<'_> { + /// Whether everything at `path` and under it is in scope. + fn covers(&self, path: &RepoPath) -> bool { + self.0.is_empty() || self.0.iter().any(|prefix| path.starts_with(prefix)) + } + + /// Whether `path` is a directory on the way to something in scope. + fn leads_in(&self, path: &RepoPath) -> bool { + self.0.iter().any(|prefix| prefix.starts_with(path)) + } +} + +impl Store

{ + /// The objects of `snapshot` that none of the snapshots `have` holds at + /// the same path, parents before children: what someone holding `have` + /// lacks of it. With `paths`, only those under them, and the trees on + /// the way. Subtrees a `have` holds whole are skipped without being + /// read, so the cost follows the size of the change. Objects appear + /// once, at their first path. + /// + /// # Errors + /// + /// Fails if a tree of `snapshot`, or of a `have`, cannot be read. + pub fn added( + &self, + snapshot: TreeId, + have: &[TreeId], + paths: &[RepoPath], + ) -> Result, StoreError> { + let mut added = Vec::new(); + let mut seen = HashSet::new(); + self.add_dir( + &RepoPath::root(), + snapshot, + have, + &Scope(paths), + &mut seen, + &mut added, + )?; + Ok(added) + } + + fn add_dir( + &self, + dir: &RepoPath, + tree: TreeId, + have: &[TreeId], + scope: &Scope<'_>, + seen: &mut HashSet, + added: &mut Vec, + ) -> Result<(), StoreError> { + if have.contains(&tree) { + return Ok(()); + } + if seen.insert(tree.into()) { + added.push(Placed { + path: dir.clone(), + entry: TreeEntry { + kind: EntryKind::Tree, + id: tree.into(), + }, + }); + } + let have: Vec = have + .iter() + .map(|&id| self.get(id)) + .collect::>()?; + for (name, &entry) in &self.get(tree)? { + let path = dir.join(name); + let covered = scope.covers(&path); + if !(covered || entry.kind.is_tree() && scope.leads_in(&path)) { + continue; + } + let held = have.iter().filter_map(|tree| tree.get(name.as_str())); + if held.clone().any(|held| *held == entry) { + continue; + } + match entry.subtree() { + Some(subtree) => { + let held: Vec<_> = held.filter_map(|held| held.subtree()).collect(); + self.add_dir(&path, subtree, &held, scope, seen, added)?; + } + None if seen.insert(entry.id) => added.push(Placed { path, entry }), + None => {} + } + } + Ok(()) + } +} + #[cfg(test)] pub(crate) mod tests { use std::collections::BTreeMap; @@ -560,6 +662,67 @@ pub(crate) mod tests { assert_eq!(store.diff(empty, old).unwrap().len(), 5); } + #[test] + fn lists_what_the_haves_lack() { + let dir = tempfile::tempdir().unwrap(); + let store = Store::new(dir.path().join(".origin"), Native::default()); + store.init().unwrap(); + let old = build( + &store, + &[ + ("same/a", "1"), + ("edit/b", "2"), + ("file", "3"), + ("docs/x", "4"), + ], + ); + let new = build( + &store, + &[ + ("same/a", "1"), + ("edit/b", "changed"), + ("file/now-dir", "4"), + ("docs/x", "4"), + ("docs/copy", "4"), + ], + ); + let paths = |placed: Vec| -> Vec { + placed + .iter() + .map(|placed| placed.path.to_string()) + .collect() + }; + + assert_eq!( + paths(store.added(new, &[old], &[]).unwrap()), + ["/", "docs", "docs/copy", "edit", "edit/b", "file"], + "`file/now-dir` has the content of `docs/copy`, listed first" + ); + assert_eq!( + store.added(new, &[], &[]).unwrap().len(), + 8, + "5 trees, and 5 files of 3 contents" + ); + assert_eq!(store.added(new, &[new], &[]).unwrap(), []); + let empty = build(&store, &[]); + assert_eq!( + paths(store.added(new, &[empty, old], &[]).unwrap()), + paths(store.added(new, &[old], &[]).unwrap()), + "any have holding an object is enough" + ); + + let only = |path: &str| [RepoPath::new(path).unwrap()]; + assert_eq!( + paths(store.added(new, &[], &only("edit/b")).unwrap()), + ["/", "edit", "edit/b"], + "the trees on the way, then the path" + ); + assert_eq!( + paths(store.added(new, &[old], &only("same")).unwrap()), + ["/"] + ); + } + /// The files of `tree`, by path, with their contents' ids. fn files(store: &Store, tree: TreeId) -> Vec<(String, ObjectId)> { let empty = build(store, &[]); diff --git a/apps/origin-src/tests/http.rs b/apps/origin-src/tests/http.rs index 5a4c46f7..15801b69 100644 --- a/apps/origin-src/tests/http.rs +++ b/apps/origin-src/tests/http.rs @@ -7,16 +7,16 @@ use std::time::{Duration, Instant}; use origin_client::{Client, Error, Repo}; use origin_shared::api::{ - ErrorCode, EventsQuery, FetchRecords, LandRequest, List, LogQuery, NewTarget, RepoName, - StatementsQuery, + ErrorCode, EventsQuery, FetchRecords, FetchSnapshot, LandRequest, List, LogQuery, NewTarget, + RepoName, StatementsQuery, }; use origin_shared::event::EventKind; use origin_shared::landing::{Blocked, Landing, Proposal}; use origin_shared::pack::Pack; use origin_shared::{ Base, BlobId, ChangeId, Digest, EncodedObject, EntryKind, EntryName, Inputs, Kind, NodeKey, - Period, Record, RecordId, Revision, RevisionId, Source, Statement, TargetName, Tree, TreeEntry, - Verdict, + Period, Record, RecordId, RepoPath, Revision, RevisionId, Source, Statement, TargetName, Tree, + TreeEntry, TreeId, Verdict, }; use origin_src::http::Api; use origin_src::policy::Policy; @@ -201,14 +201,29 @@ async fn puts_and_fetches_records() { "records are immutable, so putting them again does nothing" ); - let wanted = [made.objects[4].clone(), made.objects[0].clone()]; + let [a, _, tree, description, revision] = &made.objects[..] else { + unreachable!() + }; let fetched = repo .fetch_records(&FetchRecords { - ids: wanted.iter().map(EncodedObject::id).collect(), + ids: vec![revision.id()], }) .await .unwrap(); - assert_eq!(fetched.objects, wanted, "verified, in the order asked"); + assert_eq!( + fetched.pack.objects, + [revision.clone(), description.clone()], + "verified, with the description" + ); + for content in [a, tree] { + let error = repo + .fetch_records(&FetchRecords { + ids: vec![content.id()], + }) + .await + .unwrap_err(); + assert_eq!(code(error), ErrorCode::BadRequest, "content leaves by path"); + } // A record is refused unless the repository can use it. let orphan = Made::revision(change(2), main_tip(repo).await, vec![], &[("c.txt", "c")]); @@ -357,6 +372,68 @@ async fn promotions_must_match_their_original() { assert_eq!(stored.new, 1, "the original was stored with the forgery"); } +#[tokio::test] +async fn fetches_snapshots_by_walking_them() { + let server = Server::start().await; + let repo = &server.demo; + let made = Made::revision( + change(1), + main_tip(repo).await, + vec![], + &[("a.txt", "a"), ("b.txt", "b")], + ); + repo.put_records(&made.pack()).await.unwrap(); + let [a, b, tree, description, _] = &made.objects[..] else { + unreachable!() + }; + + let snapshot = |have: Vec, paths: &[&str]| FetchSnapshot { + snapshot: tree.id().into(), + have, + paths: paths + .iter() + .map(|path| RepoPath::new(path).unwrap()) + .collect(), + skip: 0, + }; + let whole = repo.fetch_snapshot(&snapshot(vec![], &[])).await.unwrap(); + assert_eq!(whole.pack.objects, [tree.clone(), a.clone(), b.clone()]); + let only_b = repo + .fetch_snapshot(&snapshot(vec![], &["b.txt"])) + .await + .unwrap(); + assert_eq!(only_b.pack.objects, [tree.clone(), b.clone()]); + let edited = Made::revision( + change(3), + main_tip(repo).await, + vec![], + &[("a.txt", "a"), ("b.txt", "c")], + ); + repo.put_records(&edited.pack()).await.unwrap(); + let changed = repo + .fetch_snapshot(&FetchSnapshot { + snapshot: edited.objects[2].id().into(), + have: vec![tree.id().into()], + paths: Vec::new(), + skip: 0, + }) + .await + .unwrap(); + assert_eq!( + changed.pack.objects, + [edited.objects[2].clone(), edited.objects[1].clone()], + "the new tree and the edited file" + ); + let missing = FetchSnapshot { + snapshot: description.id().into(), + have: Vec::new(), + paths: Vec::new(), + skip: 0, + }; + let error = repo.fetch_snapshot(&missing).await.unwrap_err(); + assert_eq!(code(error), ErrorCode::NotFound, "a blob is no snapshot"); +} + #[tokio::test] async fn reads_statements_and_revisions() { let server = Server::start().await; diff --git a/crates/origin-client/src/lib.rs b/crates/origin-client/src/lib.rs index 398f2d9c..77a1fe36 100644 --- a/crates/origin-client/src/lib.rs +++ b/crates/origin-client/src/lib.rs @@ -19,12 +19,13 @@ //! in `docs/openapi.json`, for other languages. use origin_shared::api::{ - Annotation, ApiError, EventsQuery, FetchRecords, LandRequest, Landings, LogEntry, LogQuery, - NewTarget, RepoName, RepoSummary, Revisions, StatementsQuery, Stored, TargetInfo, + Annotation, ApiError, 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 origin_shared::{ChangeId, Head}; use reqwest::{Method, RequestBuilder}; use serde::de::DeserializeOwned; @@ -65,9 +66,18 @@ endpoints! { } impl Repo { - /// Fetches objects by id, in the order asked. - fn fetch_records(request: &FetchRecords) -> Pack = - POST "records/fetch", json(request) => pack; + /// Fetches records by id, in the order asked, each followed by the + /// blob it carries if the server has it: a revision's description, + /// a statement's payload. A part that stops short holds those up to + /// the last record it has. + fn fetch_records(request: &FetchRecords) -> Part = + POST "records/fetch", json(request) => part; + /// Fetches the trees and blobs of a snapshot that none of the + /// request's snapshots holds at the same path, parents first. A + /// part that stops short is followed by asking again, skipping the + /// objects it holds. + fn fetch_snapshot(request: &FetchSnapshot) -> Part = + POST "snapshots/fetch", json(request) => part; /// 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; @@ -170,8 +180,10 @@ impl Response { Ok(self.0.json().await?) } - async fn pack(self) -> Result { - Ok(Pack::decode(&self.0.bytes().await?)?) + async fn part(self) -> Result { + let more = self.0.headers().contains_key(MORE); + let pack = Pack::decode(&self.0.bytes().await?)?; + Ok(Part { pack, more }) } } diff --git a/crates/origin-shared/src/api.rs b/crates/origin-shared/src/api.rs index c0b1caf6..8b91759c 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, Revision, RevisionId, - Statement, StatementId, TargetName, + Acceptance, AcceptanceId, Head, ObjectId, PrincipalName, RecordId, RepoPath, Revision, + RevisionId, Statement, StatementId, TargetName, TreeId, }; /// The name of a repository on a server: ASCII letters, digits, `.`, `_` @@ -95,13 +95,53 @@ pub struct RepoSummary { pub name: RepoName, } -/// Asks for records, and any other objects, by id. +/// The response header saying a fetch stopped short of what it asked for, +/// to stay within [`Pack::LIMIT`](crate::pack::Pack::LIMIT): see +/// [`Part`](crate::pack::Part). +pub const MORE: &str = "origin-more"; + +/// Asks for records by id: revisions, statements and acceptances. Each +/// comes with the blob it carries, if the repository has it: a revision's +/// description, a statement's payload. Snapshots are fetched with +/// [`FetchSnapshot`] instead. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, ToSchema)] pub struct FetchRecords { - /// The objects, returned in this order. + /// The records, returned in this order, each followed by its blob. A + /// response that stops short, with the [`MORE`] header, holds those up + /// to the last record it has: ask again for those after it. pub ids: Vec, } +/// Asks for the objects of a snapshot that the caller lacks: its trees and +/// blobs, walked from its root. This is the only way blobs and trees leave +/// a repository, so what each caller may read can be checked by path. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, ToSchema)] +pub struct FetchSnapshot { + /// The snapshot. + pub snapshot: TreeId, + /// Snapshots the caller holds whole. Whatever one of them holds at the + /// same path is skipped, so only what changed since comes. Those the + /// repository doesn't have are ignored. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub have: Vec, + /// Only these files and directories, with everything under them, and + /// the trees on the way to them. Everything by default. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub paths: Vec, + /// Skip this many of the objects, which earlier parts brought: a + /// response that stops short has the [`MORE`] header. + #[serde(default, skip_serializing_if = "is_zero")] + pub skip: u64, +} + +#[expect( + clippy::trivially_copy_pass_by_ref, + reason = "serde passes a reference" +)] +fn is_zero(value: &u64) -> bool { + *value == 0 +} + /// What putting a batch of records did. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, ToSchema)] pub struct Stored { diff --git a/crates/origin-shared/src/pack.rs b/crates/origin-shared/src/pack.rs index d9b76202..f32773ae 100644 --- a/crates/origin-shared/src/pack.rs +++ b/crates/origin-shared/src/pack.rs @@ -4,6 +4,10 @@ //! `id:[u8; 32] len:u64 bytes:[u8; len]` with `bytes` the object's encoding. //! Decoding verifies every object against its id, so a pack can come from an //! untrusted peer. +//! +//! Transfers are bounded: a [`Packer`] splits objects into packs of at most +//! [`Pack::LIMIT`] bytes, in order, so a push takes several requests, and a +//! fetch response stops at a [`Part`], with the rest asked for again. use std::collections::HashSet; @@ -20,14 +24,20 @@ pub struct Pack { impl Pack { const HEADER_LEN: usize = ObjectId::LEN + 8; + /// The most bytes a request or a response carries as one pack, encoded. + /// A pack holds one object at least, so an object larger than this + /// travels alone. + pub const LIMIT: usize = 64 << 20; + + /// The bytes `object` takes in an encoded pack. + fn encoded_len(object: &EncodedObject) -> usize { + Self::HEADER_LEN + object.bytes().len() + } + /// Encodes the pack. #[must_use] pub fn encode(&self) -> Vec { - let len = self - .objects - .iter() - .map(|object| Self::HEADER_LEN + object.bytes().len()) - .sum(); + let len = self.objects.iter().map(Self::encoded_len).sum(); let mut out = Vec::with_capacity(len); for object in &self.objects { out.extend_from_slice(object.id().as_bytes()); @@ -60,6 +70,97 @@ impl Pack { } } +/// Splits objects into packs of at most a limit, [`Pack::LIMIT`] by +/// default, in the order they're added. Objects only ever depend on those +/// before them, so each pack can be sent as soon as it's full. +#[derive(Debug)] +pub struct Packer { + limit: usize, + pack: Pack, + /// The encoded size of `pack`. + len: usize, +} + +impl Default for Packer { + fn default() -> Self { + Self::new(Pack::LIMIT) + } +} + +impl Packer { + /// A packer filling packs up to `limit` bytes. + #[must_use] + pub fn new(limit: usize) -> Self { + Self { + limit, + pack: Pack::default(), + len: 0, + } + } + + /// Whether the pack being filled has room for `objects`: an empty one + /// has room for anything. + #[must_use] + pub fn fits<'o>(&self, objects: impl IntoIterator) -> bool { + let len: usize = objects.into_iter().map(Pack::encoded_len).sum(); + self.pack.objects.is_empty() || self.len + len <= self.limit + } + + /// Adds `object` to the pack being filled. If it has no room for it, + /// returns that pack, full, and starts the next one with the object. + #[must_use = "a full pack is returned, not kept"] + pub fn add(&mut self, object: EncodedObject) -> Option { + self.add_together(vec![object]) + } + + /// Adds `objects` to the pack being filled, which they all go in. If it + /// has no room for them, returns that pack, full, and starts the next + /// one with them. + #[must_use = "a full pack is returned, not kept"] + pub fn add_together(&mut self, objects: Vec) -> Option { + let full = (!self.fits(&objects)).then(|| { + self.len = 0; + std::mem::take(&mut self.pack) + }); + self.extend(objects); + full + } + + /// Adds `objects` to the pack being filled, room or not: those + /// [`Packer::fits`] said it has room for. + pub fn extend(&mut self, objects: impl IntoIterator) { + for object in objects { + self.len += Pack::encoded_len(&object); + self.pack.objects.push(object); + } + } + + /// Whether no object was added since the last full pack. + #[must_use] + pub fn is_empty(&self) -> bool { + self.pack.objects.is_empty() + } + + /// The pack being filled. + #[must_use] + pub fn finish(self) -> Pack { + self.pack + } +} + +/// A fetch's answer, which may stop short of everything asked for, to stay +/// within [`Pack::LIMIT`]: then `more` is set, and asking again for the +/// rest brings the next part (see +/// [`FetchRecords`](crate::api::FetchRecords) and +/// [`FetchSnapshot`](crate::api::FetchSnapshot)). +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Part { + /// The objects of this part. + pub pack: Pack, + /// Whether it stopped short. + pub more: bool, +} + /// Bytes that are not a valid pack. #[derive(Debug, thiserror::Error)] pub enum PackError { @@ -94,6 +195,25 @@ mod tests { assert_eq!(Pack::decode(&pack.encode()).unwrap().objects, vec![blob]); } + #[test] + fn packers_split_in_order_within_the_limit() { + let large = [b'x'; 100]; + let objects: Vec<_> = [b"a".as_slice(), b"bb", b"c", &large] + .map(EncodedObject::blob) + .to_vec(); + let limit = 2 * Pack::encoded_len(&objects[0]) + 1; + let mut packer = Packer::new(limit); + let mut packs: Vec = objects + .iter() + .filter_map(|object| packer.add(object.clone())) + .collect(); + packs.push(packer.finish()); + let split: Vec = packs.iter().map(|pack| pack.objects.len()).collect(); + assert_eq!(split, [2, 1, 1], "one larger than the limit travels alone"); + let joined: Vec<_> = packs.into_iter().flat_map(|pack| pack.objects).collect(); + assert_eq!(joined, objects, "in order"); + } + #[test] fn rejects_truncated_and_corrupt_packs() { let mut bytes = Pack { diff --git a/docs/openapi.json b/docs/openapi.json index 3e2e4de0..0fc98ded 100644 --- a/docs/openapi.json +++ b/docs/openapi.json @@ -429,7 +429,7 @@ }, "/api/v1/repos/{repo}/records/fetch": { "post": { - "summary": "Fetches objects by id, as a pack.", + "summary": "Fetches records by id, each with the blob it carries, as a pack.", "operationId": "fetch_records", "parameters": [ { @@ -454,7 +454,15 @@ }, "responses": { "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", + "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", + "headers": { + "origin-more": { + "schema": { + "type": "boolean" + }, + "description": "Present if the pack stopped short: ask again for the records after the last it holds" + } + }, "content": { "application/octet-stream": { "schema": { @@ -463,8 +471,75 @@ } } }, + "400": { + "description": "An object is a blob or a tree, which only leave by walking a snapshot", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, "404": { - "description": "The repository or an object does not exist", + "description": "The repository or a record does not exist", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + } + } + } + }, + "/api/v1/repos/{repo}/snapshots/fetch": { + "post": { + "summary": "Fetches the objects of a snapshot the caller lacks, as a pack: the only\nway trees and blobs leave a repository.", + "operationId": "fetch_snapshot", + "parameters": [ + { + "name": "repo", + "in": "path", + "description": "The repository", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/FetchSnapshot" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "The trees and blobs, parents before children, as a pack, of at most 64 MiB, but for an object alone", + "headers": { + "origin-more": { + "schema": { + "type": "boolean" + }, + "description": "Present if the pack stopped short: ask again, skipping the objects it holds" + } + }, + "content": { + "application/octet-stream": { + "schema": { + "$ref": "#/components/schemas/Binary" + } + } + } + }, + "404": { + "description": "The repository or the snapshot does not exist", "content": { "application/json": { "schema": { @@ -1052,7 +1127,7 @@ }, "FetchRecords": { "type": "object", - "description": "Asks for records, and any other objects, by id.", + "description": "Asks for records by id: revisions, statements and acceptances. Each\ncomes with the blob it carries, if the repository has it: a revision's\ndescription, a statement's payload. Snapshots are fetched with\n[`FetchSnapshot`] instead.", "required": [ "ids" ], @@ -1062,7 +1137,40 @@ "items": { "$ref": "#/components/schemas/ObjectId" }, - "description": "The objects, returned in this order." + "description": "The records, returned in this order, each followed by its blob. A\nresponse that stops short, with the [`MORE`] header, holds those up\nto the last record it has: ask again for those after it." + } + } + }, + "FetchSnapshot": { + "type": "object", + "description": "Asks for the objects of a snapshot that the caller lacks: its trees and\nblobs, walked from its root. This is the only way blobs and trees leave\na repository, so what each caller may read can be checked by path.", + "required": [ + "snapshot" + ], + "properties": { + "have": { + "type": "array", + "items": { + "$ref": "#/components/schemas/TreeId" + }, + "description": "Snapshots the caller holds whole. Whatever one of them holds at the\nsame path is skipped, so only what changed since comes. Those the\nrepository doesn't have are ignored." + }, + "paths": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RepoPath" + }, + "description": "Only these files and directories, with everything under them, and\nthe trees on the way to them. Everything by default." + }, + "skip": { + "type": "integer", + "format": "int64", + "description": "Skip this many of the objects, which earlier parts brought: a\nresponse that stops short has the [`MORE`] header.", + "minimum": 0 + }, + "snapshot": { + "$ref": "#/components/schemas/TreeId", + "description": "The snapshot." } } },