1
//! Traits and enumerations for connections.
2

            
3
use std::{error::Error as StdError, sync::Arc};
4

            
5
use async_trait::async_trait;
6

            
7
/// Connection status.
8
#[derive(Debug, PartialEq)]
9
pub enum Status {
10
    /// The connection is closing.
11
    Closing,
12
    /// The connection is closed by the program.
13
    Closed,
14
    /// Connecting to the message broker.
15
    Connecting,
16
    /// Connected to the message broker.
17
    Connected,
18
    /// The connection is not connected. It will retry connecting to the broker automatically.
19
    Disconnected,
20
}
21

            
22
/// The operations for connections.
23
#[async_trait]
24
pub trait GmqConnection: Send + Sync {
25
    /// To get the connection status.
26
    fn status(&self) -> Status;
27

            
28
    /// To add a connection event handler. This will return an identifier for applications to manage
29
    /// handlers.
30
    fn add_handler(&mut self, handler: Arc<dyn EventHandler>) -> String;
31

            
32
    /// To remove a handler with an idenfier from [`GmqConnection::add_handler`].
33
    fn remove_handler(&mut self, id: &str);
34

            
35
    /// To connect to the message broker. The [`GmqConnection`] will connect to the broker using
36
    /// another runtime task and report status with [`Status`]s.
37
    fn connect(&mut self) -> Result<(), Box<dyn StdError>>;
38

            
39
    /// To close the connection.
40
    async fn close(&mut self) -> Result<(), Box<dyn StdError + Send + Sync>>;
41
}
42

            
43
/// The event handler for connections.
44
#[async_trait]
45
pub trait EventHandler: Send + Sync {
46
    /// Triggered when there are errors.
47
    async fn on_error(
48
        &self,
49
        handler_id: String,
50
        conn: Arc<dyn GmqConnection>,
51
        err: Box<dyn StdError + Send + Sync>,
52
    );
53

            
54
    /// Triggered by [`Status`].
55
    async fn on_status(&self, handler_id: String, conn: Arc<dyn GmqConnection>, status: Status);
56
}
57

            
58
impl Copy for Status {}
59

            
60
impl Clone for Status {
61
    fn clone(&self) -> Status {
62
        *self
63
    }
64
}