Skip to main content

eventail/
endpoint.rs

1/*!
2The Enpoint API.
3
4This API is used to start and manage a new endpoint, aka service, and to publish on the EDA Bus.
5
6# Quickstart
7
8```
9use eventail::endpoint::{Config, Endpoint};
10
11#[tokio::main]
12async fn main() {
13
14    let config = Config {
15        prefetch_count: 3,
16        logical_service: String::from("my_service_name"),
17        hosts: vec![String::from("amqp://localhost")],
18        event_subscriptions: vec![],
19        command_subscriptions: vec![],
20        configuration_subscriptions: vec![],
21    };
22    let (endpoint, _client_rx) = Endpoint::new(config);
23    // do something
24    // ...
25    endpoint
26        .shutdown()
27        .await
28        .expect("problem when shutting down the service!");
29}
30```
31*/
32
33use log::debug;
34use serde::Serialize;
35
36use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, error, unbounded_channel};
37use tokio::task::{JoinError, JoinHandle};
38
39mod gelf;
40mod manager;
41pub(crate) mod shipment;
42
43pub use super::Delivery;
44pub use gelf::Criticity;
45pub use gelf::ExtraFields;
46use gelf::GelfPayload;
47use manager::{EndpointManager, Message, run};
48use shipment::Shipment;
49
50#[derive(Debug)]
51pub enum Error {
52    EndpointDown,
53    Shutdown(JoinError),
54}
55
56impl From<error::SendError<Message>> for Error {
57    fn from(_value: error::SendError<Message>) -> Self {
58        Self::EndpointDown
59    }
60}
61
62impl From<JoinError> for Error {
63    fn from(value: JoinError) -> Self {
64        Self::Shutdown(value)
65    }
66}
67
68/// Events sent by the endpoint and consumed by the user code.
69#[derive(Debug)]
70pub enum ClientMessage {
71    ClockTicked(u64),
72    CommandReceived(Box<Delivery>),
73    ConfigurationReceived(Box<Delivery>),
74    EventReceived(Box<Delivery>),
75    MessageReturned(String),
76    Ready,
77    ResultReceived(Box<Delivery>),
78    WaitingForConfiguration,
79}
80
81/// Configure the Enpoint.
82pub struct Config {
83    pub prefetch_count: u16,
84    pub hosts: Vec<String>,
85    pub logical_service: String,
86    pub event_subscriptions: Vec<String>,
87    pub command_subscriptions: Vec<String>,
88    pub configuration_subscriptions: Vec<String>,
89}
90
91/// The endpoint handle implements the EDA API
92#[derive(Clone)]
93pub struct EndpointHandle {
94    endpoint_tx: UnboundedSender<Message>,
95    pub force_json: bool,
96    logical_service: String,
97    host: String,
98}
99
100/// The master endpoint API.
101pub struct Endpoint {
102    api: EndpointHandle,
103    manager_handle: JoinHandle<()>,
104}
105
106impl Endpoint {
107    /// Create and start a new master endpoint.
108    ///
109    /// A background task is launched that manages the connection and the topology and automatically
110    /// switches over or reconnects in case of network or broker failure.
111    /// Return an `Endpoint` and a channel receiver for EDA and local messages.
112    /// The background task should be cleanly shutdown when not needed anymore with the [`Self::shutdown()`] method.
113    ///
114    /// To use the Endpoint API, the client code should request a [`EndpointHandle`] with the [`Self::new_handle()`] method.
115    pub fn new(config: Config) -> (Self, UnboundedReceiver<ClientMessage>) {
116        let (endpoint_tx, endpoint_rx) = unbounded_channel();
117        let (client_tx, client_rx) = unbounded_channel();
118        let manager = EndpointManager::new(endpoint_tx.clone(), endpoint_rx, client_tx);
119        let logical_service = config.logical_service.clone();
120        let manager_handle = run(manager, config);
121        (
122            Self {
123                manager_handle,
124                api: EndpointHandle {
125                    endpoint_tx,
126                    force_json: false,
127                    logical_service,
128                    host: gethostname::gethostname().into_string().unwrap(),
129                },
130            },
131            client_rx,
132        )
133    }
134
135    /// Create a new handle.
136    pub fn new_handle(&self) -> EndpointHandle {
137        self.api.clone()
138    }
139
140    /// Shutdown the endpoint gracefully.
141    pub async fn shutdown(self) -> Result<(), Error> {
142        self.api.endpoint_tx.send(Message::Shutdown)?;
143        self.manager_handle.await?;
144        Ok(())
145    }
146}
147
148impl EndpointHandle {
149    /// Send a new Event on the EDA bus.
150    ///
151    /// * `event` is the name (class name) of the event;
152    /// * `message` is the event payload;
153    /// * `conversation_id` is the mandatory conversation ID;
154    /// * if `mandatory` is true, a `ClientMessage::MessageReturned(_)` will be sent if the event is
155    ///   unroutable, that is, the exchange did not find any queue to put it in.
156    pub fn publish_event(
157        &self,
158        event: &str,
159        message: &impl Serialize,
160        conversation_id: &str,
161        mandatory: bool,
162    ) -> Result<(), Error> {
163        Ok(self
164            .endpoint_tx
165            .send(Message::PublishMain(Box::new(Shipment::new_event(
166                event,
167                message,
168                conversation_id,
169                mandatory,
170                self.force_json,
171            ))))?)
172    }
173
174    /// Send a new Configuration or Configuration Request on the EDA bus.
175    ///
176    /// * `event` is the name (class name) of the message;
177    /// * `message` is the message payload;
178    /// * `conversation_id` is the mandatory conversation ID;
179    pub fn publish_configuration(
180        &self,
181        event: &str,
182        message: &impl Serialize,
183        conversation_id: &str,
184    ) -> Result<(), Error> {
185        Ok(self
186            .endpoint_tx
187            .send(Message::PublishMain(Box::new(Shipment::new_configuration(
188                event,
189                message,
190                conversation_id,
191                self.force_json,
192            ))))?)
193    }
194
195    /// Send a new Command on the EDA bus.
196    ///
197    /// * `command` is the name (class name) of the command;
198    /// * `message` is the command payload;
199    /// * `conversation_id` is the mandatory conversation ID;
200    /// * `reply_to`: is the routing key to send the result to;
201    /// * `correlation_id`: is the mandatory correlation ID used to reconcile the result with the command;
202    /// * if `mandatory` is true, a `ClientMessage::MessageReturned(_)` will be sent if the command is
203    ///   unroutable, that is, the exchange did not find any queue to put it in.
204    pub fn send_command(
205        &self,
206        command: &str,
207        message: &impl Serialize,
208        conversation_id: &str,
209        reply_to: &str,
210        correlation_id: &str,
211        mandatory: bool,
212    ) -> Result<(), Error> {
213        Ok(self
214            .endpoint_tx
215            .send(Message::PublishMain(Box::new(Shipment::new_command(
216                command,
217                message,
218                conversation_id,
219                reply_to,
220                correlation_id,
221                mandatory,
222                self.force_json,
223            ))))?)
224    }
225
226    /// Send a new successful Result on the EDA bus.
227    ///
228    /// * `destination` is routing key to which the result is to be sent;
229    /// * `message` is the result payload;
230    /// * `conversation_id` is the mandatory conversation ID;
231    /// * `correlation_id`: is the mandatory correlation ID used to reconcile the result with the command;
232    /// * if `mandatory` is true, a `ClientMessage::MessageReturned(_)` will be sent if the result is
233    ///   unroutable, that is, the exchange did not find any queue to put it in.
234    pub fn return_success(
235        &self,
236        destination: &str,
237        message: &impl Serialize,
238        conversation_id: &str,
239        correlation_id: &str,
240        mandatory: bool,
241    ) -> Result<(), Error> {
242        Ok(self
243            .endpoint_tx
244            .send(Message::PublishMain(Box::new(Shipment::new_result(
245                destination,
246                "success",
247                message,
248                conversation_id,
249                correlation_id,
250                mandatory,
251                self.force_json,
252            ))))?)
253    }
254
255    /// Send a new failure Result on the EDA bus.
256    ///
257    /// * `destination` is routing key to which the result is to be sent;
258    /// * `message` is the result payload;
259    /// * `conversation_id` is the mandatory conversation ID;
260    /// * `correlation_id`: is the mandatory correlation ID used to reconcile the result with the command;
261    /// * if `mandatory` is true, a `ClientMessage::MessageReturned(_)` will be sent if the result is
262    ///   unroutable, that is, the exchange did not find any queue to put it in.
263    pub fn return_error(
264        &self,
265        destination: &str,
266        message: &impl Serialize,
267        conversation_id: &str,
268        correlation_id: &str,
269        mandatory: bool,
270    ) -> Result<(), Error> {
271        Ok(self
272            .endpoint_tx
273            .send(Message::PublishMain(Box::new(Shipment::new_result(
274                destination,
275                "error",
276                message,
277                conversation_id,
278                correlation_id,
279                mandatory,
280                self.force_json,
281            ))))?)
282    }
283
284    /// Log on the EDA log bus with custom fields.
285    pub fn log_with_extra_fields(
286        &self,
287        criticity: Criticity,
288        short_message: &str,
289        full_message: &str,
290        conversation_id: &str,
291        extra_fields: ExtraFields,
292    ) -> Result<(), Error> {
293        debug!("{}: {short_message}\n{full_message}", criticity.label());
294        let payload = GelfPayload::new(
295            criticity,
296            short_message,
297            full_message,
298            conversation_id,
299            &self.logical_service,
300            &self.host,
301            extra_fields,
302        );
303        Ok(self
304            .endpoint_tx
305            .send(Message::PublishLog(Box::new(Shipment::new_log(
306                &payload.routing_key(),
307                &payload,
308                conversation_id,
309            ))))?)
310    }
311
312    /// Log on the EDA log bus
313    pub fn log(
314        &self,
315        criticity: Criticity,
316        short_message: &str,
317        full_message: &str,
318        conversation_id: &str,
319    ) -> Result<(), Error> {
320        self.log_with_extra_fields(
321            criticity,
322            short_message,
323            full_message,
324            conversation_id,
325            ExtraFields::new(),
326        )
327    }
328
329    /// Tell the endpoint that the client is configured and ready to accept events and commands.
330    ///
331    /// You don't need to call this method explicitly if you use the [`Callback API`](crate::service).
332    pub fn configured(&self) -> Result<(), Error> {
333        self.endpoint_tx.send(Message::Configured)?;
334        Ok(())
335    }
336
337    /// Tell the broker to immediately remove the message from the queue.
338    ///
339    /// Use this method only if there is no pending publishes triggered by this message.
340    /// If unsure, use [`Self::delivery_processed()`] instead.
341    pub fn ack_delivery(&self, delivery_tag: u64) -> Result<(), Error> {
342        self.endpoint_tx.send(Message::AckDelivery(delivery_tag))?;
343        Ok(())
344    }
345
346    /// Tell the endpoint that the message was successfully processed and can be safely removed from the queue
347    /// when all current publishing is actually done.
348    ///
349    /// You don't need to call this method explicitly if you use the [`Callback API`](crate::service).
350    pub fn delivery_processed(&self, delivery_tag: u64) -> Result<(), Error> {
351        self.endpoint_tx
352            .send(Message::DeliveryProcessed(delivery_tag))?;
353        Ok(())
354    }
355
356    /// Tell the broker that the message was not properly handled (transient error) and should be requeued to
357    /// be retried later.
358    ///
359    /// You don't need to call this method explicitly if you use the [`Callback API`](crate::service).
360    pub fn nack_delivery(&self, delivery_tag: u64) -> Result<(), Error> {
361        self.endpoint_tx.send(Message::NackDelivery(delivery_tag))?;
362        Ok(())
363    }
364
365    /// Tell the broker that the message in unprocessable and must be rejected (to dead-letter).
366    ///
367    /// You don't need to call this method explicitly if you use the [`Callback API`](crate::service).
368    pub fn reject_delivery(&self, delivery_tag: u64) -> Result<(), Error> {
369        self.endpoint_tx
370            .send(Message::RejectDelivery(delivery_tag))?;
371        Ok(())
372    }
373}