1use std::{error::Error as StdError, sync::Arc};
4
5use async_trait::async_trait;
6use regex::Regex;
7
8#[derive(Debug, PartialEq)]
10pub enum Status {
11 Closing,
13 Closed,
15 Connecting,
17 Connected,
19 Disconnected,
21}
22
23pub const QUEUE_NAME_PATTERN: &'static str = r"^[a-z0-9_-]+([\.]{1}[a-z0-9_-]+)*$";
25
26#[async_trait]
28pub trait GmqQueue: Send + Sync {
29 fn name(&self) -> &str;
31
32 fn is_recv(&self) -> bool;
34
35 fn status(&self) -> Status;
37
38 fn set_handler(&mut self, handler: Arc<dyn EventHandler>);
40
41 fn clear_handler(&mut self);
43
44 fn set_msg_handler(&mut self, handler: Arc<dyn MessageHandler>);
46
47 fn connect(&mut self) -> Result<(), Box<dyn StdError>>;
52
53 async fn close(&mut self) -> Result<(), Box<dyn StdError + Send + Sync>>;
55
56 async fn send_msg(&self, payload: Vec<u8>) -> Result<(), Box<dyn StdError + Send + Sync>>;
58}
59
60#[async_trait]
62pub trait Message: Send + Sync {
63 fn payload(&self) -> &[u8];
65
66 async fn ack(&self) -> Result<(), Box<dyn StdError + Send + Sync>>;
68
69 async fn nack(&self) -> Result<(), Box<dyn StdError + Send + Sync>>;
73}
74
75#[async_trait]
77pub trait EventHandler: Send + Sync {
78 async fn on_error(&self, queue: Arc<dyn GmqQueue>, err: Box<dyn StdError + Send + Sync>);
80
81 async fn on_status(&self, queue: Arc<dyn GmqQueue>, status: Status);
83}
84
85#[async_trait]
87pub trait MessageHandler: Send + Sync {
88 async fn on_message(&self, queue: Arc<dyn GmqQueue>, msg: Box<dyn Message>);
90}
91
92impl Copy for Status {}
93
94impl Clone for Status {
95 fn clone(&self) -> Status {
96 *self
97 }
98}
99
100pub(crate) fn name_validate(name: &str) -> bool {
102 let re = Regex::new(QUEUE_NAME_PATTERN).unwrap();
103 re.is_match(name)
104}