diff --git a/apps/origin-src/benches/land.rs b/apps/origin-src/benches/land.rs index 8a152d3e..db16d29c 100644 --- a/apps/origin-src/benches/land.rs +++ b/apps/origin-src/benches/land.rs @@ -9,12 +9,13 @@ use std::thread; use divan::Bencher; use divan::counter::ItemsCount; use origin_platform::Native; +use origin_shared::landing::Landing; use origin_shared::{ AcceptanceId, Base, ChangeId, EncodedObject, EntryKind, EntryName, Kind, NodeKey, PrincipalName, Record, RecordId, Revision, Statement, TargetName, Tree, TreeEntry, Verdict, }; use origin_src::annotations::Annotations; -use origin_src::queue::{Landing, Queue}; +use origin_src::queue::Queue; use origin_src::store::Store; fn main() { diff --git a/apps/origin-src/benches/store.rs b/apps/origin-src/benches/store.rs index 526706c6..8be84474 100644 --- a/apps/origin-src/benches/store.rs +++ b/apps/origin-src/benches/store.rs @@ -12,11 +12,12 @@ use divan::{Bencher, black_box}; use origin_platform::{ CloneFile, Durability, Error, FileLock, FileSystem, FsKind, Native, Platform, ReadAt, }; +use origin_shared::event::Filter; use origin_shared::{ AcceptanceBody, Base, ChangeId, EncodedObject, Kind, NodeKey, Record, RecordId, Revision, Statement, TargetName, Tree, TreeId, Verdict, }; -use origin_src::events::{Events, Filter}; +use origin_src::events::Events; use origin_src::index::Index; use origin_src::store::Store; diff --git a/apps/origin-src/src/cli.rs b/apps/origin-src/src/cli.rs index 8968d961..8bf2c0cd 100644 --- a/apps/origin-src/src/cli.rs +++ b/apps/origin-src/src/cli.rs @@ -9,11 +9,11 @@ use std::str::FromStr; use anyhow::{Context, Result}; use clap::error::ErrorKind; use clap::{Args, CommandFactory, Parser, Subcommand}; +use origin_shared::event::Filter; use origin_shared::policy::KindPattern; use origin_shared::{Digest, Inputs, Kind, RepoPath, TargetName, Verdict}; use crate::config::UserConfig; -use crate::events::Filter; use crate::oplog::Actor; use crate::workspace::{Annotated, Payload, Workspace}; diff --git a/apps/origin-src/src/events.rs b/apps/origin-src/src/events.rs index 61cb639c..c192ede0 100644 --- a/apps/origin-src/src/events.rs +++ b/apps/origin-src/src/events.rs @@ -25,251 +25,19 @@ //! a power loss could take back, so none is reused. Entries lost to damage //! deliver nothing, and the damage is reported on stderr. -use std::fmt; use std::thread; use std::time::{Duration, Instant}; use origin_platform::{Native, Platform}; -use origin_shared::policy::{KindPattern, Requirement}; -use origin_shared::{ - AcceptanceId, ChangeId, Kind, Object, ObjectId, Principal, RecordId, RevisionId, StatementId, - TargetName, Verdict, -}; +use origin_shared::event::{Event, EventKind, Filter, Page}; +use origin_shared::landing::{Blocked, Pending}; +use origin_shared::{Object, ObjectId}; use crate::index; use crate::oplog::{Effect, Entry}; -use crate::queue::{Blocked, Pending, Queue}; +use crate::queue::Queue; use crate::store::{Store, StoreError}; -/// Something that happened, and where it is in the op log. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct Event { - /// The sequence number of the op log entry it comes from. Reading from - /// it delivers the events of the entries after it. - pub cursor: u64, - /// What happened. - pub kind: EventKind, -} - -/// What happened: an event's identity, which consumers deduplicate by. -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -pub enum EventKind { - /// A statement was issued. - StatementIssued { - /// The statement. - statement: StatementId, - /// What it's about. - subject: RecordId, - /// Its kind. - kind: Kind, - /// Its verdict. - verdict: Option, - /// Who issued it. - issuer: Principal, - }, - /// A revision was created. - RevisionCreated { - /// The revision. - revision: RevisionId, - /// Its change. - change: ChangeId, - /// Who made it. - author: Principal, - }, - /// A target advanced. - TargetAdvanced { - /// The target. - target: TargetName, - /// The acceptance's position in its log. - seq: u64, - /// The acceptance. - acceptance: AcceptanceId, - }, - /// A landing waits for a statement it requires. - CheckRequested { - /// The target it lands on. - onto: TargetName, - /// What the statement must be about. - subject: RecordId, - /// The statement required. - requirement: Requirement, - }, -} - -/// What an event is about, which `--subject` matches. -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum Subject { - /// A record. - Record(RecordId), - /// A change: the subject of its revisions' events. - Change(ChangeId), - /// A target. - Target(TargetName), -} - -impl EventKind { - /// The event's name, such as `statement.issued`. - #[must_use] - pub fn name(&self) -> &'static str { - match self { - Self::StatementIssued { .. } => "statement.issued", - Self::RevisionCreated { .. } => "revision.created", - Self::TargetAdvanced { .. } => "target.advanced", - Self::CheckRequested { .. } => "check.requested", - } - } - - /// The record the event is about: the statement, revision or - /// acceptance, or for a check, the record to check. - #[must_use] - pub fn record(&self) -> RecordId { - match *self { - Self::StatementIssued { statement, .. } => RecordId::Statement(statement), - Self::RevisionCreated { revision, .. } => RecordId::Revision(revision), - Self::TargetAdvanced { acceptance, .. } => RecordId::Acceptance(acceptance), - Self::CheckRequested { subject, .. } => subject, - } - } - - /// What the event is about: a statement's or a check's subject, a - /// revision's change, or the target that advanced. - #[must_use] - pub fn subject(&self) -> Subject { - match self { - Self::StatementIssued { subject, .. } | Self::CheckRequested { subject, .. } => { - Subject::Record(*subject) - } - Self::RevisionCreated { change, .. } => Subject::Change(*change), - Self::TargetAdvanced { target, .. } => Subject::Target(target.clone()), - } - } - - /// What `--subject` matches the event by: its [subject](Self::subject), - /// and for a revision created, the revision too. - fn subjects(&self) -> Vec { - let subject = self.subject(); - match *self { - Self::RevisionCreated { revision, .. } => { - vec![subject, Subject::Record(RecordId::Revision(revision))] - } - _ => vec![subject], - } - } - - /// The kinds `--kind` matches the event by: its name, and the kind of - /// the statement issued or requested. - fn kinds(&self) -> Vec { - let name = Kind::new(self.name()).expect("event names are valid kinds"); - match self { - Self::StatementIssued { kind, .. } => vec![name, kind.clone()], - Self::CheckRequested { requirement, .. } => vec![name, requirement.kind.clone()], - Self::RevisionCreated { .. } | Self::TargetAdvanced { .. } => vec![name], - } - } -} - -impl fmt::Display for Subject { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Record(RecordId::Snapshot(id)) => write!(f, "snapshot:{id}"), - Self::Record(RecordId::Revision(id)) => write!(f, "revision:{id}"), - Self::Record(RecordId::Statement(id)) => write!(f, "statement:{id}"), - Self::Record(RecordId::Acceptance(id)) => write!(f, "acceptance:{id}"), - Self::Change(id) => write!(f, "change:{id}"), - Self::Target(name) => write!(f, "target:{name}"), - } - } -} - -/// One line: the cursor, the name, then `key=value` fields with full ids. -impl fmt::Display for Event { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{} {}", self.cursor, self.kind.name())?; - let verdict = |verdict: &Option| { - verdict.map_or_else(|| "none".to_owned(), |verdict| verdict.to_string()) - }; - match &self.kind { - EventKind::StatementIssued { - statement, - subject, - kind, - verdict: issued, - issuer, - } => write!( - f, - " statement={statement} subject={} kind={kind} verdict={} issuer={issuer}", - Subject::Record(*subject), - verdict(issued) - ), - EventKind::RevisionCreated { - revision, - change, - author, - } => write!(f, " revision={revision} change={change} author={author}"), - EventKind::TargetAdvanced { - target, - seq, - acceptance, - } => write!(f, " target={target} seq={seq} acceptance={acceptance}"), - EventKind::CheckRequested { - onto, - subject, - requirement, - } => write!( - f, - " onto={onto} subject={} kind={} verdict={} issuer={}", - Subject::Record(*subject), - requirement.kind, - requirement.verdict, - requirement.issuer - ), - } - } -} - -/// Which events to deliver. An empty list matches everything. -#[derive(Clone, Debug, Default)] -pub struct Filter { - /// Event names or statement kinds, such as `check.requested`, - /// `core.conflict` or `ci.*`: an event matches one if its name, or the - /// kind it issues or requests, does. - pub kinds: Vec, - /// Starts of subjects, such as a revision id prefix, `change:3fa2` or - /// `main`: an event matches one if its [subject](EventKind::subject), - /// or a revision's creation its revision, written as `revision:`, - /// or its id or name alone, starts with it. - pub subjects: Vec, -} - -impl Filter { - /// Whether `event` passes the filter. - #[must_use] - pub fn matches(&self, event: &EventKind) -> bool { - let kind = self.kinds.is_empty() - || event - .kinds() - .iter() - .any(|kind| self.kinds.iter().any(|pattern| pattern.matches(kind))); - kind && (self.subjects.is_empty() - || event.subjects().iter().any(|subject| { - let subject = subject.to_string(); - let bare = subject.split_once(':').map_or("", |(_, bare)| bare); - self.subjects.iter().any(|start| { - subject.starts_with(start.as_str()) || bare.starts_with(start.as_str()) - }) - })) - } -} - -/// A batch of events, and the cursor to read the next batch from. -#[derive(Clone, Debug, Default, PartialEq, Eq)] -pub struct Page { - /// The events, oldest first. - pub events: Vec, - /// The cursor after the entries read: pass it to the next read. - pub next: u64, -} - /// The events of a store. #[derive(Debug)] pub struct Events<'a, P = Native> { @@ -449,10 +217,10 @@ impl<'a, P: Platform> Events<'a, P> { #[cfg(test)] mod tests { - use std::collections::HashSet; use std::fs; - use origin_shared::{Base, ChangeId, EncodedObject, ObjectId}; + use origin_shared::event::Subject; + use origin_shared::{Base, ChangeId, ObjectId, RecordId, TargetName}; use super::*; use crate::annotations::Annotations; @@ -666,7 +434,7 @@ mod tests { // file replaces the conflict's: readers wait for both. let again = Effect::Waiting { onto: TargetName::MAIN, - proposal: crate::queue::Proposal::Change(ChangeId::from_bytes([2; 16])), + proposal: origin_shared::landing::Proposal::Change(ChangeId::from_bytes([2; 16])), }; let (_, writing) = repo.store.oplog().append_in_progress(&again).unwrap(); assert_eq!( @@ -686,29 +454,6 @@ mod tests { ); } - #[test] - fn check_requests_about_one_record_are_told_apart() { - let subject = RecordId::Revision(EncodedObject::blob(b"a revision").id().into()); - let request = |onto: &str, kind: &str| EventKind::CheckRequested { - onto: TargetName::new(onto).unwrap(), - subject, - requirement: Requirement { - kind: Kind::new(kind).unwrap(), - verdict: Verdict::Pass, - issuer: "group:runners".parse().unwrap(), - }, - }; - let requests = [ - request("main", "ci.test"), - request("main", "ci.lint"), - request("release", "ci.test"), - request("main", "ci.test"), - ]; - assert!(requests.iter().all(|request| request.record() == subject)); - let distinct: HashSet<_> = requests.iter().collect(); - assert_eq!(distinct.len(), 3, "the same request twice is one"); - } - #[test] fn waiting_returns_as_soon_as_an_event_arrives() { let repo = repo(); diff --git a/apps/origin-src/src/oplog.rs b/apps/origin-src/src/oplog.rs index 8320036f..1e75f90c 100644 --- a/apps/origin-src/src/oplog.rs +++ b/apps/origin-src/src/oplog.rs @@ -78,12 +78,12 @@ use std::sync::{Arc, OnceLock}; use std::{fmt, iter}; use origin_platform::{DurableWrite, LockMode, LockedFile, Platform}; +use origin_shared::landing::Proposal; use origin_shared::object::{DecodeError, Reader}; use origin_shared::{AcceptanceId, ChangeId, ObjectId, RevisionId, TargetName}; use crate::frames::{Frames, Tail, Writer}; use crate::index; -use crate::queue::Proposal; use crate::store::{Store, StoreError}; /// Who a store writes for, as the op log records it: a command, and the diff --git a/apps/origin-src/src/queue/mod.rs b/apps/origin-src/src/queue/mod.rs index ac78672c..4096137c 100644 --- a/apps/origin-src/src/queue/mod.rs +++ b/apps/origin-src/src/queue/mod.rs @@ -44,25 +44,23 @@ mod pending; mod session; -use std::fmt; use std::fs; use std::io; use std::path::PathBuf; use origin_platform::{DurableWrite, LockMode, LockedFile, Native, Platform}; -use origin_shared::policy::Requirement; +use origin_shared::landing::{Blocked, Landing, Pending, Proposal}; use origin_shared::{ - AcceptanceBody, AcceptanceId, ChangeId, EncodedObject, NodeKey, Principal, PrincipalName, - Record, RecordId, RepoPath, RevisionId, Source, StatementId, TargetId, TargetName, Tree, - TreeId, + AcceptanceBody, AcceptanceId, ChangeId, EncodedObject, Head, NodeKey, Principal, PrincipalName, + Record, RecordId, RepoPath, RevisionId, Source, TargetId, TargetName, Tree, TreeId, }; use crate::annotations::{AnnotateError, Annotations}; use crate::conflict::Conflicts; use crate::policy::{Policy, PolicyError}; use crate::store::{Store, StoreError}; -use crate::targets::Head; +use pending::PendingFile; use session::{Candidate, Session}; /// The landing queues of a store's targets, as run by one node. @@ -73,63 +71,6 @@ pub struct Queue<'a, P = Native> { node: PrincipalName, } -/// What a landing lands. -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum Proposal { - /// A change, as of its head. - Change(ChangeId), - /// Another target, as of its tip. - Target(TargetName), -} - -/// How a landing went. -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum Landing { - /// It landed. - Landed { - /// What landed. - proposal: Proposal, - /// The revision or acceptance the acceptance names. - source: Source, - /// The acceptance. - acceptance: Head, - }, - /// The target already has it, so nothing landed. - Unchanged(Proposal), - /// It waits, and the queue keeps it. - Pending(Pending), -} - -/// A landing that waits, kept in the queue to be listed and retried. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct Pending { - /// The target it lands on. - pub onto: TargetName, - /// What lands. - pub proposal: Proposal, - /// What the evidence must be about: the revision that would land, or - /// the merged snapshot of a target. A conflict is about the revision, - /// or the acceptance, that didn't merge. - pub subject: RecordId, - /// Why it waits. - pub blocked: Blocked, -} - -/// Why a landing waits. -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum Blocked { - /// The target requires these statements about the subject. - Evidence(Vec), - /// Both sides changed these paths. The `core.conflict` statement lists - /// them too. - Conflict { - /// The statement. - statement: StatementId, - /// The paths, sorted. - paths: Vec, - }, -} - impl<'a, P: Platform> Queue<'a, P> { /// The queues of `store`, run by the node `node`, which signs with /// `key`. @@ -329,8 +270,8 @@ impl<'a, P: Platform> Queue<'a, P> { Err(error) if error.kind() == io::ErrorKind::NotFound => continue, Err(source) => return Err(StoreError::io(&path, source)), }; - let mut landing = - Pending::decode(&text).ok_or_else(|| StoreError::Malformed(path.clone()))?; + let mut landing = PendingFile::decode(&text) + .ok_or_else(|| StoreError::Malformed(path.clone()))?; if let Blocked::Conflict { statement, paths } = &mut landing.blocked { *paths = Conflicts::listed(store, &store.get(*statement)?)?.paths(); } @@ -429,15 +370,6 @@ impl<'a, P: Platform> Queue<'a, P> { } } -impl fmt::Display for Proposal { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Change(change) => write!(f, "change {}", change.short()), - Self::Target(target) => write!(f, "`{target}`"), - } - } -} - /// A failure to land. #[derive(Debug, thiserror::Error)] pub enum LandError { diff --git a/apps/origin-src/src/queue/pending.rs b/apps/origin-src/src/queue/pending.rs index e6554939..cf239fcf 100644 --- a/apps/origin-src/src/queue/pending.rs +++ b/apps/origin-src/src/queue/pending.rs @@ -2,11 +2,13 @@ //! until it can continue. use origin_shared::RecordId; +use origin_shared::landing::{Blocked, Pending, Proposal}; use origin_shared::policy::Requirement; -use super::{Blocked, Pending, Proposal}; +/// The format of the files keeping waiting landings. +pub(super) struct PendingFile; -impl Pending { +impl PendingFile { /// The first line of every file keeping a waiting landing. const HEADER: &str = "origin pending 1"; @@ -14,20 +16,20 @@ impl Pending { /// ` or `target `, `subject `, then a `missing /// ` line for each requirement it lacks, or /// `conflict `, whose payload lists the paths. - pub(super) fn encode(&self) -> String { - let mut lines = vec![Self::HEADER.to_owned(), format!("onto {}", self.onto)]; - lines.push(match &self.proposal { + pub(super) fn encode(pending: &Pending) -> String { + let mut lines = vec![Self::HEADER.to_owned(), format!("onto {}", pending.onto)]; + lines.push(match &pending.proposal { Proposal::Change(change) => format!("change {change}"), Proposal::Target(target) => format!("target {target}"), }); - let (kind, id) = match self.subject { + let (kind, id) = match pending.subject { RecordId::Snapshot(id) => ("snapshot", id.to_hex()), RecordId::Revision(id) => ("revision", id.to_hex()), RecordId::Statement(id) => ("statement", id.to_hex()), RecordId::Acceptance(id) => ("acceptance", id.to_hex()), }; lines.push(format!("subject {kind} {id}")); - match &self.blocked { + match &pending.blocked { Blocked::Evidence(missing) => lines.extend(missing.iter().map(|requirement| { format!( "missing {} {} {}", @@ -39,9 +41,9 @@ impl Pending { lines.join("\n") + "\n" } - /// Decodes what [`Pending::encode`] wrote, without the conflicting + /// Decodes what [`PendingFile::encode`] wrote, without the conflicting /// paths, or `None` if it's malformed. - pub(super) fn decode(text: &str) -> Option { + pub(super) fn decode(text: &str) -> Option { let mut lines = text.lines(); if lines.next()? != Self::HEADER { return None; @@ -82,7 +84,7 @@ impl Pending { }, None => Blocked::Evidence(missing), }; - Some(Self { + Some(Pending { onto, proposal, subject, diff --git a/apps/origin-src/src/queue/session.rs b/apps/origin-src/src/queue/session.rs index aad88580..fe00f97e 100644 --- a/apps/origin-src/src/queue/session.rs +++ b/apps/origin-src/src/queue/session.rs @@ -8,10 +8,11 @@ use std::io; use std::path::PathBuf; use origin_platform::{LockedFile, Platform}; +use origin_shared::landing::{Blocked, Landing, Pending, Proposal}; use origin_shared::policy::Requirement; use origin_shared::{ - AcceptanceBody, AcceptanceId, Base, ChangeId, EncodedObject, Kind, Record, RecordId, Revision, - RevisionId, Source, StatementId, TargetName, TreeId, + AcceptanceBody, AcceptanceId, Base, ChangeId, EncodedObject, Head, Kind, Record, RecordId, + Revision, RevisionId, Source, StatementId, TargetName, TreeId, }; use crate::ancestry::Ancestry; @@ -20,9 +21,9 @@ use crate::conflict::Conflicts; use crate::oplog::Effect; use crate::policy::{Policy, PolicyError}; use crate::store::{Store, StoreError}; -use crate::targets::Head; -use super::{Blocked, LandError, Landing, Pending, Proposal, Queue}; +use super::pending::PendingFile; +use super::{LandError, Queue}; /// Landings onto one target, holding its queue's lock. pub(super) struct Session<'q, 'a, P> { @@ -328,7 +329,7 @@ impl Session<'_, '_, P> { let write = self.store().durable_write(); write.stage( self.pending_path(&pending.proposal)?, - pending.encode().as_bytes(), + PendingFile::encode(pending).as_bytes(), )?; let waiting = Effect::Waiting { onto: pending.onto.clone(), diff --git a/apps/origin-src/src/queue/tests/changes.rs b/apps/origin-src/src/queue/tests/changes.rs index a42cf7c4..608773b6 100644 --- a/apps/origin-src/src/queue/tests/changes.rs +++ b/apps/origin-src/src/queue/tests/changes.rs @@ -159,7 +159,10 @@ fn pending_landings_round_trip() { issuer: "group:runners".parse().unwrap(), }]), }; - assert_eq!(Pending::decode(&pending.encode()), Some(pending.clone())); + assert_eq!( + PendingFile::decode(&PendingFile::encode(&pending)), + Some(pending.clone()) + ); let conflict = Pending { proposal: change(9), blocked: Blocked::Conflict { @@ -168,8 +171,11 @@ fn pending_landings_round_trip() { }, ..pending }; - assert_eq!(Pending::decode(&conflict.encode()), Some(conflict)); - assert_eq!(Pending::decode("origin pending 2\n"), None); + assert_eq!( + PendingFile::decode(&PendingFile::encode(&conflict)), + Some(conflict) + ); + assert_eq!(PendingFile::decode("origin pending 2\n"), None); } #[test] diff --git a/apps/origin-src/src/queue/tests/mod.rs b/apps/origin-src/src/queue/tests/mod.rs index e1d15705..81095f8d 100644 --- a/apps/origin-src/src/queue/tests/mod.rs +++ b/apps/origin-src/src/queue/tests/mod.rs @@ -7,9 +7,10 @@ mod policy; mod targets; use origin_platform::Native; +use origin_shared::landing::{Blocked, Landing, Pending, Proposal}; use origin_shared::policy::Requirement; use origin_shared::{ - AcceptanceBody, Base, BlobId, ChangeId, Digest, EncodedObject, Inputs, Kind, NodeKey, + AcceptanceBody, Base, BlobId, ChangeId, Digest, EncodedObject, Head, Inputs, Kind, NodeKey, PrincipalName, Record, RecordId, RepoPath, Revision, RevisionId, Source, Statement, StatementId, TargetName, Tree, TreeId, Verdict, }; @@ -19,7 +20,6 @@ use crate::annotations::Annotations; use crate::conflict::Conflicts; use crate::policy::{Policy, PolicyError}; use crate::store::Store; -use crate::targets::Head; use crate::tree::tests::build; /// A repository whose `policy` and `main` the node `queue` orders, with diff --git a/apps/origin-src/src/store/mod.rs b/apps/origin-src/src/store/mod.rs index 4190dd50..2c8c34d1 100644 --- a/apps/origin-src/src/store/mod.rs +++ b/apps/origin-src/src/store/mod.rs @@ -36,11 +36,11 @@ use std::time::{Duration, SystemTime}; use origin_platform::{DurableWrite, LockMode, LockedFile, Native, Platform, WritableError}; use origin_shared::object::{DecodeError, IdMismatch}; -use origin_shared::{EncodedObject, ObjectId, TargetName, TypedId}; +use origin_shared::{EncodedObject, Head, ObjectId, TargetName, TypedId}; use crate::index::Entry; use crate::oplog::{Actor, Effect}; -use crate::targets::Head; +use crate::targets; pub use packs::Compaction; use packs::Packs; @@ -646,7 +646,7 @@ pub enum StoreError { /// got there first. #[error( "target `{target}` moved: expected acceptance {expected} to follow {}", - Head::describe(*actual) + targets::describe(*actual) )] Conflict { /// The target. diff --git a/apps/origin-src/src/targets.rs b/apps/origin-src/src/targets.rs index cbf17a8c..072247bd 100644 --- a/apps/origin-src/src/targets.rs +++ b/apps/origin-src/src/targets.rs @@ -17,7 +17,6 @@ //! log ahead of the head, or a partial line at its end, the next append //! repairs it first, syncing the log before publishing what it holds. -use std::fmt; use std::fs::{self, File}; use std::io::{self, Read, Seek, SeekFrom, Write}; use std::os::unix::fs::FileExt; @@ -26,40 +25,16 @@ use std::slice; use origin_platform::{DurableWrite, LockMode, LockedFile, Platform}; use origin_shared::{ - Acceptance, AcceptanceId, Base, Record, Revision, RevisionId, Source, TargetId, TargetName, + Acceptance, AcceptanceId, Base, Head, Record, Revision, RevisionId, Source, TargetId, + TargetName, }; use crate::oplog::Effect; use crate::store::{Store, StoreError}; -/// The latest acceptance of a target. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct Head { - /// Its position in the log, from 0. - pub seq: u64, - /// The acceptance. - pub acceptance: AcceptanceId, -} - -impl Head { - /// Describes where a target is, for error messages. - pub(crate) fn describe(head: Option) -> String { - head.map_or_else(|| "nothing".to_owned(), |head| head.to_string()) - } - - fn parse(line: &str) -> Option { - let (seq, acceptance) = line.strip_suffix('\n')?.split_once(' ')?; - Some(Self { - seq: seq.parse().ok()?, - acceptance: acceptance.parse().ok()?, - }) - } -} - -impl fmt::Display for Head { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "acceptance {} ({})", self.seq, self.acceptance.short()) - } +/// Describes where a target is, for error messages. +pub(crate) fn describe(head: Option) -> String { + head.map_or_else(|| "nothing".to_owned(), |head| head.to_string()) } /// The files of one target. @@ -100,11 +75,20 @@ impl TargetFiles { }; str::from_utf8(&bytes) .ok() - .and_then(Head::parse) + .and_then(Self::parse_head) .map(Some) .ok_or(StoreError::Malformed(path)) } + /// Parses `head`'s ` ` line. + fn parse_head(line: &str) -> Option { + let (seq, acceptance) = line.strip_suffix('\n')?.split_once(' ')?; + Some(Head { + seq: seq.parse().ok()?, + acceptance: acceptance.parse().ok()?, + }) + } + /// Parses the complete lines of a log, ignoring a partial last one. fn parse_log(&self, bytes: &[u8]) -> Result, StoreError> { bytes diff --git a/apps/origin-src/src/workspace/land.rs b/apps/origin-src/src/workspace/land.rs index d39a1adc..2d17dbbf 100644 --- a/apps/origin-src/src/workspace/land.rs +++ b/apps/origin-src/src/workspace/land.rs @@ -16,6 +16,7 @@ //! the working copy doesn't land until they change or are accepted with //! `origin resolve` (see [`conflict`](crate::conflict)). +use origin_shared::landing::{Blocked, Landing, Pending, Proposal}; use origin_shared::{ Base, ChangeId, EncodedObject, Record, Revision, RevisionId, Source, TargetName, TreeId, }; @@ -25,7 +26,7 @@ use crate::conflict::Conflicts; use crate::index::Index; use crate::oplog::Why; use crate::policy::Policy; -use crate::queue::{Blocked, Landing, Pending, Proposal, Queue}; +use crate::queue::Queue; use crate::tree::Merge; impl Workspace { diff --git a/apps/origin-src/src/workspace/ops.rs b/apps/origin-src/src/workspace/ops.rs index d2e71fcb..95eaeed8 100644 --- a/apps/origin-src/src/workspace/ops.rs +++ b/apps/origin-src/src/workspace/ops.rs @@ -20,13 +20,14 @@ use std::collections::{BTreeMap, HashSet}; use std::time::Duration; +use origin_shared::event::Filter; +use origin_shared::landing::Proposal; use origin_shared::{Record, RecordId, Revision, RevisionId}; use super::{Workspace, WorkspaceError}; -use crate::events::{Events, Filter}; +use crate::events::Events; use crate::index; use crate::oplog::{Effect, Entry, Move, Why}; -use crate::queue::Proposal; impl Workspace { /// `origin op log [-n ]`: prints the latest operations of every diff --git a/crates/origin-shared/src/event.rs b/crates/origin-shared/src/event.rs new file mode 100644 index 00000000..e4b2f653 --- /dev/null +++ b/crates/origin-shared/src/event.rs @@ -0,0 +1,277 @@ +//! Events: what happened on a node, for plugins and agents to react to. +//! Each carries the cursor of the op log entry it comes from, and reading +//! the events after a cursor returns a [`Page`] and the next cursor. Events +//! are delivered at least once, so consumers deduplicate by the +//! [`EventKind`], all of an event but its cursor: two check requests about +//! one record differ by target or requirement. + +use std::fmt; + +use crate::policy::{KindPattern, Requirement}; +use crate::{ + AcceptanceId, ChangeId, Kind, Principal, RecordId, RevisionId, StatementId, TargetName, Verdict, +}; + +/// Something that happened, and where it is in the op log. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Event { + /// The sequence number of the op log entry it comes from. Reading from + /// it delivers the events of the entries after it. + pub cursor: u64, + /// What happened. + pub kind: EventKind, +} + +/// What happened: an event's identity, which consumers deduplicate by. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum EventKind { + /// A statement was issued. + StatementIssued { + /// The statement. + statement: StatementId, + /// What it's about. + subject: RecordId, + /// Its kind. + kind: Kind, + /// Its verdict. + verdict: Option, + /// Who issued it. + issuer: Principal, + }, + /// A revision was created. + RevisionCreated { + /// The revision. + revision: RevisionId, + /// Its change. + change: ChangeId, + /// Who made it. + author: Principal, + }, + /// A target advanced. + TargetAdvanced { + /// The target. + target: TargetName, + /// The acceptance's position in its log. + seq: u64, + /// The acceptance. + acceptance: AcceptanceId, + }, + /// A landing waits for a statement it requires. + CheckRequested { + /// The target it lands on. + onto: TargetName, + /// What the statement must be about. + subject: RecordId, + /// The statement required. + requirement: Requirement, + }, +} + +/// What an event is about, which `--subject` matches. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Subject { + /// A record. + Record(RecordId), + /// A change: the subject of its revisions' events. + Change(ChangeId), + /// A target. + Target(TargetName), +} + +impl EventKind { + /// The event's name, such as `statement.issued`. + #[must_use] + pub fn name(&self) -> &'static str { + match self { + Self::StatementIssued { .. } => "statement.issued", + Self::RevisionCreated { .. } => "revision.created", + Self::TargetAdvanced { .. } => "target.advanced", + Self::CheckRequested { .. } => "check.requested", + } + } + + /// The record the event is about: the statement, revision or + /// acceptance, or for a check, the record to check. + #[must_use] + pub fn record(&self) -> RecordId { + match *self { + Self::StatementIssued { statement, .. } => RecordId::Statement(statement), + Self::RevisionCreated { revision, .. } => RecordId::Revision(revision), + Self::TargetAdvanced { acceptance, .. } => RecordId::Acceptance(acceptance), + Self::CheckRequested { subject, .. } => subject, + } + } + + /// What the event is about: a statement's or a check's subject, a + /// revision's change, or the target that advanced. + #[must_use] + pub fn subject(&self) -> Subject { + match self { + Self::StatementIssued { subject, .. } | Self::CheckRequested { subject, .. } => { + Subject::Record(*subject) + } + Self::RevisionCreated { change, .. } => Subject::Change(*change), + Self::TargetAdvanced { target, .. } => Subject::Target(target.clone()), + } + } + + /// What a [`Filter`] matches the event's subject by: its + /// [subject](Self::subject), and for a revision created, the revision + /// too. + #[must_use] + pub fn subjects(&self) -> Vec { + let subject = self.subject(); + match *self { + Self::RevisionCreated { revision, .. } => { + vec![subject, Subject::Record(RecordId::Revision(revision))] + } + _ => vec![subject], + } + } + + /// The kinds a [`Filter`] matches the event by: its name, and the kind + /// of the statement issued or requested. + /// + /// # Panics + /// + /// Never: event names are valid kinds. + #[must_use] + pub fn kinds(&self) -> Vec { + let name = Kind::new(self.name()).expect("event names are valid kinds"); + match self { + Self::StatementIssued { kind, .. } => vec![name, kind.clone()], + Self::CheckRequested { requirement, .. } => vec![name, requirement.kind.clone()], + Self::RevisionCreated { .. } | Self::TargetAdvanced { .. } => vec![name], + } + } +} + +impl fmt::Display for Subject { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Record(record) => record.fmt(f), + Self::Change(id) => write!(f, "change:{id}"), + Self::Target(name) => write!(f, "target:{name}"), + } + } +} + +/// One line: the cursor, the name, then `key=value` fields with full ids. +impl fmt::Display for Event { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{} {}", self.cursor, self.kind.name())?; + let verdict = |verdict: &Option| { + verdict.map_or_else(|| "none".to_owned(), |verdict| verdict.to_string()) + }; + match &self.kind { + EventKind::StatementIssued { + statement, + subject, + kind, + verdict: issued, + issuer, + } => write!( + f, + " statement={statement} subject={} kind={kind} verdict={} issuer={issuer}", + Subject::Record(*subject), + verdict(issued) + ), + EventKind::RevisionCreated { + revision, + change, + author, + } => write!(f, " revision={revision} change={change} author={author}"), + EventKind::TargetAdvanced { + target, + seq, + acceptance, + } => write!(f, " target={target} seq={seq} acceptance={acceptance}"), + EventKind::CheckRequested { + onto, + subject, + requirement, + } => write!( + f, + " onto={onto} subject={} kind={} verdict={} issuer={}", + Subject::Record(*subject), + requirement.kind, + requirement.verdict, + requirement.issuer + ), + } + } +} + +/// Which events to deliver. An empty list matches everything. +#[derive(Clone, Debug, Default)] +pub struct Filter { + /// Event names or statement kinds, such as `check.requested`, + /// `core.conflict` or `ci.*`: an event matches one if its name, or the + /// kind it issues or requests, does. + pub kinds: Vec, + /// Starts of subjects, such as a revision id prefix, `change:3fa2` or + /// `main`: an event matches one if its [subject](EventKind::subject), + /// or a revision's creation its revision, written as `revision:`, + /// or its id or name alone, starts with it. + pub subjects: Vec, +} + +impl Filter { + /// Whether `event` passes the filter. + #[must_use] + pub fn matches(&self, event: &EventKind) -> bool { + let kind = self.kinds.is_empty() + || event + .kinds() + .iter() + .any(|kind| self.kinds.iter().any(|pattern| pattern.matches(kind))); + kind && (self.subjects.is_empty() + || event.subjects().iter().any(|subject| { + let subject = subject.to_string(); + let bare = subject.split_once(':').map_or("", |(_, bare)| bare); + self.subjects.iter().any(|start| { + subject.starts_with(start.as_str()) || bare.starts_with(start.as_str()) + }) + })) + } +} + +/// A batch of events, and the cursor to read the next batch from. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Page { + /// The events, oldest first. + pub events: Vec, + /// The cursor after the entries read: pass it to the next read. + pub next: u64, +} + +#[cfg(test)] +mod tests { + use std::collections::HashSet; + + use super::*; + use crate::EncodedObject; + + #[test] + fn check_requests_about_one_record_are_told_apart() { + let subject = RecordId::Revision(EncodedObject::blob(b"a revision").id().into()); + let request = |onto: &str, kind: &str| EventKind::CheckRequested { + onto: TargetName::new(onto).unwrap(), + subject, + requirement: Requirement { + kind: Kind::new(kind).unwrap(), + verdict: Verdict::Pass, + issuer: "group:runners".parse().unwrap(), + }, + }; + let requests = [ + request("main", "ci.test"), + request("main", "ci.lint"), + request("release", "ci.test"), + request("main", "ci.test"), + ]; + assert!(requests.iter().all(|request| request.record() == subject)); + let distinct: HashSet<_> = requests.iter().collect(); + assert_eq!(distinct.len(), 3, "the same request twice is one"); + } +} diff --git a/crates/origin-shared/src/landing.rs b/crates/origin-shared/src/landing.rs new file mode 100644 index 00000000..65b9ef06 --- /dev/null +++ b/crates/origin-shared/src/landing.rs @@ -0,0 +1,72 @@ +//! Landings: what a target's queue is asked to land, and how it went. + +use std::fmt; + +use crate::policy::Requirement; +use crate::{ChangeId, Head, RecordId, RepoPath, Source, StatementId, TargetName}; + +/// What a landing lands. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Proposal { + /// A change, as of its head. + Change(ChangeId), + /// Another target, as of its tip. + Target(TargetName), +} + +/// How a landing went. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Landing { + /// It landed. + Landed { + /// What landed. + proposal: Proposal, + /// The revision or acceptance the acceptance names. + source: Source, + /// The acceptance. + acceptance: Head, + }, + /// The target already has it, so nothing landed. + Unchanged(Proposal), + /// It waits, and the queue keeps it. + Pending(Pending), +} + +/// A landing that waits, kept in the queue to be listed and retried. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Pending { + /// The target it lands on. + pub onto: TargetName, + /// What lands. + pub proposal: Proposal, + /// What the evidence must be about: the revision that would land, or + /// the merged snapshot of a target. A conflict is about the revision, + /// or the acceptance, that didn't merge. + pub subject: RecordId, + /// Why it waits. + pub blocked: Blocked, +} + +/// Why a landing waits. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Blocked { + /// The target requires these statements about the subject. + Evidence(Vec), + /// Both sides changed these paths. The `core.conflict` statement lists + /// them too. + Conflict { + /// The statement. + statement: StatementId, + /// The paths, sorted. + paths: Vec, + }, +} + +impl fmt::Display for Proposal { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Change(change) => write!(f, "change {}", change.short()), + Self::Target(target) => write!(f, "`{target}`"), + } + } +} diff --git a/crates/origin-shared/src/lib.rs b/crates/origin-shared/src/lib.rs index b26a12cc..d310c2c1 100644 --- a/crates/origin-shared/src/lib.rs +++ b/crates/origin-shared/src/lib.rs @@ -1,7 +1,9 @@ //! Types shared by every origin component: the object model, the wire //! formats, and the API contracts. +pub mod event; mod id; +pub mod landing; mod name; pub mod object; mod path; @@ -22,5 +24,5 @@ pub use object::{ }; pub use path::RepoPath; pub use principal::{Principal, PrincipalName}; -pub use target::TargetName; +pub use target::{Head, TargetName}; pub use text::{InvalidPeriod, Period}; diff --git a/crates/origin-shared/src/object/statement.rs b/crates/origin-shared/src/object/statement.rs index de1afbcf..b7f12907 100644 --- a/crates/origin-shared/src/object/statement.rs +++ b/crates/origin-shared/src/object/statement.rs @@ -6,8 +6,8 @@ use std::str::FromStr; use super::{DecodeError, Field, ObjectKind, Reader, Record, fields, tagged}; use crate::name::names; use crate::{ - AcceptanceId, BlobId, Digest, InvalidName, ObjectId, Principal, RepoPath, RevisionId, - StatementId, TreeEntry, TreeId, + AcceptanceId, BlobId, Digest, InvalidName, ObjectId, ParseIdError, Principal, RepoPath, + RevisionId, StatementId, TreeEntry, TreeId, }; /// An attributable claim about another record: a check result, a review, a @@ -173,6 +173,41 @@ impl From for ObjectId { } } +/// `revision:`: the record's kind, then its full id. A snapshot is +/// `snapshot:`. +impl fmt::Display for RecordId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let kind = match self { + Self::Snapshot(_) => "snapshot", + Self::Revision(_) => "revision", + Self::Statement(_) => "statement", + Self::Acceptance(_) => "acceptance", + }; + write!(f, "{kind}:{}", ObjectId::from(*self)) + } +} + +/// Parses what [`RecordId`] displays as. +impl FromStr for RecordId { + type Err = ParseIdError; + + fn from_str(input: &str) -> Result { + let invalid = || ParseIdError { + what: "record", + input: input.to_owned(), + }; + let (kind, id) = input.split_once(':').ok_or_else(invalid)?; + let id: ObjectId = id.parse().map_err(|_| invalid())?; + Ok(match kind { + "snapshot" => Self::Snapshot(id.into()), + "revision" => Self::Revision(id.into()), + "statement" => Self::Statement(id.into()), + "acceptance" => Self::Acceptance(id.into()), + _ => return Err(invalid()), + }) + } +} + // The tags are the records' object kinds. tagged!(RecordId { Snapshot = 2, diff --git a/crates/origin-shared/src/target.rs b/crates/origin-shared/src/target.rs index 3b444e97..862ae788 100644 --- a/crates/origin-shared/src/target.rs +++ b/crates/origin-shared/src/target.rs @@ -1,9 +1,10 @@ -//! Target names. +//! Target names, and where a target is. use std::borrow::Cow; +use std::fmt; -use crate::TargetId; use crate::name::names; +use crate::{AcceptanceId, TargetId}; names! { /// The name of a target, such as `main` or `release/v3`: `/`-separated @@ -39,6 +40,21 @@ impl TargetName { } } +/// The latest acceptance of a target. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Head { + /// Its position in the log, from 0. + pub seq: u64, + /// The acceptance. + pub acceptance: AcceptanceId, +} + +impl fmt::Display for Head { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "acceptance {} ({})", self.seq, self.acceptance.short()) + } +} + #[cfg(test)] mod tests { use super::*;