es_entity/clock/
global.rs1use chrono::{DateTime, Utc};
2
3use std::sync::OnceLock;
4use std::time::Duration;
5
6use super::{ArtificialClockConfig, ClockController, ClockHandle, ClockSleep, ClockTimeout};
7
8struct GlobalState {
9 handle: ClockHandle,
10 controller: Option<ClockController>,
11}
12
13static GLOBAL: OnceLock<GlobalState> = OnceLock::new();
14
15pub struct Clock;
17
18impl Clock {
19 pub fn now() -> DateTime<Utc> {
23 Self::handle().now()
24 }
25
26 pub fn sleep(duration: Duration) -> ClockSleep {
28 Self::handle().sleep(duration)
29 }
30
31 pub fn timeout<F: std::future::Future>(duration: Duration, future: F) -> ClockTimeout<F> {
33 Self::handle().timeout(duration, future)
34 }
35
36 pub fn handle() -> &'static ClockHandle {
38 &GLOBAL
39 .get_or_init(|| GlobalState {
40 handle: ClockHandle::realtime(),
41 controller: None,
42 })
43 .handle
44 }
45
46 pub fn install_artificial(config: ArtificialClockConfig) -> ClockController {
54 if let Some(state) = GLOBAL.get() {
56 return state
57 .controller
58 .clone()
59 .expect("Cannot install artificial clock: realtime clock already initialized");
60 }
61
62 let (handle, ctrl) = ClockHandle::artificial(config);
64
65 match GLOBAL.set(GlobalState {
66 handle,
67 controller: Some(ctrl.clone()),
68 }) {
69 Ok(()) => ctrl,
70 Err(_) => {
71 GLOBAL
73 .get()
74 .unwrap()
75 .controller
76 .clone()
77 .expect("Cannot install artificial clock: realtime clock already initialized")
78 }
79 }
80 }
81
82 pub fn is_artificial() -> bool {
84 GLOBAL
85 .get()
86 .map(|s| s.controller.is_some())
87 .unwrap_or(false)
88 }
89}