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 timer_sleep::{Sleep, TimerInterval};
57
58pub use scan_once::{
59 DEFAULT_ONCE_QUEUE_SIZE, OnceCallback, ScanOnceHandle, ScanOnceOverflow, ScanOnceQueue,
60};
61
62/// Owns the three background facilities (callback pool, delayed timer, scanOnce
63/// worker) and every thread backing them. Constructing it starts the threads;
64/// dropping it stops and joins them.
65///
66/// The delayed timer fires its due callbacks into the callback pool, exactly as
67/// C's `notify` routes an expired `epicsTimer` back through `callbackRequest`
68/// (`callback.c:404-419`).
69pub struct BackgroundExecutor {
70 callbacks: CallbackPool,
71 timer: DelayedTimer,
72 scan_once: ScanOnceQueue,
73}
74
75impl BackgroundExecutor {
76 /// Start all three facilities with their C-default sizing.
77 pub fn new() -> Self {
78 let callbacks = CallbackPool::new();
79 let timer = DelayedTimer::new(callbacks.handle());
80 let scan_once = ScanOnceQueue::new();
81 BackgroundExecutor {
82 callbacks,
83 timer,
84 scan_once,
85 }
86 }
87
88 /// A cheap, clonable handle over all three facilities — the seam route for
89 /// RTEMS synchronous-tail hand-offs.
90 pub fn handle(&self) -> BackgroundHandle {
91 BackgroundHandle {
92 callbacks: self.callbacks.handle(),
93 timer: self.timer.handle(),
94 scan_once: self.scan_once.handle(),
95 }
96 }
97
98 /// The callback executor pool.
99 pub fn callbacks(&self) -> &CallbackPool {
100 &self.callbacks
101 }
102
103 /// The delayed-callback timer.
104 pub fn timer(&self) -> &DelayedTimer {
105 &self.timer
106 }
107
108 /// The `scanOnce` facility.
109 pub fn scan_once(&self) -> &ScanOnceQueue {
110 &self.scan_once
111 }
112}
113
114impl Default for BackgroundExecutor {
115 fn default() -> Self {
116 Self::new()
117 }
118}
119
120/// Cheap, clonable submission side of a [`BackgroundExecutor`]. Every method
121/// enqueues and returns immediately; the work runs on a background thread.
122///
123/// This is the type the sans-io seam routes RTEMS tail hand-offs into — the
124/// runtime-free counterpart of [`crate::runtime::task::spawn`].
125#[derive(Clone)]
126pub struct BackgroundHandle {
127 callbacks: CallbackHandle,
128 timer: TimerHandle,
129 scan_once: ScanOnceHandle,
130}
131
132impl BackgroundHandle {
133 /// Enqueue an immediate callback on `priority` — C `callbackRequest`
134 /// (`callback.c:341`).
135 pub fn callback(&self, priority: CallbackPriority, cb: Callback) -> Result<(), CallbackError> {
136 self.callbacks.request(priority, cb)
137 }
138
139 /// Enqueue a callback to run after `delay` on `priority` — C
140 /// `callbackRequestDelayed` (`callback.c:410`).
141 pub fn callback_delayed(&self, delay: Duration, priority: CallbackPriority, cb: Callback) {
142 self.timer.schedule(delay, priority, cb);
143 }
144
145 /// Enqueue a one-shot record-process tail — C `scanOnce` (`dbScan.c:664`).
146 pub fn scan_once(&self, cb: OnceCallback) -> Result<(), ScanOnceOverflow> {
147 self.scan_once.scan_once(cb)
148 }
149
150 /// The callback-submission handle alone.
151 pub fn callbacks(&self) -> &CallbackHandle {
152 &self.callbacks
153 }
154
155 /// The delayed-timer handle alone.
156 pub fn timer(&self) -> &TimerHandle {
157 &self.timer
158 }
159
160 /// The scanOnce-submission handle alone.
161 pub fn scan_once_handle(&self) -> &ScanOnceHandle {
162 &self.scan_once
163 }
164}
165
166#[cfg(test)]
167mod tests {
168 use super::*;
169 use std::sync::mpsc;
170
171 const T: Duration = Duration::from_secs(5);
172
173 #[test]
174 fn executor_routes_all_three_facilities() {
175 let exec = BackgroundExecutor::new();
176 let h = exec.handle();
177
178 let (tx, rx) = mpsc::channel();
179 let tx_cb = tx.clone();
180 h.callback(
181 CallbackPriority::Medium,
182 Box::new(move || tx_cb.send("cb").unwrap()),
183 )
184 .unwrap();
185 let tx_once = tx.clone();
186 h.scan_once(Box::new(move || tx_once.send("once").unwrap()))
187 .unwrap();
188 h.callback_delayed(
189 Duration::from_millis(20),
190 CallbackPriority::High,
191 Box::new(move || tx.send("delayed").unwrap()),
192 );
193
194 let mut seen = std::collections::HashSet::new();
195 for _ in 0..3 {
196 seen.insert(rx.recv_timeout(T).unwrap());
197 }
198 assert!(seen.contains("cb"));
199 assert!(seen.contains("once"));
200 assert!(seen.contains("delayed"));
201 }
202}