Skip to main content

epics_libcom_rs/runtime/background/
mod.rs

1//! RTEMS-side background-execution infrastructure (CA sans-io refactor,
2//! increment W3a — the seam backend).
3//!
4//! # Why this exists (decision A2)
5//!
6//! The CA server is being made runnable on RTEMS (armv7-rtems-eabihf) with
7//! **one** async engine. On a hosted target, async *tails* — PACT device
8//! completion, FLNK/scanOnce chains, SDLY/ODLY/watchdog timers, WRITE_NOTIFY
9//! completion — run as tokio tasks via [`crate::runtime::task::spawn`]. RTEMS
10//! has no tokio runtime (`tokio::spawn`/`tokio::time` need one), so those tails
11//! need a runtime-free home. This module is that home: three C-parity
12//! facilities built from **plain `std` threads + `Mutex`/`Condvar`**, carrying
13//! no tokio dependency.
14//!
15//! | Facility | C source | Rust |
16//! |----------|----------|------|
17//! | [`callback_executor`] | `callback.c` `callbackQueue[]`/`callbackTask` | priority-banded worker pool |
18//! | [`delayed_timer`] | `callback.c` `callbackRequestDelayed`/`timerQueue` | one deadline-ordered timer thread |
19//! | [`scan_once`] | `dbScan.c` `onceQ`/`scanOnce`/`onceTask` | bounded ring + one worker |
20//!
21//! # The seam handle
22//!
23//! [`BackgroundExecutor`] owns the three facilities and their threads;
24//! [`BackgroundExecutor::handle`] hands out a cheap, clonable
25//! [`BackgroundHandle`] that the future seam wiring routes synchronous-tail
26//! hand-offs through. The hosted (tokio) build keeps calling
27//! [`crate::runtime::task::spawn`] — this module is **only** the RTEMS route,
28//! and this increment adds the infrastructure without switching any call site
29//! over to it (that is a later increment).
30
31pub mod callback_executor;
32pub mod delayed_timer;
33// `pub`, not `pub(crate)`: the record system's periodic-scan threads
34// (`epics_base_rs::server::scan`) and the database write gate run under the
35// same poison-recovery and panic-isolation rules as the facilities here, and
36// they call [`facility::recover`] / [`facility::run_isolated`] to get them.
37// Those call sites were inside this crate before the runtime layer was split
38// out; the split moved the callers across a crate boundary, and one shared
39// helper reached through a wider door is what keeps the rule single-sourced
40// rather than restated in the crate above.
41pub mod facility;
42pub mod future_exec;
43pub mod scan_once;
44pub mod timer_sleep;
45
46use std::time::Duration;
47
48pub use callback_executor::{
49    Callback, CallbackError, CallbackHandle, CallbackPool, CallbackPriority, DEFAULT_QUEUE_SIZE,
50    DEFAULT_THREADS_PER_PRIORITY, NUM_CALLBACK_PRIORITIES,
51};
52pub use delayed_timer::{DelayedTimer, TimerHandle};
53pub use future_exec::{
54    AbortHandle, DEFAULT_SPAWN_PRIORITY, JoinError, JoinFuture, spawn_blocking_on, spawn_future,
55};
56pub use scan_once::{
57    DEFAULT_ONCE_QUEUE_SIZE, OnceCallback, ScanOnceHandle, ScanOnceOverflow, ScanOnceQueue,
58};
59
60/// Owns the three background facilities (callback pool, delayed timer, scanOnce
61/// worker) and every thread backing them. Constructing it starts the threads;
62/// dropping it stops and joins them.
63///
64/// The delayed timer fires its due callbacks into the callback pool, exactly as
65/// C's `notify` routes an expired `epicsTimer` back through `callbackRequest`
66/// (`callback.c:404-419`).
67pub struct BackgroundExecutor {
68    callbacks: CallbackPool,
69    timer: DelayedTimer,
70    scan_once: ScanOnceQueue,
71}
72
73impl BackgroundExecutor {
74    /// Start all three facilities with their C-default sizing.
75    pub fn new() -> Self {
76        let callbacks = CallbackPool::new();
77        let timer = DelayedTimer::new(callbacks.handle());
78        let scan_once = ScanOnceQueue::new();
79        BackgroundExecutor {
80            callbacks,
81            timer,
82            scan_once,
83        }
84    }
85
86    /// A cheap, clonable handle over all three facilities — the seam route for
87    /// RTEMS synchronous-tail hand-offs.
88    pub fn handle(&self) -> BackgroundHandle {
89        BackgroundHandle {
90            callbacks: self.callbacks.handle(),
91            timer: self.timer.handle(),
92            scan_once: self.scan_once.handle(),
93        }
94    }
95
96    /// The callback executor pool.
97    pub fn callbacks(&self) -> &CallbackPool {
98        &self.callbacks
99    }
100
101    /// The delayed-callback timer.
102    pub fn timer(&self) -> &DelayedTimer {
103        &self.timer
104    }
105
106    /// The `scanOnce` facility.
107    pub fn scan_once(&self) -> &ScanOnceQueue {
108        &self.scan_once
109    }
110}
111
112impl Default for BackgroundExecutor {
113    fn default() -> Self {
114        Self::new()
115    }
116}
117
118/// Cheap, clonable submission side of a [`BackgroundExecutor`]. Every method
119/// enqueues and returns immediately; the work runs on a background thread.
120///
121/// This is the type the sans-io seam routes RTEMS tail hand-offs into — the
122/// runtime-free counterpart of [`crate::runtime::task::spawn`].
123#[derive(Clone)]
124pub struct BackgroundHandle {
125    callbacks: CallbackHandle,
126    timer: TimerHandle,
127    scan_once: ScanOnceHandle,
128}
129
130impl BackgroundHandle {
131    /// Enqueue an immediate callback on `priority` — C `callbackRequest`
132    /// (`callback.c:341`).
133    pub fn callback(&self, priority: CallbackPriority, cb: Callback) -> Result<(), CallbackError> {
134        self.callbacks.request(priority, cb)
135    }
136
137    /// Enqueue a callback to run after `delay` on `priority` — C
138    /// `callbackRequestDelayed` (`callback.c:410`).
139    pub fn callback_delayed(&self, delay: Duration, priority: CallbackPriority, cb: Callback) {
140        self.timer.schedule(delay, priority, cb);
141    }
142
143    /// Enqueue a one-shot record-process tail — C `scanOnce` (`dbScan.c:664`).
144    pub fn scan_once(&self, cb: OnceCallback) -> Result<(), ScanOnceOverflow> {
145        self.scan_once.scan_once(cb)
146    }
147
148    /// The callback-submission handle alone.
149    pub fn callbacks(&self) -> &CallbackHandle {
150        &self.callbacks
151    }
152
153    /// The delayed-timer handle alone.
154    pub fn timer(&self) -> &TimerHandle {
155        &self.timer
156    }
157
158    /// The scanOnce-submission handle alone.
159    pub fn scan_once_handle(&self) -> &ScanOnceHandle {
160        &self.scan_once
161    }
162}
163
164#[cfg(test)]
165mod tests {
166    use super::*;
167    use std::sync::mpsc;
168
169    const T: Duration = Duration::from_secs(5);
170
171    #[test]
172    fn executor_routes_all_three_facilities() {
173        let exec = BackgroundExecutor::new();
174        let h = exec.handle();
175
176        let (tx, rx) = mpsc::channel();
177        let tx_cb = tx.clone();
178        h.callback(
179            CallbackPriority::Medium,
180            Box::new(move || tx_cb.send("cb").unwrap()),
181        )
182        .unwrap();
183        let tx_once = tx.clone();
184        h.scan_once(Box::new(move || tx_once.send("once").unwrap()))
185            .unwrap();
186        h.callback_delayed(
187            Duration::from_millis(20),
188            CallbackPriority::High,
189            Box::new(move || tx.send("delayed").unwrap()),
190        );
191
192        let mut seen = std::collections::HashSet::new();
193        for _ in 0..3 {
194            seen.insert(rx.recv_timeout(T).unwrap());
195        }
196        assert!(seen.contains("cb"));
197        assert!(seen.contains("once"));
198        assert!(seen.contains("delayed"));
199    }
200}