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
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<repo>/events?cursor=<n>&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.
Expand Down
7 changes: 5 additions & 2 deletions apps/origin-src/src/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)?;
Expand Down Expand Up @@ -457,7 +458,8 @@ mod tests {
held,
Page {
events: Vec::new(),
next: crashed - 1
next: crashed - 1,
..Page::default()
},
"it may be in progress"
);
Expand Down Expand Up @@ -520,7 +522,8 @@ mod tests {
empty,
Page {
events: Vec::new(),
next: end
next: end,
..Page::default()
}
);
thread::scope(|scope| {
Expand Down
5 changes: 5 additions & 0 deletions apps/origin-src/src/index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,11 @@ impl Index {
&self.arrivals
}

/// Every change with a revision, in no particular order.
pub fn changes(&self) -> impl Iterator<Item = ChangeId> {
self.changes.keys().copied()
}

/// The revisions of `change`, in arrival order.
#[must_use]
pub fn revisions(&self, change: ChangeId) -> &[RevisionId] {
Expand Down
50 changes: 46 additions & 4 deletions apps/origin-src/src/oplog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
//!
//! ```text
//! .origin/oplog/
//! generation a random id, made with the log
//! lock held exclusively while appending
//! writers/<n> held by each writer while it writes
//! <first sequence number> segments of entries, 16 hex digits each
Expand All @@ -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
Expand Down Expand Up @@ -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<LockedFile, StoreError> {
/// 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<String, StoreError> {
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<LockedFile, StoreError> {
self.create_dir()?;
let dir = self.dir();
Ok(LockedFile::open(
&self.store.platform,
&dir.join(name),
Expand Down
16 changes: 14 additions & 2 deletions apps/origin-src/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Page, ServiceError> {
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,
Expand All @@ -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 })
}
}

Expand Down Expand Up @@ -873,6 +881,9 @@ pub enum ServiceError {
/// Its heads now.
heads: Vec<origin_shared::RevisionId>,
},
/// 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())]
Expand Down Expand Up @@ -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(_)
Expand Down
3 changes: 3 additions & 0 deletions apps/origin-src/src/store/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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}")]
Expand Down
Loading