#![forbid(unsafe_code)]
use std::future::Future;
use std::time::Duration;
use seiva_ports::PortResult;
#[derive(Debug, Clone)]
pub struct WorkerConfig {
pub name: String,
pub interval: Duration,
pub drain_threshold: u64,
}
impl WorkerConfig {
pub fn new(name: impl Into<String>, interval: Duration) -> Self {
Self {
name: name.into(),
interval,
drain_threshold: 0,
}
}
pub fn drain_fast_at(mut self, threshold: u64) -> Self {
self.drain_threshold = threshold;
self
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct WorkerReport {
pub passes: u64,
pub processed: u64,
pub errors: u64,
}
pub async fn run_worker<F, Fut, S>(config: WorkerConfig, shutdown: S, mut pass: F) -> WorkerReport
where
F: FnMut() -> Fut,
Fut: Future<Output = PortResult<u64>>,
S: Future<Output = ()>,
{
let mut report = WorkerReport::default();
let mut shutdown = std::pin::pin!(shutdown);
loop {
report.passes += 1;
let processed = match pass().await {
Ok(n) => {
report.processed += n;
n
}
Err(error) => {
report.errors += 1;
tracing::warn!(
target: "seiva::worker",
worker = %config.name,
error = %error,
"worker pass failed; continuing",
);
0
}
};
let wait = if config.drain_threshold > 0 && processed >= config.drain_threshold {
Duration::ZERO
} else {
config.interval
};
tokio::select! {
biased;
_ = &mut shutdown => break,
_ = tokio::time::sleep(wait) => {}
}
}
tracing::info!(
target: "seiva::worker",
worker = %config.name,
passes = report.passes,
processed = report.processed,
errors = report.errors,
"worker stopped",
);
report
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Mutex;
use tokio::sync::oneshot;
fn immediate() -> WorkerConfig {
WorkerConfig::new("test", Duration::ZERO)
}
#[tokio::test]
async fn runs_passes_until_shutdown_and_accumulates_metrics() {
let (tx, rx) = oneshot::channel();
let tx = Mutex::new(Some(tx));
let calls = AtomicU64::new(0);
let report = run_worker(
immediate(),
async {
let _ = rx.await;
},
|| {
if calls.fetch_add(1, Ordering::SeqCst) + 1 == 3 {
if let Some(tx) = tx.lock().unwrap().take() {
let _ = tx.send(());
}
}
async { Ok(10) }
},
)
.await;
assert_eq!(report.passes, 3);
assert_eq!(report.processed, 30);
assert_eq!(report.errors, 0);
}
#[tokio::test]
async fn an_erroring_pass_is_counted_and_not_fatal() {
let (tx, rx) = oneshot::channel();
let tx = Mutex::new(Some(tx));
let calls = AtomicU64::new(0);
let report = run_worker(
immediate(),
async {
let _ = rx.await;
},
|| {
let n = calls.fetch_add(1, Ordering::SeqCst) + 1;
if n == 2 {
if let Some(tx) = tx.lock().unwrap().take() {
let _ = tx.send(());
}
}
async move {
if n == 1 {
Err("transient".into()) } else {
Ok(5)
}
}
},
)
.await;
assert_eq!(report.passes, 2);
assert_eq!(report.processed, 5);
assert_eq!(report.errors, 1);
}
}