Skip to main content

crabshell_services/
clock.rs

1//! The clock: the time, truncated to a whole second, minute or day.
2
3use std::cell::RefCell;
4use std::collections::HashMap;
5use std::future::poll_fn;
6use std::path::Path;
7use std::pin::Pin;
8use std::rc::Rc;
9use std::sync::Once;
10use std::task::Poll;
11use std::time::{Duration, Instant};
12
13use calloop::RegistrationToken;
14use calloop::timer::TimeoutAction;
15use crabshell_reactive::{ReadSignal, Signal};
16use crabshell_ui::Cx;
17use jiff::tz::TimeZone;
18use jiff::{SignedDuration, Timestamp, Zoned};
19use zbus::export::futures_core::Stream;
20use zbus::{MatchRule, Message, MessageStream};
21
22use crate::Shared;
23
24#[cfg(test)]
25mod tests;
26
27/// How often a clock changes.
28#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
29pub enum Precision {
30  /// On every whole second.
31  Second,
32  /// On every whole minute.
33  Minute,
34  /// At every midnight in the system time zone, for a date: once a day,
35  /// 23 or 25 hours apart on a day the clocks change.
36  Day,
37}
38
39/// How long after the first clock the system bus is reached, so its
40/// connection stays off a first frame's path. A suspend before the
41/// watcher listens goes unannounced, so it resyncs once it does.
42const WATCH_AFTER: Duration = if cfg!(test) {
43  Duration::from_millis(200)
44} else {
45  Duration::from_secs(1)
46};
47
48/// How early a timer may fire and still count as on its boundary.
49const EARLY: SignedDuration = SignedDuration::from_millis(50);
50
51/// The clocks of one shell: one per precision, each started on first use.
52pub(crate) struct Clocks {
53  shared: Rc<Shared>,
54  started: RefCell<Vec<Clock>>,
55}
56
57struct Clock {
58  precision: Precision,
59  signal: Signal<Zoned>,
60  /// Its timer in the event loop, set for the next boundary.
61  timer: Option<RegistrationToken>,
62}
63
64/// `cx.clock(precision)`.
65pub(crate) fn clock(cx: &Cx, precision: Precision) -> ReadSignal<Zoned> {
66  if let Some(clocks) = cx.service::<Clocks>() {
67    return clocks.get(precision);
68  }
69  static LOGGED: Once = Once::new();
70  LOGGED.call_once(|| {
71    tracing::warn!("cx.clock() needs the services the shell provides; this clock stands still");
72  });
73  let zone = TimeZone::system();
74  let (shown, _) = boundaries(Timestamp::now(), precision, &zone);
75  cx.signal(shown.to_zoned(zone)).read_only()
76}
77
78impl Clocks {
79  pub(crate) fn new(shared: Rc<Shared>) -> Clocks {
80    Clocks {
81      shared,
82      started: RefCell::new(Vec::new()),
83    }
84  }
85
86  /// The clock for `precision`, started if it is the first ask.
87  fn get(self: &Rc<Self>, precision: Precision) -> ReadSignal<Zoned> {
88    let started = self.started.borrow();
89    if let Some(clock) = started.iter().find(|clock| clock.precision == precision) {
90      return clock.signal.read_only();
91    }
92    let first = started.is_empty();
93    drop(started);
94    if first
95      && let Some(bus) = self.shared.config.system_bus.clone()
96      && let Some(event_loop) = self.shared.event_loop()
97    {
98      let clocks = Rc::clone(self);
99      let mut bus = Some(bus);
100      let later = Box::new(move || {
101        if let Some(bus) = bus.take() {
102          clocks.shared.spawn(watch(Rc::clone(&clocks), bus));
103        }
104        TimeoutAction::Drop
105      });
106      event_loop.insert_timer(Instant::now() + WATCH_AFTER, later);
107    }
108    let (shown, deadline) = current(precision, &self.zone());
109    let signal = self.shared.root.signal(shown);
110    let timer = self.timer(precision, deadline);
111    self.started.borrow_mut().push(Clock {
112      precision,
113      signal,
114      timer,
115    });
116    signal.read_only()
117  }
118
119  /// Shows the right time at once and sets every timer afresh from the
120  /// wall clock. Timers count monotonic time, which stops in a suspend.
121  fn resync(self: &Rc<Self>) {
122    let zone = self.zone();
123    let Some(event_loop) = self.shared.event_loop() else {
124      return;
125    };
126    for clock in self.started.borrow_mut().iter_mut() {
127      let (shown, deadline) = current(clock.precision, &zone);
128      clock.signal.try_set(shown);
129      if let Some(old) = clock.timer.take() {
130        event_loop.remove(old);
131      }
132      clock.timer = self.timer(clock.precision, deadline);
133    }
134  }
135
136  /// Acts on a signal from logind or timedated. A bad one is logged.
137  fn on_message(self: &Rc<Self>, message: &Message) {
138    let body = message.body();
139    match message.header().member().map(|member| member.as_str()) {
140      Some("PrepareForSleep") => match body.deserialize::<bool>() {
141        Ok(true) => {}
142        Ok(false) => self.resync(),
143        Err(error) => tracing::warn!(%error, "a bad PrepareForSleep from logind"),
144      },
145      Some("PropertiesChanged") => {
146        match body.deserialize::<(&str, HashMap<&str, zbus::Variant<'_>>, Vec<&str>)>() {
147          Ok((_, changed, invalidated))
148            if changed.contains_key("Timezone") || invalidated.contains(&"Timezone") =>
149          {
150            tracing::info!(zone = self.zone().iana_name(), "the time zone changed");
151            self.resync();
152          }
153          Ok(_) => {}
154          Err(error) => tracing::warn!(%error, "a bad PropertiesChanged from timedated"),
155        }
156      }
157      _ => {}
158    }
159  }
160
161  /// A timer that ticks the `precision` clock at `deadline`, and then at
162  /// every boundary after it.
163  fn timer(self: &Rc<Self>, precision: Precision, deadline: Instant) -> Option<RegistrationToken> {
164    let clocks = Rc::clone(self);
165    self
166      .shared
167      .event_loop()?
168      .insert_timer(deadline, Box::new(move || clocks.tick(precision)))
169  }
170
171  /// Shows the boundary just passed on the `precision` clock and says
172  /// when to tick next. Stops once the clock's signal is disposed.
173  fn tick(&self, precision: Precision) -> TimeoutAction {
174    let (shown, deadline) = current(precision, &self.zone());
175    let started = self.started.borrow();
176    let clock = started.iter().find(|clock| clock.precision == precision);
177    match clock {
178      Some(clock) if clock.signal.try_set(shown) => TimeoutAction::ToInstant(deadline),
179      _ => TimeoutAction::Drop,
180    }
181  }
182
183  /// Read on every tick, since `/etc/localtime` can change with no
184  /// timedated to say so, as under OpenRC.
185  fn zone(&self) -> TimeZone {
186    system_zone(self.shared.config.localtime.as_deref())
187  }
188}
189
190/// Re-syncs `clocks` when the machine resumes and when timedated changes
191/// the time zone, for as long as the bus is there.
192async fn watch(clocks: Rc<Clocks>, bus: zbus::Address) {
193  let (mut sleep, mut zone) = match subscribe(bus).await {
194    Ok(streams) => streams,
195    Err(error) => {
196      tracing::info!(
197          %error,
198          "no system bus: the clock won't re-sync after a suspend or a time zone change"
199      );
200      return;
201    }
202  };
203  // For a resume before the match rules were in, which nobody heard.
204  clocks.resync();
205  loop {
206    let next = poll_fn(|cx| match Pin::new(&mut sleep).poll_next(cx) {
207      Poll::Pending => Pin::new(&mut zone).poll_next(cx),
208      ready => ready,
209    });
210    match next.await {
211      Some(Ok(message)) => clocks.on_message(&message),
212      Some(Err(error)) => tracing::warn!(%error, "a bad message on the system bus"),
213      None => {
214        tracing::info!("the system bus closed: the clock no longer re-syncs");
215        return;
216      }
217    }
218  }
219}
220
221/// Connects to the system bus and subscribes to logind's `PrepareForSleep`
222/// and timedated's `PropertiesChanged`. Match rules only: a proxy would
223/// read properties first, which starts logind and timedated if they are
224/// not running.
225async fn subscribe(bus: zbus::Address) -> zbus::Result<(MessageStream, MessageStream)> {
226  let connection = zbus::connection::Builder::address(bus).build().await?;
227  let signal = || MatchRule::builder().msg_type(zbus::message::Type::Signal);
228  let sleep = signal()
229    .sender("org.freedesktop.login1")
230    .path("/org/freedesktop/login1")
231    .interface("org.freedesktop.login1.Manager")
232    .member("PrepareForSleep")
233    .build()?;
234  let zone = signal()
235    .sender("org.freedesktop.timedate1")
236    .path("/org/freedesktop/timedate1")
237    .interface("org.freedesktop.DBus.Properties")
238    .member("PropertiesChanged")
239    .arg(0, "org.freedesktop.timedate1")
240    .build()?;
241  Ok((
242    MessageStream::for_match_rule(sleep, &connection, None).await?,
243    MessageStream::for_match_rule(zone, &connection, None).await?,
244  ))
245}
246
247/// What a `precision` clock shows now in `zone`, and the instant its timer
248/// should fire next.
249fn current(precision: Precision, zone: &TimeZone) -> (Zoned, Instant) {
250  let now = Timestamp::now();
251  let (shown, next) = boundaries(now, precision, zone);
252  let wait = Duration::try_from(next.duration_since(now)).unwrap_or_default();
253  // Read after the wall clock, so the deadline errs late, never early.
254  (shown.to_zoned(zone.clone()), Instant::now() + wait)
255}
256
257/// The boundary `now` has just passed, and the one after it: a day's in
258/// `zone`. A `now` up to [`EARLY`] before a boundary counts as on it, so a
259/// timer that fires a hair early shows the new value instead of waking
260/// again ms later.
261fn boundaries(now: Timestamp, precision: Precision, zone: &TimeZone) -> (Timestamp, Timestamp) {
262  const RANGE: &str = "the system clock is within jiff's years -9999 to 9999";
263  let step = match precision {
264    Precision::Second => 1,
265    Precision::Minute => 60,
266    Precision::Day => {
267      let today = (now + EARLY).to_zoned(zone.clone());
268      let midnight = |day: &Zoned| day.start_of_day().expect(RANGE).timestamp();
269      return (midnight(&today), midnight(&today.tomorrow().expect(RANGE)));
270    }
271  };
272  let shown = (now + EARLY).as_second().div_euclid(step) * step;
273  let at = |second| Timestamp::from_second(second).expect(RANGE);
274  (at(shown), at(shown + step))
275}
276
277/// The system time zone, read afresh each call. jiff's
278/// `TimeZone::system()` keeps its answer for 5 minutes, so the
279/// `/etc/localtime` link that timedated rewrites is read here. A copied
280/// file, or `TZ` (`localtime` is `None`), is left to jiff.
281fn system_zone(localtime: Option<&Path>) -> TimeZone {
282  let target = localtime.and_then(|path| std::fs::read_link(path).ok());
283  let name = target
284    .as_deref()
285    .and_then(Path::to_str)
286    .and_then(|target| target.rsplit_once("zoneinfo/"))
287    .map(|(_, name)| name);
288  match name.map(|name| jiff::tz::db().get(name)) {
289    Some(Ok(zone)) => zone,
290    _ => TimeZone::system(),
291  }
292}