use std::marker::PhantomData; use std::{fmt::Debug, future::Future}; use tokio::sync::{broadcast, mpsc::UnboundedSender}; use super::{Interrupted, Share}; pub type EmptyProcessors = Vec; /// A task that can be run. pub trait Task: Debug + Send + Sync + 'static { type Return; fn run(&self) -> anyhow::Result>; } /// A processor that can be added to the application environment. /// Processors will receive application messages and can produce new ones. pub trait Process { fn process(&mut self, _message: M) -> impl Future>> + Send; } /// An empty processor that does nothing. #[derive(Debug, Clone)] pub struct EmptyProcessor; impl Process for EmptyProcessor { async fn process(&mut self, _message: M) -> anyhow::Result> { Ok(vec![]) } } /// A worker that is spawned by the application. Invokes /// all processors and sends received application messages. pub struct Worker { work_tx: UnboundedSender, _phantom: PhantomData<(P, M, R)>, } impl Worker where P: Process + Share, M: Share, R: Share, { pub fn new(tx: UnboundedSender) -> Self { Self { work_tx: tx, _phantom: PhantomData, } } pub async fn run( &self, processors: Vec

, mut message_rx: broadcast::Receiver, mut interrupt_rx: broadcast::Receiver>, ) -> anyhow::Result> { let result = loop { tokio::select! { Ok(message) = message_rx.recv() => { for mut p in processors.clone() { for m in p.process(message.clone()).await? { if let Err(err) = self.work_tx.send(m) { log::error!(target: "worker", "Unable to send message: {err}") } } } }, // Catch and handle interrupt signal to gracefully shutdown Ok(interrupted) = interrupt_rx.recv() => { break interrupted; } } }; Ok(result) } }