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
13 changes: 8 additions & 5 deletions apps/origin-ci/benches/worker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ use std::cell::RefCell;
use std::path::PathBuf;
use std::process::Command;
use std::sync::Arc;
use std::time::Duration;

use divan::Bencher;
use origin_ci::runner::{Outcome, Runner};
Expand All @@ -20,8 +19,8 @@ use origin_shared::api::{At, LandRequest};
use origin_shared::landing::{Landing, Proposal};
use origin_shared::pack::Pack;
use origin_shared::{
AttachmentId, Base, ChangeId, EncodedObject, EntryKind, EntryName, Kind, NodeKey, Principal,
Record, RecordId, Revision, RevisionId, TargetName, Tree, TreeEntry,
AttachmentId, Base, ChangeId, EncodedObject, EntryKind, EntryName, Kind, NodeKey, Period,
Principal, Record, RecordId, Revision, RevisionId, TargetName, Tree, TreeEntry,
};
use origin_src::auth::{Credentials, StaticTokens};
use origin_src::http::Api;
Expand Down Expand Up @@ -100,7 +99,7 @@ impl Hosted {
let outcomes = hosted.runner.check(first, &At::Record(first), None);
assert!(matches!(outcomes.unwrap()[..], [Outcome::Ran { .. }]));
// Takes the cursor.
hosted.worker.poll(Duration::ZERO).unwrap();
hosted.worker.poll(Period::from_secs(0)).unwrap();
hosted
}

Expand Down Expand Up @@ -186,7 +185,11 @@ fn check_requested_to_statement(bencher: Bencher) {
hosted.borrow_mut().submit();
})
.bench_local_values(|()| {
let answers = hosted.borrow_mut().worker.poll(Duration::ZERO).unwrap();
let answers = hosted
.borrow_mut()
.worker
.poll(Period::from_secs(0))
.unwrap();
assert!(matches!(&answers[..], [answer] if answer.result.is_ok()));
});
}
Expand Down
10 changes: 5 additions & 5 deletions apps/origin-ci/src/worker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ pub struct Worker {

impl Worker {
/// How long each long-poll waits.
pub const WAIT: Duration = Duration::from_secs(30);
pub const WAIT: Period = Period::from_secs(30);

/// How often the worker answers every landing that waits, whatever the
/// events said.
Expand Down Expand Up @@ -120,7 +120,7 @@ impl Worker {
/// # Errors
///
/// Fails like [`Worker::poll`], but for a remote that can't be reached.
pub fn next(&mut self, wait: Duration) -> Result<Vec<Answer>, WorkerError> {
pub fn next(&mut self, wait: Period) -> Result<Vec<Answer>, WorkerError> {
let mut retry = Self::FIRST_RETRY;
loop {
match self.poll(wait) {
Expand All @@ -145,7 +145,7 @@ impl Worker {
/// # Errors
///
/// Fails if the remote cannot be reached or refuses.
pub fn poll(&mut self, wait: Duration) -> Result<Vec<Answer>, WorkerError> {
pub fn poll(&mut self, wait: Period) -> Result<Vec<Answer>, WorkerError> {
let cursor = match self.cursor {
Some(cursor) if self.reconciled.elapsed() < Self::RECONCILE => cursor,
_ => return self.reconcile(),
Expand Down Expand Up @@ -220,10 +220,10 @@ impl Worker {

/// The `check.requested` events after `cursor`, or from now, waiting up
/// to `wait` for some.
fn events(&self, cursor: Option<u64>, wait: Option<Duration>) -> Result<Page, RemoteError> {
fn events(&self, cursor: Option<u64>, wait: Option<Period>) -> Result<Page, RemoteError> {
self.runner.remote().events(&EventsQuery {
cursor,
wait: wait.map(Period),
wait,
kind: List(vec![KindPattern::Exact(
Kind::new("check.requested").expect("a valid kind"),
)]),
Expand Down
4 changes: 2 additions & 2 deletions apps/origin-src/benches/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ fn long_poll_wakeup(bencher: Bencher<'_, '_>) {
.next;
let query = EventsQuery {
cursor: Some(cursor),
wait: Some(Period(Duration::from_secs(30))),
wait: Some(Period::from_secs(30)),
kind: List(vec!["statement.issued".parse().unwrap()]),
..EventsQuery::default()
};
Expand Down Expand Up @@ -225,7 +225,7 @@ fn long_poll_wakeup_from_another_process(bencher: Bencher<'_, '_>) {
.next;
let query = EventsQuery {
cursor: Some(cursor),
wait: Some(Period(Duration::from_secs(30))),
wait: Some(Period::from_secs(30)),
kind: List(vec!["statement.issued".parse().unwrap()]),
..EventsQuery::default()
};
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 @@ -545,7 +545,7 @@ impl Cli {
}) => {
println!(
"{}",
ServerConfig::load(&config)?.issue_token(principal, scope, ttl.0)?
ServerConfig::load(&config)?.issue_token(principal, scope, ttl.duration())?
);
return Ok(());
}
Expand Down
2 changes: 1 addition & 1 deletion apps/origin-src/src/permissions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1735,7 +1735,7 @@ grants = { all = "none", "user:ada" = "write" }
let parent = scoped("user:eve", &["annotate review", "land *"], expires);
let request = origin_shared::api::TokenRequest {
scope: vec!["annotate review".parse().unwrap()],
ttl: origin_shared::Period(OriginService::MAX_TOKEN_TTL),
ttl: origin_shared::Period::from_secs(OriginService::MAX_TOKEN_TTL.as_secs()),
};
let issued = fixture.service.issue_token(&parent, &request).unwrap();
assert_eq!(issued.expires, expires);
Expand Down
2 changes: 1 addition & 1 deletion apps/origin-src/src/policy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -653,7 +653,7 @@ impl TryFrom<BTreeMap<String, String>> for Retention {
let rules = table
.into_iter()
.map(|(pattern, period)| {
let Period(duration) = period.parse()?;
let duration = period.parse::<Period>()?.duration();
let pattern: KindPattern = pattern.parse()?;
if pattern.is_reserved() {
return Err(RetentionError::Reserved(pattern));
Expand Down
6 changes: 4 additions & 2 deletions apps/origin-src/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,7 @@ impl OriginService {
let mut token = Token::new(
principal.clone(),
request.scope.clone(),
request.ttl.0.min(Self::MAX_TOKEN_TTL),
request.ttl.duration().min(Self::MAX_TOKEN_TTL),
);
if let Caller::Principal {
scope: Some(scope), ..
Expand Down Expand Up @@ -1312,7 +1312,9 @@ impl OriginService {
.limit
.unwrap_or(Self::MAX_EVENTS)
.min(Self::MAX_EVENTS) as usize;
let wait = query.wait.map_or(Duration::ZERO, |wait| wait.0);
let wait = query
.wait
.map_or(Duration::ZERO, origin_shared::Period::duration);
let accept = |event: &EventKind| Ok(filter.matches(event) && reader.sees_event(event)?);
let page = events.wait(cursor, accept, limit, wait.min(Self::MAX_WAIT))?;
Ok(Page { generation, ..page })
Expand Down
2 changes: 1 addition & 1 deletion apps/origin-src/src/workspace/ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ impl Workspace {
let mut query = EventsQuery {
cursor: since,
generation: None,
wait: Some(Period(OriginService::MAX_WAIT)),
wait: Some(Period::from_secs(OriginService::MAX_WAIT.as_secs())),
limit: Some(256),
kind: List(kinds),
subject: List(subjects),
Expand Down
4 changes: 2 additions & 2 deletions apps/origin-src/tests/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -837,7 +837,7 @@ async fn events_long_poll() {

let query = EventsQuery {
cursor: Some(now.next),
wait: Some(Period(Duration::from_secs(30))),
wait: Some(Period::from_secs(30)),
kind: List(vec!["revision.created".parse().unwrap()]),
..EventsQuery::default()
};
Expand Down Expand Up @@ -919,7 +919,7 @@ async fn tells_callers_what_they_may_do_and_issues_narrower_tokens() {
.iter()
.map(|capability| capability.parse().unwrap())
.collect(),
ttl: Period(Duration::from_hours(1)),
ttl: Period::from_secs(60 * 60),
};
let issued = server
.strict
Expand Down
28 changes: 20 additions & 8 deletions crates/origin-shared/src/text.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,14 +82,27 @@ as_text! {
}

/// A length of time, written as a whole number of seconds (`s`), minutes
/// (`m`), hours (`h`) or days (`d`), such as `90d` or `30s`.
/// (`m`), hours (`h`) or days (`d`), such as `90d` or `30s`. It holds whole
/// seconds only, so it always displays as what it is.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Period(pub Duration);
pub struct Period(u64);

impl Period {
/// The units, longest first, so a period displays in the largest one
/// that divides it.
const UNITS: [(char, u64); 4] = [('d', 24 * 60 * 60), ('h', 60 * 60), ('m', 60), ('s', 1)];

/// A period of `seconds`.
#[must_use]
pub const fn from_secs(seconds: u64) -> Self {
Self(seconds)
}

/// The period's length.
#[must_use]
pub const fn duration(self) -> Duration {
Duration::from_secs(self.0)
}
}

impl FromStr for Period {
Expand All @@ -103,15 +116,14 @@ impl FromStr for Period {
.find(|(name, _)| *name == unit)
.ok_or_else(invalid)?;
let count: u64 = period[..period.len() - 1].parse().map_err(|_| invalid())?;
let total = count.checked_mul(seconds).ok_or_else(invalid)?;
Ok(Self(Duration::from_secs(total)))
count.checked_mul(seconds).map(Self).ok_or_else(invalid)
}
}

/// In whole seconds, in the largest unit that divides them.
impl fmt::Display for Period {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let seconds = self.0.as_secs();
let seconds = self.0;
let (unit, size) = Self::UNITS
.into_iter()
.find(|&(_, size)| seconds.is_multiple_of(size) && seconds >= size)
Expand All @@ -138,11 +150,11 @@ mod tests {
("45s", 45),
] {
let period: Period = text.parse().unwrap();
assert_eq!(period.0, Duration::from_secs(seconds));
assert_eq!(period.duration(), Duration::from_secs(seconds));
assert_eq!(period.to_string(), text);
}
assert_eq!(Period(Duration::from_secs(120)).to_string(), "2m");
assert_eq!(Period(Duration::ZERO).to_string(), "0s");
assert_eq!(Period::from_secs(120).to_string(), "2m");
assert_eq!(Period::from_secs(0).to_string(), "0s");
for invalid in ["", "d", "5", "5w", "-1s", "1.5h"] {
assert!(invalid.parse::<Period>().is_err(), "{invalid:?}");
}
Expand Down
Loading