Skip to content
Merged
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
9 changes: 1 addition & 8 deletions apps/origin-src/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ 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};

Expand Down Expand Up @@ -498,13 +497,7 @@ impl WorkspaceCommand {
kind,
subject,
since,
} => workspace.watch(
&Filter {
kinds: kind,
subjects: subject,
},
since,
)?,
} => workspace.watch(kind, subject, since)?,
}
Ok(())
}
Expand Down
62 changes: 58 additions & 4 deletions apps/origin-src/src/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ use origin_platform::{Native, Platform};
use origin_shared::event::{Event, EventKind, Filter, Page};
use origin_shared::landing::{Blocked, Pending};
use origin_shared::{Object, ObjectId};
use parking_lot::{Condvar, Mutex};

use crate::index;
use crate::oplog::{Effect, Entry};
Expand All @@ -42,6 +43,39 @@ use crate::store::{Store, StoreError};
#[derive(Debug)]
pub struct Events<'a, P = Native> {
store: &'a Store<P>,
/// Wakes [`Events::wait`] as soon as this process writes, if set.
/// Otherwise it only polls.
wakeup: Option<&'a Wakeup>,
}

/// Wakes the readers in this process that wait for events as soon as the
/// process writes, instead of at their next poll of the op log. Writes from
/// other processes are still seen only at the next poll.
#[derive(Debug, Default)]
pub struct Wakeup {
/// How many writes this process has made.
writes: Mutex<u64>,
written: Condvar,
}

impl Wakeup {
/// Wakes every waiting reader. Call it after this process writes.
pub fn notify(&self) {
*self.writes.lock() += 1;
self.written.notify_all();
}

/// How many writes this process has made so far.
fn writes(&self) -> u64 {
*self.writes.lock()
}

/// Waits up to `timeout`, or until the write count is no longer `seen`.
fn sleep(&self, seen: u64, timeout: Duration) {
let mut writes = self.writes.lock();
self.written
.wait_while_for(&mut writes, |writes| *writes == seen, timeout);
}
}

impl<'a, P: Platform> Events<'a, P> {
Expand All @@ -50,7 +84,19 @@ impl<'a, P: Platform> Events<'a, P> {

/// Creates a reader of the events of `store`.
pub fn new(store: &'a Store<P>) -> Self {
Self { store }
Self {
store,
wakeup: None,
}
}

/// Returns these events with [`Events::wait`] also woken by `wakeup`.
#[must_use]
pub fn waking_on(self, wakeup: &'a Wakeup) -> Self {
Self {
wakeup: Some(wakeup),
..self
}
}

/// Returns the cursor after every event so far. Reading from it delivers
Expand Down Expand Up @@ -100,8 +146,10 @@ impl<'a, P: Platform> Events<'a, P> {
Ok(page)
}

/// Like [`Events::after`], but waits up to `timeout` for events, reading
/// the op log every [`Events::POLL`]. Returns an empty page if none came.
/// Like [`Events::after`], but waits up to `timeout` for events. It reads
/// the op log every [`Events::POLL`], and also as soon as the [`Wakeup`],
/// if any, reports a write by this process. Returns an empty page if none
/// came.
///
/// # Errors
///
Expand All @@ -116,14 +164,20 @@ impl<'a, P: Platform> Events<'a, P> {
let start = Instant::now();
let mut cursor = cursor;
loop {
// Read before the op log, so no write after it is missed.
let seen = self.wakeup.map(Wakeup::writes);
let page = self.after(cursor, filter, limit)?;
let left = timeout.saturating_sub(start.elapsed());
if !page.events.is_empty() || left.is_zero() {
return Ok(page);
}
// Entries with no matching events are read past.
cursor = page.next;
thread::sleep(Self::POLL.min(left));
let pause = Self::POLL.min(left);
match (self.wakeup, seen) {
(Some(wakeup), Some(seen)) => wakeup.sleep(seen, pause),
_ => thread::sleep(pause),
}
}
}

Expand Down
59 changes: 53 additions & 6 deletions apps/origin-src/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
//! Plugins use it in the same two ways.
//!
//! A service lives as long as its process. It keeps the record index open and
//! catches it up with the op log before each use. Calls don't wait for each
//! catches it up with the op log before each use, and wakes the event
//! long-polls waiting on it whenever it writes. Calls don't wait for each
//! other: each takes one of the open indexes, or opens a new one, up to
//! [`OriginService::MAX_INDEXES`]; past that, calls wait for one, since each
//! index holds everything in memory. Landings on one target still run one at a
Expand All @@ -17,12 +18,14 @@ use std::collections::hash_map::Entry;
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;

use origin_platform::Native;
use origin_shared::api::{
Annotation, ErrorCode, LandRequest, Landings, LogEntry, NewTarget, RevisionEntry, Revisions,
Stored, TargetInfo,
Annotation, ErrorCode, EventsQuery, 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;
Expand All @@ -33,6 +36,7 @@ use origin_shared::{
use parking_lot::{Condvar, Mutex, MutexGuard};

use crate::annotations::{AnnotateError, Annotations};
use crate::events::{Events, Wakeup};
use crate::index::Index;
use crate::policy::{Policy, PolicyError};
use crate::queue::{LandError, Queue};
Expand Down Expand Up @@ -72,9 +76,16 @@ pub struct OriginService {
node: Node,
/// The record indexes kept open for calls to use.
indexes: Indexes,
wakeup: Wakeup,
}

impl OriginService {
/// The most events a page holds, which is also the default.
const MAX_EVENTS: u32 = 1024;

/// The longest an event long-poll waits.
pub const MAX_WAIT: Duration = Duration::from_mins(1);

/// The most indexes open at once, in use or kept free for calls.
pub const MAX_INDEXES: usize = 8;

Expand All @@ -85,6 +96,7 @@ impl OriginService {
store,
node,
indexes: Indexes::default(),
wakeup: Wakeup::default(),
}
}

Expand Down Expand Up @@ -286,6 +298,7 @@ impl OriginService {
Ok(())
})?;
}
self.wakeup.notify();
Ok(Stored { new: new as u64 })
}

Expand Down Expand Up @@ -411,7 +424,7 @@ impl OriginService {
/// be read or written.
pub fn land(&self, _caller: &Caller, request: &LandRequest) -> Result<Landings, ServiceError> {
let queue = Queue::new(&self.store, &self.node.key, self.node.name.clone());
self.annotations(|annotations| {
let landed = self.annotations(|annotations| {
let landed = match &request.proposal {
Proposal::Change(change) => {
let onto = match &request.onto {
Expand All @@ -431,7 +444,11 @@ impl OriginService {
}
};
Ok(landed)
})
});
// Even a failed landing may have written records, such as a
// conflict.
self.wakeup.notify();
landed
}

/// Returns the target the stack of `change` is on: the target of the acceptance
Expand Down Expand Up @@ -484,7 +501,37 @@ impl OriginService {
request: &NewTarget,
) -> Result<Head, ServiceError> {
let queue = Queue::new(&self.store, &self.node.key, self.node.name.clone());
Ok(queue.create_target(&request.name, &request.from)?)
let head = queue.create_target(&request.name, &request.from)?;
self.wakeup.notify();
Ok(head)
}

/// Returns the events after the query's cursor that pass its filter. Waits up
/// to the query's `wait`, at most [`OriginService::MAX_WAIT`], for some to
/// arrive. Without a cursor, returns only events from now on.
///
/// # Errors
///
/// Fails if the op log no longer keeps the events after the cursor, or if the
/// op log or a record cannot be read.
pub fn events(&self, _caller: &Caller, query: &EventsQuery) -> Result<Page, ServiceError> {
let events = Events::new(&self.store).waking_on(&self.wakeup);
let cursor = match query.cursor {
Some(cursor) => cursor,
None => events.end()?,
};
let filter = Filter {
kinds: query.kind.0.clone(),
subjects: query.subject.0.clone(),
};
let limit = query
.limit
.unwrap_or(Self::MAX_EVENTS)
.min(Self::MAX_EVENTS) as usize;
let wait = query
.wait
.map_or(Duration::ZERO, origin_shared::Period::duration);
Ok(events.wait(cursor, &filter, limit, wait.min(Self::MAX_WAIT))?)
}
}

Expand Down
35 changes: 22 additions & 13 deletions apps/origin-src/src/workspace/ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,16 @@
//! doesn't diverge.

use std::collections::{BTreeMap, HashSet};
use std::time::Duration;

use origin_shared::event::Filter;
use origin_shared::api::{EventsQuery, List};
use origin_shared::landing::Proposal;
use origin_shared::{Record, RecordId, Revision, RevisionId};
use origin_shared::policy::KindPattern;
use origin_shared::{Period, Record, RecordId, Revision, RevisionId};

use super::{Workspace, WorkspaceError};
use crate::events::Events;
use crate::index;
use crate::oplog::{Effect, Entry, Move, Why};
use crate::service::{Caller, OriginService};

impl Workspace {
/// `origin op log [-n <limit>]`: prints the latest operations of every
Expand Down Expand Up @@ -205,24 +205,33 @@ impl Workspace {
}

/// `origin watch [--kind <kind>]... [--subject <subject>]... [--since
/// <cursor>]`: prints the events that pass `filter` as they happen, one per
/// line, from `since`, or from now. Runs until interrupted.
/// <cursor>]`: prints the events of those kinds about those subjects as they
/// happen, one per line, from `since`, or from now. Without kinds or subjects,
/// prints every event. Runs until interrupted.
///
/// # Errors
///
/// Fails if the cursor expired, or the op log or a record cannot be read.
pub fn watch(&self, filter: &Filter, since: Option<u64>) -> Result<(), WorkspaceError> {
let events = Events::new(&self.store);
let mut cursor = match since {
Some(since) => since,
None => events.end()?,
pub fn watch(
&self,
kinds: Vec<KindPattern>,
subjects: Vec<String>,
since: Option<u64>,
) -> Result<(), WorkspaceError> {
let service = self.service(None)?;
let mut query = EventsQuery {
cursor: since,
wait: Some(Period::from_secs(OriginService::MAX_WAIT.as_secs())),
limit: Some(256),
kind: List(kinds),
subject: List(subjects),
};
loop {
let page = events.wait(cursor, filter, 256, Duration::from_secs(60))?;
let page = service.events(&Caller::Owner, &query)?;
for event in &page.events {
println!("{event}");
}
cursor = page.next;
query.cursor = Some(page.next);
}
}
}
Loading