Skip to main content

eventail/
service.rs

1//! Callback API and helpers for implementing services.
2//!
3
4use log::error;
5use tokio::sync::mpsc::UnboundedReceiver;
6
7use super::delivery::{Delivery, Error as DError};
8use super::endpoint::{ClientMessage as Message, Criticity, EndpointHandle, Error as EError};
9
10/// Error type for message handlers.
11/// In case of recoverable error, the error is logged and the message is requeued (only once).
12/// In case of critical error, the error is logged and the message is rejected to the dead-letter.
13pub enum Error {
14    Recoverable(String),
15    Critical(String),
16}
17
18impl From<DError> for Error {
19    fn from(value: DError) -> Self {
20        match value {
21            DError::Deserialization(msg) => Self::Critical(msg),
22        }
23    }
24}
25
26impl From<EError> for Error {
27    fn from(_value: EError) -> Self {
28        Self::Recoverable("EndpointHandle is down?".to_owned())
29    }
30}
31
32/// The traditional Callback API
33///
34/// A service should be run with [`run_service`].
35pub trait Service {
36    /// Called when the EndpointHandle starts consuming the subscribed messages.
37    fn on_ready(&mut self, endpoint: &EndpointHandle);
38    /// Called when the EndpointHandle is connected and Configuration events were subscribed.
39    ///
40    /// Usually, the implementation publishes a configuration request event on the EDA Bus.
41    fn on_waiting_for_configuration(&mut self, endpoint: &EndpointHandle);
42    /// Called when a subscribed configuration event is received.
43    ///
44    /// The implementation returns `Ok(true)` only if it is fully configured and ready to
45    /// consume business events.
46    fn on_configuration(
47        &mut self,
48        endpoint: &EndpointHandle,
49        message: Box<Delivery>,
50    ) -> Result<bool, Error>;
51    /// Called when a subscribed event is received.
52    ///
53    /// If an [`Error`] is returned, the message is acknowledged accordingly.
54    fn on_event(&mut self, endpoint: &EndpointHandle, message: Box<Delivery>) -> Result<(), Error>;
55    /// Called when a subscribed command is received.
56    ///
57    /// If an [`Error`] is returned, the message is acknowledged accordingly.
58    fn on_command(
59        &mut self,
60        endpoint: &EndpointHandle,
61        message: Box<Delivery>,
62    ) -> Result<(), Error>;
63    /// Called when a subscribed result is received.
64    ///
65    /// If an [`Error`] is returned, the message is acknowledged accordingly.
66    fn on_result(&mut self, endpoint: &EndpointHandle, message: Box<Delivery>)
67    -> Result<(), Error>;
68    /// Called when a message sent with the `mandatory` flag true is unroutable.
69    fn on_message_returned(&mut self, endpoint: &EndpointHandle, routing_key: String);
70    /// This method is called every second with the `time` elapsed seconds since the endpoint was started.
71    fn on_clock_ticked(&mut self, endpoint: &EndpointHandle, time: u64);
72}
73
74/// Run the service forever, consuming the [`Message`] events and triggering the callbacks.
75pub async fn run_service<T: Service>(
76    mut service: T,
77    endpoint: EndpointHandle,
78    mut client_rx: UnboundedReceiver<Message>,
79) {
80    while let Some(message) = client_rx.recv().await {
81        match message {
82            Message::ClockTicked(time) => service.on_clock_ticked(&endpoint, time),
83            Message::CommandReceived(msg) => {
84                safely_apply_sync(&endpoint, msg, |e, d| service.on_command(e, d))
85                    .unwrap_or_else(|_| error!("EndpointHandle dropped!"));
86            }
87            Message::ConfigurationReceived(msg) => {
88                safely_manage_configuration_sync(&endpoint, msg, |e, d| {
89                    service.on_configuration(e, d)
90                })
91                .unwrap_or_else(|_| error!("EndpointHandle dropped!"));
92            }
93            Message::EventReceived(msg) => {
94                safely_apply_sync(&endpoint, msg, |e, d| service.on_event(e, d))
95                    .unwrap_or_else(|_| error!("EndpointHandle dropped!"));
96            }
97            Message::MessageReturned(routing_key) => {
98                service.on_message_returned(&endpoint, routing_key)
99            }
100            Message::Ready => service.on_ready(&endpoint),
101            Message::ResultReceived(msg) => {
102                safely_apply_sync(&endpoint, msg, |e, d| service.on_result(e, d))
103                    .unwrap_or_else(|_| error!("EndpointHandle dropped!"));
104            }
105            Message::WaitingForConfiguration => service.on_waiting_for_configuration(&endpoint),
106        }
107    }
108}
109
110/// Execute the synchronous `callback` to process the `delivery` in a transaction like manner.
111/// The `delivery` is ACKed, NACKed (and requeued) or REJECTed depending on the `Error` returned.
112pub fn safely_apply_sync<F>(
113    endpoint: &EndpointHandle,
114    delivery: Box<Delivery>,
115    callback: F,
116) -> Result<(), EError>
117where
118    F: FnOnce(&EndpointHandle, Box<Delivery>) -> Result<(), Error>,
119{
120    let delivery_tag = delivery.tag();
121    let message_type = delivery.routing_key().to_owned();
122    let conversation_id = delivery.conversation_id().unwrap().to_owned();
123    let redelivered = delivery.redelivered();
124    match callback(endpoint, delivery) {
125        Ok(_) => endpoint.delivery_processed(delivery_tag),
126        Err(Error::Recoverable(msg)) => {
127            endpoint.log(
128                Criticity::Alert,
129                &format!("Error processing {message_type}"),
130                &msg,
131                &conversation_id,
132            )?;
133            if redelivered {
134                endpoint.log(
135                    Criticity::Emergency,
136                    &format!("Too many retries for {message_type}; giving up!"),
137                    "rejecting message",
138                    &conversation_id,
139                )?;
140                endpoint.reject_delivery(delivery_tag)
141            } else {
142                endpoint.nack_delivery(delivery_tag)
143            }
144        }
145        Err(Error::Critical(msg)) => {
146            endpoint.log(
147                Criticity::Emergency,
148                &format!("Unrecoverable error processing {message_type}; giving up!"),
149                &msg,
150                &conversation_id,
151            )?;
152            endpoint.reject_delivery(delivery_tag)
153        }
154    }
155}
156
157pub fn safely_manage_configuration_sync<F>(
158    endpoint: &EndpointHandle,
159    delivery: Box<Delivery>,
160    mut callback: F,
161) -> Result<(), EError>
162where
163    F: FnMut(&EndpointHandle, Box<Delivery>) -> Result<bool, Error>,
164{
165    let delivery_tag = delivery.tag();
166    let message_type = delivery.routing_key().to_owned();
167    let conversation_id = delivery.conversation_id().unwrap_or("").to_owned();
168    match callback(endpoint, delivery) {
169        Ok(configured) => {
170            endpoint.ack_delivery(delivery_tag)?;
171            if configured {
172                endpoint.configured()?;
173            }
174            Ok(())
175        }
176        Err(Error::Critical(msg)) | Err(Error::Recoverable(msg)) => {
177            endpoint.log(
178                Criticity::Emergency,
179                &format!("Error processing configuration {message_type}; giving up!"),
180                &msg,
181                &conversation_id,
182            )?;
183            endpoint.reject_delivery(delivery_tag)
184        }
185    }
186}
187
188/// Execute the async `callback` to process the `delivery` in a transaction like manner.
189/// The `delivery` is ACKed, NACKed (and requeued) or REJECTed depending on the `Error` returned.
190pub async fn safely_apply<'a, F, Fut>(
191    endpoint: &'a EndpointHandle,
192    delivery: Box<Delivery>,
193    callback: F,
194) -> Result<(), EError>
195where
196    F: FnOnce(&'a EndpointHandle, Box<Delivery>) -> Fut,
197    Fut: std::future::Future<Output = Result<(), Error>>,
198{
199    let delivery_tag = delivery.tag();
200    let message_type = delivery.routing_key().to_owned();
201    let conversation_id = delivery.conversation_id().unwrap().to_owned();
202    let redelivered = delivery.redelivered();
203    match callback(endpoint, delivery).await {
204        Ok(_) => endpoint.delivery_processed(delivery_tag),
205        Err(Error::Recoverable(msg)) => {
206            endpoint.log(
207                Criticity::Alert,
208                &format!("Error processing {message_type}"),
209                &msg,
210                &conversation_id,
211            )?;
212            if redelivered {
213                endpoint.log(
214                    Criticity::Emergency,
215                    &format!("Too many retries for {message_type}; giving up!"),
216                    "rejecting message",
217                    &conversation_id,
218                )?;
219                endpoint.reject_delivery(delivery_tag)
220            } else {
221                endpoint.nack_delivery(delivery_tag)
222            }
223        }
224        Err(Error::Critical(msg)) => {
225            endpoint.log(
226                Criticity::Emergency,
227                &format!("Unrecoverable error processing {message_type}; giving up!"),
228                &msg,
229                &conversation_id,
230            )?;
231            endpoint.reject_delivery(delivery_tag)
232        }
233    }
234}