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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion apps/origin-src/benches/land.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
3 changes: 2 additions & 1 deletion apps/origin-src/benches/store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
2 changes: 1 addition & 1 deletion apps/origin-src/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};

Expand Down
269 changes: 7 additions & 262 deletions apps/origin-src/src/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Verdict>,
/// 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<Subject> {
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<Kind> {
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>| {
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<KindPattern>,
/// 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:<id>`,
/// or its id or name alone, starts with it.
pub subjects: Vec<String>,
}

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<Event>,
/// 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> {
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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!(
Expand All @@ -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();
Expand Down
2 changes: 1 addition & 1 deletion apps/origin-src/src/oplog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading