aimdb_core/executor.rs
1//! Runtime capability surface consumed by the database engine.
2//!
3//! [`RuntimeOps`] is the single trait a runtime adapter implements: identity,
4//! a clock factory, sleep, and logging, all on concrete types
5//! (`core::time::Duration`, a boxed sleep future, `Arc<dyn InstanceClock>`) so the
6//! runtime travels as a *value* — `Arc<dyn RuntimeOps>` — rather than a type
7//! parameter. `AimDb`/`RuntimeContext` hold the runtime this way, and adapters
8//! hand one to `AimDbBuilder::runtime`.
9//!
10//! The boxed `sleep` future costs one allocation per call, consistent with the
11//! engine's cost model: every service future is already boxed, and `alloc` is
12//! mandatory on all supported targets.
13
14/// Heap-pinned, `Send`, `'static` future — the unit of work AimDB drives.
15pub type BoxFuture =
16 core::pin::Pin<alloc::boxed::Box<dyn core::future::Future<Output = ()> + Send + 'static>>;
17
18/// Log severity for [`RuntimeOps::log`].
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub enum LogLevel {
21 Debug,
22 Info,
23 Warn,
24 Error,
25}
26
27/// Object-safe runtime capabilities: identity, clock, sleep, and logging.
28///
29/// Time is read from the [`InstanceClock`] this trait creates, never from the
30/// runtime itself (design 058 §3.1).
31///
32/// Implemented by every runtime adapter (`TokioAdapter`, `EmbassyAdapter`,
33/// `WasmAdapter`) so a runtime can travel as `Arc<dyn RuntimeOps>` instead of
34/// a generic parameter.
35pub trait RuntimeOps: Send + Sync {
36 /// Short adapter identity, e.g. `"tokio"`.
37 fn name(&self) -> &'static str;
38
39 /// Completes after at least `d` has elapsed.
40 fn sleep(&self, d: core::time::Duration) -> BoxFuture;
41
42 /// Emits `msg` at `level` through the adapter's logging backend.
43 fn log(&self, level: LogLevel, msg: &str);
44
45 /// Creates a new clock whose monotonic origin is the moment of this call.
46 ///
47 /// Called once by `AimDbBuilder::build()`; every write of the instance is
48 /// stamped from the returned clock, whichever thread, task or runtime
49 /// performs it (design 058 §3). Code outside an instance (a standalone
50 /// client engine) creates its own through `RuntimeContext::new`.
51 fn new_clock(&self) -> alloc::sync::Arc<dyn InstanceClock>;
52}
53
54use crate::clock::InstanceClock;
55
56pub type ExecutorResult<T> = Result<T, ExecutorError>;
57
58/// Errors from the engine's task-coordination plumbing.
59#[derive(Debug, thiserror::Error)]
60pub enum ExecutorError {
61 /// A join pipeline's trigger queue closed because every sender was dropped.
62 #[error("Join queue closed")]
63 QueueClosed,
64}
65
66/// Shared behavioral contract for [`RuntimeOps`] implementations.
67///
68/// Each adapter crate calls [`assert_runtime_ops_contract`] from a test running
69/// under its own executor (`#[tokio::test]`, `block_on`, `#[wasm_bindgen_test]`),
70/// so the one contract is exercised against every runtime implementation.
71///
72/// [`assert_runtime_ops_contract`]: test_support::assert_runtime_ops_contract
73#[doc(hidden)]
74pub mod test_support {
75 use super::{LogLevel, RuntimeOps};
76 use crate::clock::{InstanceClock, Stamp};
77 use alloc::sync::Arc;
78 #[cfg(target_has_atomic = "64")]
79 use portable_atomic::{AtomicU64, Ordering};
80
81 /// An [`InstanceClock`] pinned at zero.
82 #[derive(Clone, Copy, Debug, Default)]
83 pub struct ZeroClock;
84
85 impl InstanceClock for ZeroClock {
86 fn now(&self) -> Stamp {
87 Stamp::from_nanos(0)
88 }
89 fn unix_time(&self) -> Option<(u64, u32)> {
90 None
91 }
92 }
93
94 /// An [`InstanceClock`] that stands still until [`advance`](Self::advance)d.
95 /// Host targets only (needs 64-bit atomics).
96 #[cfg(target_has_atomic = "64")]
97 #[derive(Debug, Default)]
98 pub struct ManualClock(AtomicU64);
99
100 #[cfg(target_has_atomic = "64")]
101 impl ManualClock {
102 pub fn new() -> Self {
103 Self::default()
104 }
105 pub fn advance(&self, d: core::time::Duration) {
106 let ns = crate::clock::stamp_from_duration(d).as_nanos();
107 self.0.fetch_add(ns, Ordering::SeqCst);
108 }
109 }
110
111 #[cfg(target_has_atomic = "64")]
112 impl InstanceClock for ManualClock {
113 fn now(&self) -> Stamp {
114 Stamp::from_nanos(self.0.load(Ordering::SeqCst))
115 }
116 fn unix_time(&self) -> Option<(u64, u32)> {
117 None
118 }
119 }
120
121 /// [`NoopRuntimeOps`], except that its instance clock is one shared
122 /// [`ManualClock`] the test holds and advances.
123 #[cfg(target_has_atomic = "64")]
124 #[derive(Clone, Debug, Default)]
125 pub struct ManualClockRuntimeOps {
126 pub clock: Arc<ManualClock>,
127 }
128
129 #[cfg(target_has_atomic = "64")]
130 impl RuntimeOps for ManualClockRuntimeOps {
131 fn name(&self) -> &'static str {
132 "manual-clock"
133 }
134 fn sleep(&self, _d: core::time::Duration) -> super::BoxFuture {
135 alloc::boxed::Box::pin(core::future::ready(()))
136 }
137 fn log(&self, _level: LogLevel, _msg: &str) {}
138 fn new_clock(&self) -> Arc<dyn InstanceClock> {
139 self.clock.clone()
140 }
141 }
142
143 /// A no-op [`RuntimeOps`] for tests that need a runtime value (a
144 /// `RuntimeContext`, an engine clock) but no real runtime behind it: the
145 /// clock (and each instance clock) is pinned at `0`, sleeps complete immediately, logs are discarded.
146 ///
147 /// One shared stub instead of a hand-rolled copy per test module, so a
148 /// `RuntimeOps` change is fixed here and in the real adapters only.
149 #[derive(Clone, Copy, Debug, Default)]
150 pub struct NoopRuntimeOps;
151
152 impl RuntimeOps for NoopRuntimeOps {
153 fn name(&self) -> &'static str {
154 "noop"
155 }
156 fn sleep(&self, _d: core::time::Duration) -> super::BoxFuture {
157 alloc::boxed::Box::pin(core::future::ready(()))
158 }
159 fn log(&self, _level: LogLevel, _msg: &str) {}
160 fn new_clock(&self) -> Arc<dyn InstanceClock> {
161 Arc::new(ZeroClock)
162 }
163 }
164
165 /// Asserts the behavioral contract every `RuntimeOps` implementation must hold.
166 ///
167 /// Uses `Duration::ZERO` for the sleep check: the Embassy host-test time
168 /// driver reports `now() == 0` with a no-op `schedule_wake`, so any non-zero
169 /// sleep would hang forever on the host. Adapters with a real clock should
170 /// additionally assert that a non-zero sleep advances their clock in their
171 /// own tests.
172 pub async fn assert_runtime_ops_contract(ops: &dyn RuntimeOps) {
173 assert!(!ops.name().is_empty(), "name() must be non-empty");
174
175 let clock = ops.new_clock();
176 let s0 = clock.now();
177 let s1 = clock.now();
178 assert!(
179 s1 >= s0,
180 "instance clock must be nondecreasing ({s1:?} < {s0:?})"
181 );
182
183 ops.log(LogLevel::Debug, "runtime-ops contract: debug");
184 ops.log(LogLevel::Info, "runtime-ops contract: info");
185 ops.log(LogLevel::Warn, "runtime-ops contract: warn");
186 ops.log(LogLevel::Error, "runtime-ops contract: error");
187
188 ops.sleep(core::time::Duration::ZERO).await;
189
190 if let Some((secs, nanos)) = clock.unix_time() {
191 assert!(
192 nanos < 1_000_000_000,
193 "unix_time nanos out of range: {nanos}"
194 );
195 // Sanity: any real wall clock reads after 2020-09-13 (1.6e9).
196 assert!(
197 secs > 1_600_000_000,
198 "unix_time seconds implausible: {secs}"
199 );
200 }
201 }
202}