general_mq/
connection.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//! Traits and enumerations for connections.

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

use async_trait::async_trait;

/// Connection status.
#[derive(Debug, PartialEq)]
pub enum Status {
    /// The connection is closing.
    Closing,
    /// The connection is closed by the program.
    Closed,
    /// Connecting to the message broker.
    Connecting,
    /// Connected to the message broker.
    Connected,
    /// The connection is not connected. It will retry connecting to the broker automatically.
    Disconnected,
}

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

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

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

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

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

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

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

impl Copy for Status {}

impl Clone for Status {
    fn clone(&self) -> Status {
        *self
    }
}