diff --git a/README.md b/README.md index e319d8d6..3e728f32 100644 --- a/README.md +++ b/README.md @@ -126,7 +126,10 @@ 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. +are events after the cursor, with a JSON batch, the next cursor, and the +generation of the op log it's of: pass it back as `generation`, and a +cursor of another log, such as from before the repository was restored, +is refused as expired. [`docs/openapi.json`](docs/openapi.json) describes it, and [`origin-client`](crates/origin-client) is its Rust SDK. Nothing authenticates callers yet. diff --git a/apps/origin-src/src/events.rs b/apps/origin-src/src/events.rs index 49fab4a3..f5d51c9f 100644 --- a/apps/origin-src/src/events.rs +++ b/apps/origin-src/src/events.rs @@ -121,6 +121,7 @@ impl<'a, P: Platform> Events<'a, P> { let mut page = Page { events: Vec::new(), next: cursor, + ..Page::default() }; let oplog = self.store.oplog(); let read = oplog.after(cursor)?; @@ -457,7 +458,8 @@ mod tests { held, Page { events: Vec::new(), - next: crashed - 1 + next: crashed - 1, + ..Page::default() }, "it may be in progress" ); @@ -520,7 +522,8 @@ mod tests { empty, Page { events: Vec::new(), - next: end + next: end, + ..Page::default() } ); thread::scope(|scope| { diff --git a/apps/origin-src/src/index.rs b/apps/origin-src/src/index.rs index 76ab1245..b35ce7d8 100644 --- a/apps/origin-src/src/index.rs +++ b/apps/origin-src/src/index.rs @@ -386,6 +386,11 @@ impl Index { &self.arrivals } + /// Every change with a revision, in no particular order. + pub fn changes(&self) -> impl Iterator { + self.changes.keys().copied() + } + /// The revisions of `change`, in arrival order. #[must_use] pub fn revisions(&self, change: ChangeId) -> &[RevisionId] { diff --git a/apps/origin-src/src/oplog.rs b/apps/origin-src/src/oplog.rs index 1e75f90c..4aea9a2f 100644 --- a/apps/origin-src/src/oplog.rs +++ b/apps/origin-src/src/oplog.rs @@ -17,6 +17,7 @@ //! //! ```text //! .origin/oplog/ +//! generation a random id, made with the log //! lock held exclusively while appending //! writers/ held by each writer while it writes //! segments of entries, 16 hex digits each @@ -25,7 +26,9 @@ //! A segment is a file of [frames](crate::frames), an entry each. Entries are //! appended to the last segment until it's full, then to a new one, and the //! oldest segments are deleted beyond a cap: the log keeps the latest 16 MiB -//! of entries, and a cursor older than that has expired. +//! of entries, and a cursor older than that has expired. So has a cursor +//! of another log, such as the one a restored repository had: the log's +//! generation tells them apart ([`OpLog::generation`]). //! //! **Writing.** Events and the index come from the entries, so every entry //! must be durable before a reader moves past it: a power loss could drop @@ -455,17 +458,56 @@ impl<'a, P: Platform> OpLog<'a, P> { let writers = self.dir().join(Self::WRITERS); fs::create_dir_all(&writers).map_err(|source| StoreError::io(&writers, source))?; self.start_segment(1, &[])?; + self.generation()?; Ok(()) } - /// Opens and locks one of the log's lock files, creating the log's - /// directory, durably, if it's missing. - fn lock(&self, name: &str, mode: LockMode) -> Result { + /// The file holding the log's generation. + const GENERATION: &str = "generation"; + + /// The log's generation: a random id made with it, which a log made + /// later, as when a repository is restored from a copy of its records, + /// doesn't share. The cursors of one log mean nothing in another. + /// + /// # Errors + /// + /// Fails if the generation cannot be read, or made and written. + pub fn generation(&self) -> Result { + let path = self.dir().join(Self::GENERATION); + let read = |path: &Path| match fs::read_to_string(path) { + Ok(generation) => Ok(Some(generation.trim_end().to_owned())), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None), + Err(source) => Err(StoreError::io(path, source)), + }; + if let Some(generation) = read(&path)? { + return Ok(generation); + } + // A log made without one. Writers racing to make it each write + // theirs, and the last stays: a cursor from another only costs a + // full read. + self.create_dir()?; + let generation = getrandom::u64().map_err(StoreError::Random)?; + let write = self.store.durable_write(); + write.stage(&path, format!("{generation:016x}\n").as_bytes())?; + write.commit()?; + Ok(read(&path)?.unwrap_or_default()) + } + + /// Creates the log's directory, durably, if it's missing. + fn create_dir(&self) -> Result<(), StoreError> { let dir = self.dir(); if !dir.is_dir() { fs::create_dir_all(&dir).map_err(|source| StoreError::io(&dir, source))?; self.store.sync_dir(self.store.root())?; } + Ok(()) + } + + /// Opens and locks one of the log's lock files, creating the log's + /// directory, durably, if it's missing. + fn lock(&self, name: &str, mode: LockMode) -> Result { + self.create_dir()?; + let dir = self.dir(); Ok(LockedFile::open( &self.store.platform, &dir.join(name), diff --git a/apps/origin-src/src/service.rs b/apps/origin-src/src/service.rs index 2ef5e623..0e5c032f 100644 --- a/apps/origin-src/src/service.rs +++ b/apps/origin-src/src/service.rs @@ -707,8 +707,15 @@ impl OriginService { /// # Errors /// /// Fails if the op log no longer keeps the events after the cursor, or - /// it or a record cannot be read. + /// isn't of the generation the query names, or it or a record cannot + /// be read. pub fn events(&self, _caller: &Caller, query: &EventsQuery) -> Result { + let generation = self.store.oplog().generation()?; + if let Some(theirs) = &query.generation + && *theirs != generation + { + return Err(ServiceError::OtherLog(theirs.clone())); + } let events = Events::new(&self.store).waking_on(&self.wakeup); let cursor = match query.cursor { Some(cursor) => cursor, @@ -723,7 +730,8 @@ impl OriginService { .unwrap_or(Self::MAX_EVENTS) .min(Self::MAX_EVENTS) as usize; let wait = query.wait.map_or(Duration::ZERO, |wait| wait.0); - Ok(events.wait(cursor, &filter, limit, wait.min(Self::MAX_WAIT))?) + let page = events.wait(cursor, &filter, limit, wait.min(Self::MAX_WAIT))?; + Ok(Page { generation, ..page }) } } @@ -873,6 +881,9 @@ pub enum ServiceError { /// Its heads now. heads: Vec, }, + /// An events cursor is of another op log than the repository's. + #[error("the cursor is of another op log, generation {0}: read from the end")] + OtherLog(String), /// A statement put isn't one the repository accepts: a promotion that /// doesn't match its original. #[error("statement {} cannot be put", .id.short())] @@ -913,6 +924,7 @@ impl ServiceError { _ => ErrorCode::BadRequest, }, Self::Moved { .. } => ErrorCode::Conflict, + Self::OtherLog(_) => ErrorCode::Expired, Self::Land(error) => match error { LandError::UnknownTarget(_) | LandError::UnknownChange(_) => ErrorCode::NotFound, LandError::TargetExists(_) diff --git a/apps/origin-src/src/store/mod.rs b/apps/origin-src/src/store/mod.rs index 48259051..b72b7276 100644 --- a/apps/origin-src/src/store/mod.rs +++ b/apps/origin-src/src/store/mod.rs @@ -804,6 +804,9 @@ pub enum StoreError { /// Why decoding failed. source: DecodeError, }, + /// The operating system has no randomness to give. + #[error("cannot draw a random id")] + Random(#[source] getrandom::Error), /// The op log no longer keeps the entries after a cursor: retention /// deleted them. #[error("the op log no longer keeps the entries after #{after}: its oldest is #{oldest}")] diff --git a/apps/origin-src/src/sync.rs b/apps/origin-src/src/sync.rs index 48fcb946..ead6032a 100644 --- a/apps/origin-src/src/sync.rs +++ b/apps/origin-src/src/sync.rs @@ -11,9 +11,13 @@ //! stores, such as the base of a revision fetched, never govern anything. //! Each acceptance comes with what it landed, and the records of the //! changes that brings. -//! - The records of changes are compared with the remote's, by id, and -//! those missing fetched, with the records they refer to, and the records -//! of the changes those belong to. +//! - Then the records of each change that moved are compared with the +//! remote's, by id, and those missing fetched, with the records they +//! refer to, and the records of the changes those belong to. The changes +//! that moved are those the remote's events since the last fetch name +//! ([`Sync::moved`]), so a fetch that brings nothing costs the same +//! however long the history: only without a cursor, or once it expired, +//! are all the changes this node knows compared. //! - Snapshots don't come with records: [`Sync::need`] fetches one when //! something reads it, such as a checkout. A snapshot is marked while it's //! fetched ([`Store::fetching`]), so one whose fetch was interrupted is @@ -29,15 +33,19 @@ use std::collections::{BTreeSet, HashMap, HashSet}; use std::mem; use origin_platform::Native; -use origin_shared::api::{FetchRecords, FetchSnapshot, InventoryRequest, LogQuery}; +use origin_shared::api::{ + ErrorCode, EventsQuery, FetchRecords, FetchSnapshot, InventoryRequest, List, LogQuery, +}; +use origin_shared::event::EventKind; use origin_shared::object::{BadSignature, DecodeError}; use origin_shared::pack::Part; use origin_shared::{ Acceptance, AcceptanceId, ChangeId, EncodedObject, Head, Object, ObjectId, ObjectKind, - Principal, PrincipalName, Record, Revision, TargetName, TreeId, + Principal, PrincipalName, Record, RecordId, Revision, TargetName, TreeId, }; use crate::annotations::Annotations; +use crate::index::Index; use crate::policy::{Policy, PolicyError}; use crate::remote::{Remote, RemoteError}; use crate::service::Dependencies; @@ -71,6 +79,39 @@ pub struct Fetched { pub statements: usize, } +/// What a fetch did. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Fetch { + /// The targets whose chains it extended. + pub advanced: Vec, + /// The records it fetched. + pub fetched: Fetched, + /// The remote's event cursor to fetch from next time. + pub cursor: Cursor, +} + +/// Where the remote's events are read from: after a sequence number of +/// its op log, which only means something in the log of its generation. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Cursor { + /// The generation of the remote's op log. + pub generation: String, + /// The sequence number to read after. + pub next: u64, +} + +/// What the remote's events say moved since a cursor. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Moved { + /// The remote's cursor after those events: where the next fetch reads + /// from. + pub cursor: Cursor, + /// The changes that have revisions or statements the events name, or + /// `None` if the events since the cursor are unknown: there was none, + /// the remote no longer keeps them, or it's of another op log. + pub changes: Option>, +} + /// The new acceptances of a target, verified and about to be appended. struct Chain { target: TargetName, @@ -82,6 +123,10 @@ struct Chain { } impl<'a> Sync<'a> { + /// The most events a page of [`Sync::moved`] asks for: as many as a + /// server sends. + const EVENTS: u32 = 1024; + /// Syncs `store` with `remote`, as the node `node`. pub fn new(store: &'a Store, remote: &'a Remote, node: PrincipalName) -> Self { Self { @@ -91,6 +136,46 @@ impl<'a> Sync<'a> { } } + /// Fetches as the module explains: the chains of the targets this node + /// follows and of `targets`, then the records of `changes` and of those + /// this node knows that moved since `cursor`, the remote's event cursor + /// as of the last fetch, or of all those it knows without one. + /// + /// # Errors + /// + /// Fails like [`Sync::fetch_chains`] and [`Sync::fetch_changes`]. + pub fn fetch( + &self, + targets: &[TargetName], + changes: &[ChangeId], + cursor: Option<&Cursor>, + ) -> Result { + // Read first, so what moves while this fetches is fetched again. + let moved = self.moved(cursor)?; + let (advanced, landed) = self.chains(targets)?; + let mut wanted: Vec = match &moved.changes { + // Nothing moved: the index needn't even be read. + Some(moved) if moved.is_empty() => Vec::new(), + Some(moved) => { + let index = Index::open(self.store)?; + moved + .iter() + .copied() + .filter(|&change| !index.revisions(change).is_empty()) + .collect() + } + None => Index::open(self.store)?.changes().collect(), + }; + wanted.extend(changes.iter().chain(&landed)); + wanted.sort_unstable(); + wanted.dedup(); + Ok(Fetch { + advanced, + fetched: self.fetch_changes(&wanted)?, + cursor: moved.cursor, + }) + } + /// Fetches the chains of `policy`, of the targets this node holds, and /// of `more`, with what they landed, as the module explains. Returns /// the targets that moved, `policy` first. Learns the names of all the @@ -302,6 +387,124 @@ impl<'a> Sync<'a> { Ok(on_chain.then_some(body.state)) } + /// The remote's cursor after its events since `since`, and the changes + /// they say moved: those with a revision created or a statement issued + /// about them, or about a statement about them. Without `since`, or if + /// the remote no longer keeps its events, or its op log is of another + /// generation, as once it was restored, the remote's current cursor, + /// and no changes: then every change may have moved. + /// + /// # Errors + /// + /// Fails if the remote or the store fails. + pub fn moved(&self, since: Option<&Cursor>) -> Result { + // Should a name not parse, every event comes, and those of other + // kinds name no change. + let kinds = ["revision.created", "statement.issued"] + .into_iter() + .filter_map(|kind| kind.parse().ok()) + .collect(); + let mut query = EventsQuery { + kind: List(kinds), + limit: Some(Self::EVENTS), + ..EventsQuery::default() + }; + let everything = |query: &mut EventsQuery| { + query.cursor = None; + query.generation = None; + let page = self.remote.events(query)?; + Ok(Moved { + cursor: Cursor { + generation: page.generation, + next: page.next, + }, + changes: None, + }) + }; + let Some(since) = since else { + return everything(&mut query); + }; + let mut cursor = since.clone(); + let mut events = Vec::new(); + loop { + query.cursor = Some(cursor.next); + query.generation = Some(cursor.generation.clone()); + let page = match self.remote.events(&query) { + Err(error) if error.code() == Some(ErrorCode::Expired) => { + return everything(&mut query); + } + page => page?, + }; + cursor.next = page.next; + // A page short of the limit holds every event there was. + let last = page.events.len() < Self::EVENTS as usize; + events.extend(page.events.into_iter().map(|event| event.kind)); + if last { + break; + } + } + Ok(Moved { + cursor, + changes: Some(self.changes_moved(&events)?), + }) + } + + /// The changes `events` name, as [`Sync::moved`] says. A statement is + /// traced to its subject through the events, then this node's records: + /// one about a record it knows nothing of is about no change it knows. + fn changes_moved(&self, events: &[EventKind]) -> Result, SyncError> { + let mut changes = HashSet::new(); + let mut revisions = HashMap::new(); + let mut subjects = HashMap::new(); + for event in events { + match *event { + EventKind::RevisionCreated { + revision, change, .. + } => { + changes.insert(change); + revisions.insert(revision, change); + } + EventKind::StatementIssued { + statement, subject, .. + } => { + subjects.insert(statement, subject); + } + _ => {} + } + } + for &subject in subjects.values() { + let mut subject = subject; + // A chain of statements ends at a record, or one unknown. + let change = loop { + match subject { + RecordId::Revision(id) => match revisions.get(&id) { + Some(&change) => break Some(change), + None => break self.stored(id)?.map(|revision| revision.change), + }, + RecordId::Statement(id) => match subjects.get(&id) { + Some(&next) if next != subject => subject = next, + _ => match self.stored(id)? { + Some(statement) => subject = statement.subject, + None => break None, + }, + }, + RecordId::Acceptance(_) | RecordId::Snapshot(_) => break None, + } + }; + changes.extend(change); + } + Ok(changes) + } + + /// The record `id` names, if this node has it. + fn stored(&self, id: I) -> Result, StoreError> { + match self.store.get(id) { + Ok(record) => Ok(Some(record)), + Err(StoreError::NotFound(_)) => Ok(None), + Err(error) => Err(error), + } + } + /// Fetches the records of `changes` the remote has and this node /// doesn't: their revisions and the statements about them, with the /// records they refer to, and then the records of the changes the @@ -587,9 +790,9 @@ mod tests { use std::sync::Arc; use origin_platform::Native; - use origin_shared::event::{EventKind, Filter}; + use origin_shared::event::Filter; use origin_shared::pack::Pack; - use origin_shared::{AcceptanceBody, Base, NodeKey, RepoPath}; + use origin_shared::{AcceptanceBody, Base, NodeKey, RepoPath, Statement}; use super::*; use crate::events::Events; @@ -636,6 +839,10 @@ mod tests { } } + fn main_tip(store: &Store) -> Base { + Base::Acceptance(store.head(&TargetName::MAIN).unwrap().unwrap().acceptance) + } + /// Writes a snapshot of `policy.toml` making `key` the key of /// `node:queue`, the authority of `policy`, to `store`. fn policy_snapshot(store: &Store, key: &NodeKey) -> TreeId { @@ -952,4 +1159,63 @@ mod tests { client.sync().repair(snapshot).unwrap(); assert_eq!(client.store.diff(empty, snapshot).unwrap().len(), 1); } + + #[test] + fn the_remote_events_say_which_changes_moved() { + let server = Repo::new(MAIN_RULES); + let first = server.change_on_main(1, &[("a", "a")]); + let second = server.change_on_main(2, &[("b", "b")]); + let client = Client::new(&server); + let both = [1, 2].map(|change| ChangeId::from_bytes([change; 16])); + client.sync().fetch_changes(&both).unwrap(); + let moved = client.sync().moved(None).unwrap(); + assert_eq!(moved.changes, None, "without a cursor, any change may have"); + let cursor = moved.cursor; + let nothing = client.sync().moved(Some(&cursor)).unwrap(); + assert_eq!(nothing.changes, Some(HashSet::new())); + assert_eq!(nothing.cursor, cursor); + + // A statement about a statement about the second change, and a + // revision of the first. + let annotations = server.annotations(); + let result = annotations + .issue(&ci_test(second, "node:ci"), None) + .unwrap(); + let flaky = Statement { + subject: RecordId::Statement(result), + kind: "flaky".parse().unwrap(), + verdict: None, + inputs: None, + ..ci_test(second, "user:ada") + }; + annotations.issue(&flaky, None).unwrap(); + let tip = main_tip(&server.store); + server.revision(1, &[first], tip, &[("a", "again")]); + let moved = client.sync().moved(Some(&cursor)).unwrap(); + assert_eq!(moved.changes, Some(HashSet::from(both))); + assert!(moved.cursor.next > cursor.next); + } + + #[test] + fn cursors_of_another_op_log_read_everything() { + let server = Repo::new(MAIN_RULES); + let first = server.change_on_main(1, &[("a", "a")]); + let change = ChangeId::from_bytes([1; 16]); + let client = Client::new(&server); + let fetch = client + .sync() + .fetch(&[TargetName::MAIN], &[change], None) + .unwrap(); + // The remote was restored, with a new op log, and has a revision + // since: a cursor of the old log, even ahead of the new one's + // end, finds it. + let cursor = Cursor { + generation: "restored".to_owned(), + next: fetch.cursor.next + 10_000, + }; + let newer = server.revision(1, &[first], main_tip(&server.store), &[("a", "new")]); + let fetch = client.sync().fetch(&[], &[], Some(&cursor)).unwrap(); + assert!(client.store.contains(newer.into()).unwrap()); + assert_ne!(fetch.cursor.generation, cursor.generation); + } } diff --git a/apps/origin-src/src/workspace/ops.rs b/apps/origin-src/src/workspace/ops.rs index 19b9df91..988d5f52 100644 --- a/apps/origin-src/src/workspace/ops.rs +++ b/apps/origin-src/src/workspace/ops.rs @@ -223,6 +223,7 @@ impl Workspace { let service = self.service(None)?; let mut query = EventsQuery { cursor: since, + generation: None, wait: Some(Period(OriginService::MAX_WAIT)), limit: Some(256), kind: List(kinds), @@ -234,6 +235,7 @@ impl Workspace { println!("{event}"); } query.cursor = Some(page.next); + query.generation = Some(page.generation); } } } diff --git a/crates/origin-shared/src/api.rs b/crates/origin-shared/src/api.rs index 4f6cd521..85cb2e11 100644 --- a/crates/origin-shared/src/api.rs +++ b/crates/origin-shared/src/api.rs @@ -346,6 +346,10 @@ pub struct EventsQuery { /// The cursor to read after: the `next` of the previous page. By /// default, the end of the stream, so only new events come. pub cursor: Option, + /// The generation of the op log the cursor is of, as its page said. A + /// cursor of another generation, such as from before the repository + /// was restored, has expired. + pub generation: Option, /// How long to wait for events, such as `30s`. Without it, the answer /// comes at once, possibly empty. #[param(value_type = Option)] diff --git a/crates/origin-shared/src/event.rs b/crates/origin-shared/src/event.rs index 2c587b12..a3f06c51 100644 --- a/crates/origin-shared/src/event.rs +++ b/crates/origin-shared/src/event.rs @@ -254,6 +254,10 @@ pub struct Page { pub events: Vec, /// The cursor after the entries read: pass it to the next read. pub next: u64, + /// The generation of the op log the cursor is of: pass it with the + /// cursor, which means nothing in another. + #[serde(default)] + pub generation: String, } #[cfg(test)] diff --git a/docs/openapi.json b/docs/openapi.json index 87d85bbb..1e9db4e8 100644 --- a/docs/openapi.json +++ b/docs/openapi.json @@ -173,6 +173,15 @@ "minimum": 0 } }, + { + "name": "generation", + "in": "query", + "description": "The generation of the op log the cursor is of, as its page said. A\ncursor of another generation, such as from before the repository\nwas restored, has expired.", + "required": false, + "schema": { + "type": "string" + } + }, { "name": "wait", "in": "query", @@ -1531,6 +1540,10 @@ }, "description": "The events, oldest first." }, + "generation": { + "type": "string", + "description": "The generation of the op log the cursor is of: pass it with the\ncursor, which means nothing in another." + }, "next": { "type": "integer", "format": "int64",