Skip to main content

relay_system/service/
simple.rs

1use std::sync::Arc;
2
3use crate::{Interface, Service};
4
5/// A service that handles messages one at a time.
6///
7/// When the message handler cannot keep up with incoming messages,
8/// it applies backpressure into the input queue.
9pub struct SimpleService<T>(T);
10
11impl<T: MessageHandler> SimpleService<T> {
12    /// Wraps a message handler in a service loop.
13    pub fn from_message_handler(message_handler: T) -> Self {
14        Self(message_handler)
15    }
16}
17
18impl<T: MessageHandler + Send + 'static> Service for SimpleService<T> {
19    type Interface = T::Interface;
20
21    async fn run(self, mut rx: super::Receiver<Self::Interface>) {
22        while let Some(message) = rx.recv().await {
23            self.0.handle_message(message).await;
24        }
25    }
26}
27
28/// Basic building block for composing services.
29pub trait MessageHandler {
30    /// The message interface (see [`Service::Interface`]).
31    type Interface: Interface;
32
33    /// The asynchronous message handler for this service.
34    fn handle_message(&self, message: Self::Interface) -> impl Future<Output = ()> + Send;
35
36    /// The name of the message handler.
37    fn name() -> &'static str {
38        std::any::type_name::<Self>()
39    }
40}
41
42impl<T: MessageHandler + ?Sized> MessageHandler for Arc<T> {
43    type Interface = T::Interface;
44
45    fn handle_message(&self, message: Self::Interface) -> impl Future<Output = ()> + Send {
46        self.as_ref().handle_message(message)
47    }
48
49    fn name() -> &'static str {
50        std::any::type_name::<T>() // use inner name
51    }
52}