seiva_worker/lib.rs
1//! The worker runtime: drive a one-pass job in a loop, with an interval,
2//! graceful shutdown, and metrics.
3//!
4//! This is the framework half of the boundary the brief draws (Parte B / the ORM
5//! boundary): the **one-pass** functions belong to the data layer — the outbox
6//! relay's `forward`/`drain`, RAG's `run_once`, a `dorm-jobs` lease pass — each
7//! does one pass and returns how many items it handled; the **loop** that repeats
8//! them, with timing, shutdown and metrics, is the framework's. [`run_worker`]
9//! is that loop, generic over any such pass, so it is data-layer-free and
10//! testable with a plain closure.
11
12#![forbid(unsafe_code)]
13
14use std::future::Future;
15use std::time::Duration;
16
17use seiva_ports::PortResult;
18
19/// How a worker loops.
20#[derive(Debug, Clone)]
21pub struct WorkerConfig {
22 /// A label for logs and metrics.
23 pub name: String,
24 /// How long to wait between passes. `Duration::ZERO` runs the next pass as
25 /// soon as the last returns.
26 pub interval: Duration,
27 /// When a pass processed at least this many items, run the next immediately
28 /// (drain fast while there is a backlog) instead of waiting `interval`. `0`
29 /// disables the fast path.
30 pub drain_threshold: u64,
31}
32
33impl WorkerConfig {
34 /// A worker named `name` that waits `interval` between passes, with the
35 /// fast-drain path off.
36 pub fn new(name: impl Into<String>, interval: Duration) -> Self {
37 Self {
38 name: name.into(),
39 interval,
40 drain_threshold: 0,
41 }
42 }
43
44 /// Enable the fast-drain path: a pass that processed `>= threshold` items is
45 /// followed immediately by the next, without waiting `interval`.
46 pub fn drain_fast_at(mut self, threshold: u64) -> Self {
47 self.drain_threshold = threshold;
48 self
49 }
50}
51
52/// What a worker did between start and shutdown.
53#[derive(Debug, Clone, Default, PartialEq, Eq)]
54pub struct WorkerReport {
55 /// How many passes ran.
56 pub passes: u64,
57 /// Total items processed across all passes.
58 pub processed: u64,
59 /// How many passes returned an error (logged, never fatal).
60 pub errors: u64,
61}
62
63/// Run `pass` in a loop until `shutdown` resolves, then stop (drain-and-exit).
64///
65/// Each pass returns how many items it processed. An `Err` from a pass is logged
66/// and counted but **never fatal** — a worker outlives a transient failure.
67/// Between passes the loop waits `config.interval`, unless the last pass hit
68/// `config.drain_threshold`, in which case it runs again immediately. Shutdown is
69/// honoured promptly: it is checked before each wait, so a resolved `shutdown`
70/// ends the loop within one pass. Returns the accumulated [`WorkerReport`].
71pub async fn run_worker<F, Fut, S>(config: WorkerConfig, shutdown: S, mut pass: F) -> WorkerReport
72where
73 F: FnMut() -> Fut,
74 Fut: Future<Output = PortResult<u64>>,
75 S: Future<Output = ()>,
76{
77 let mut report = WorkerReport::default();
78 let mut shutdown = std::pin::pin!(shutdown);
79
80 loop {
81 report.passes += 1;
82 let processed = match pass().await {
83 Ok(n) => {
84 report.processed += n;
85 n
86 }
87 Err(error) => {
88 report.errors += 1;
89 tracing::warn!(
90 target: "seiva::worker",
91 worker = %config.name,
92 error = %error,
93 "worker pass failed; continuing",
94 );
95 0
96 }
97 };
98
99 let wait = if config.drain_threshold > 0 && processed >= config.drain_threshold {
100 Duration::ZERO
101 } else {
102 config.interval
103 };
104
105 // Wait the interval, but stop at once if shutdown has fired (biased: it
106 // wins a tie, so a ready shutdown always ends the loop here).
107 tokio::select! {
108 biased;
109 _ = &mut shutdown => break,
110 _ = tokio::time::sleep(wait) => {}
111 }
112 }
113
114 tracing::info!(
115 target: "seiva::worker",
116 worker = %config.name,
117 passes = report.passes,
118 processed = report.processed,
119 errors = report.errors,
120 "worker stopped",
121 );
122 report
123}
124
125#[cfg(test)]
126mod tests {
127 use super::*;
128 use std::sync::atomic::{AtomicU64, Ordering};
129 use std::sync::Mutex;
130 use tokio::sync::oneshot;
131
132 fn immediate() -> WorkerConfig {
133 WorkerConfig::new("test", Duration::ZERO)
134 }
135
136 #[tokio::test]
137 async fn runs_passes_until_shutdown_and_accumulates_metrics() {
138 let (tx, rx) = oneshot::channel();
139 let tx = Mutex::new(Some(tx));
140 let calls = AtomicU64::new(0);
141
142 let report = run_worker(
143 immediate(),
144 async {
145 let _ = rx.await;
146 },
147 || {
148 // The third pass signals shutdown; the loop then ends after it.
149 if calls.fetch_add(1, Ordering::SeqCst) + 1 == 3 {
150 if let Some(tx) = tx.lock().unwrap().take() {
151 let _ = tx.send(());
152 }
153 }
154 async { Ok(10) }
155 },
156 )
157 .await;
158
159 assert_eq!(report.passes, 3);
160 assert_eq!(report.processed, 30);
161 assert_eq!(report.errors, 0);
162 }
163
164 #[tokio::test]
165 async fn an_erroring_pass_is_counted_and_not_fatal() {
166 let (tx, rx) = oneshot::channel();
167 let tx = Mutex::new(Some(tx));
168 let calls = AtomicU64::new(0);
169
170 let report = run_worker(
171 immediate(),
172 async {
173 let _ = rx.await;
174 },
175 || {
176 let n = calls.fetch_add(1, Ordering::SeqCst) + 1;
177 if n == 2 {
178 if let Some(tx) = tx.lock().unwrap().take() {
179 let _ = tx.send(());
180 }
181 }
182 async move {
183 if n == 1 {
184 Err("transient".into()) // first pass fails, worker continues
185 } else {
186 Ok(5)
187 }
188 }
189 },
190 )
191 .await;
192
193 assert_eq!(report.passes, 2);
194 assert_eq!(report.processed, 5);
195 assert_eq!(report.errors, 1);
196 }
197}