From c1a7051dfbbccd466b72aa20b3ea257f00f03c57 Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 20:21:37 +0100 Subject: [PATCH] fix(shared): hold whole seconds in a Period Period wrapped any Duration, but it displays, and goes over the wire, in whole seconds: a sub-second part was dropped silently. It now holds whole seconds, built with Period::from_secs and read with Period::duration, so it always displays as what it is. The CI worker's long-poll wait is a Period too. --- apps/origin-ci/benches/worker.rs | 13 ++++++++----- apps/origin-ci/src/worker.rs | 10 +++++----- apps/origin-src/benches/server.rs | 4 ++-- apps/origin-src/src/cli.rs | 2 +- apps/origin-src/src/permissions.rs | 2 +- apps/origin-src/src/policy.rs | 2 +- apps/origin-src/src/service.rs | 6 ++++-- apps/origin-src/src/workspace/ops.rs | 2 +- apps/origin-src/tests/http.rs | 4 ++-- crates/origin-shared/src/text.rs | 28 ++++++++++++++++++++-------- 10 files changed, 45 insertions(+), 28 deletions(-) diff --git a/apps/origin-ci/benches/worker.rs b/apps/origin-ci/benches/worker.rs index 054845b1..baf3442e 100644 --- a/apps/origin-ci/benches/worker.rs +++ b/apps/origin-ci/benches/worker.rs @@ -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}; @@ -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; @@ -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 } @@ -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())); }); } diff --git a/apps/origin-ci/src/worker.rs b/apps/origin-ci/src/worker.rs index 99be20a8..97779b67 100644 --- a/apps/origin-ci/src/worker.rs +++ b/apps/origin-ci/src/worker.rs @@ -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. @@ -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, WorkerError> { + pub fn next(&mut self, wait: Period) -> Result, WorkerError> { let mut retry = Self::FIRST_RETRY; loop { match self.poll(wait) { @@ -145,7 +145,7 @@ impl Worker { /// # Errors /// /// Fails if the remote cannot be reached or refuses. - pub fn poll(&mut self, wait: Duration) -> Result, WorkerError> { + pub fn poll(&mut self, wait: Period) -> Result, WorkerError> { let cursor = match self.cursor { Some(cursor) if self.reconciled.elapsed() < Self::RECONCILE => cursor, _ => return self.reconcile(), @@ -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, wait: Option) -> Result { + fn events(&self, cursor: Option, wait: Option) -> Result { self.runner.remote().events(&EventsQuery { cursor, - wait: wait.map(Period), + wait, kind: List(vec![KindPattern::Exact( Kind::new("check.requested").expect("a valid kind"), )]), diff --git a/apps/origin-src/benches/server.rs b/apps/origin-src/benches/server.rs index 44eab978..2f4f7db0 100644 --- a/apps/origin-src/benches/server.rs +++ b/apps/origin-src/benches/server.rs @@ -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() }; @@ -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() }; diff --git a/apps/origin-src/src/cli.rs b/apps/origin-src/src/cli.rs index b54ee041..b5edf961 100644 --- a/apps/origin-src/src/cli.rs +++ b/apps/origin-src/src/cli.rs @@ -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(()); } diff --git a/apps/origin-src/src/permissions.rs b/apps/origin-src/src/permissions.rs index c96f93ba..29eccb88 100644 --- a/apps/origin-src/src/permissions.rs +++ b/apps/origin-src/src/permissions.rs @@ -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); diff --git a/apps/origin-src/src/policy.rs b/apps/origin-src/src/policy.rs index 9acca94b..072adb34 100644 --- a/apps/origin-src/src/policy.rs +++ b/apps/origin-src/src/policy.rs @@ -653,7 +653,7 @@ impl TryFrom> for Retention { let rules = table .into_iter() .map(|(pattern, period)| { - let Period(duration) = period.parse()?; + let duration = period.parse::()?.duration(); let pattern: KindPattern = pattern.parse()?; if pattern.is_reserved() { return Err(RetentionError::Reserved(pattern)); diff --git a/apps/origin-src/src/service.rs b/apps/origin-src/src/service.rs index ceba2583..43674a75 100644 --- a/apps/origin-src/src/service.rs +++ b/apps/origin-src/src/service.rs @@ -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), .. @@ -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 }) diff --git a/apps/origin-src/src/workspace/ops.rs b/apps/origin-src/src/workspace/ops.rs index 6a35d020..057e0596 100644 --- a/apps/origin-src/src/workspace/ops.rs +++ b/apps/origin-src/src/workspace/ops.rs @@ -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), diff --git a/apps/origin-src/tests/http.rs b/apps/origin-src/tests/http.rs index 71aff378..018298e6 100644 --- a/apps/origin-src/tests/http.rs +++ b/apps/origin-src/tests/http.rs @@ -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() }; @@ -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 diff --git a/crates/origin-shared/src/text.rs b/crates/origin-shared/src/text.rs index b8490596..43bf9024 100644 --- a/crates/origin-shared/src/text.rs +++ b/crates/origin-shared/src/text.rs @@ -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 { @@ -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) @@ -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::().is_err(), "{invalid:?}"); }