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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
//! Callback interfaces of asynchronous message for [`Connection`] and [`Channel`].
//!
//! In AMQP_0-9-1 protocol, some messages (`methods` in AMQP's term) can be initiated by server.
//! These messages are handled asynchronously by client via callbacks.
//!
//! User should define its own callback types and implement the traits [`ConnectionCallback`]
//! and [`ChannelCallback`].
//!
//! After open a connection, immediately register the callbacks by [`Connection::register_callback`].
//! After open a channel,  immediately register the callbacks by [`Channel::register_callback`].
//!
//! # Examples
//! See [`DefaultConnectionCallback`] and [`DefaultChannelCallback`] for simple example.
//!
//! The default callback implementations are only for demo and debugging purposes.
//! User is expected to implement its own callbacks.
//!
//! [`Connection`]: ../connection/struct.Connection.html
//! [`Connection::register_callback`]: ../connection/struct.Connection.html#method.register_callback
//! [`Channel`]: ../channel/struct.Channel.html
//! [`Channel::register_callback`]: ../channel/struct.Channel.html#method.register_callback

use std::str::from_utf8;

use super::{channel::Channel, connection::Connection};
use crate::api::Result;
use crate::frame::Cancel;
use crate::{
    frame::{Ack, Close, CloseChannel, Nack, Return},
    BasicProperties,
};
use async_trait::async_trait;
use tracing::{error, info};

/////////////////////////////////////////////////////////////////////////////
/// Callback interfaces for asynchronous `Connection` class message.
///
/// See [module][`self`] documentation for general guidelines.
#[async_trait]
pub trait ConnectionCallback {
    /// Callback to handle `close` connection request from server.
    ///
    /// Returns [`Ok`] to reply server that the request is received and
    /// handled properly.
    ///
    /// # Errors
    ///
    /// If returns [`Err`], no reply to server, which means server won't know
    /// whether the request has been received by client, and may consider
    /// the connection isn't shutdown.
    async fn close(&mut self, connection: &Connection, close: Close) -> Result<()>;

    /// Callback to handle connection `blocked` indication from server
    async fn blocked(&mut self, connection: &Connection, reason: String);

    /// Callback to handle connection `unblocked` indication from server
    async fn unblocked(&mut self, connection: &Connection);
}

/// Default type that implements `ConnectionCallback`.
///
/// For demo and debugging purpose only.
pub struct DefaultConnectionCallback;

#[async_trait]
impl ConnectionCallback for DefaultConnectionCallback {
    async fn close(&mut self, _connection: &Connection, close: Close) -> Result<()> {
        error!("{}!", close);
        Ok(())
    }

    async fn blocked(&mut self, _connection: &Connection, reason: String) {
        info!("connection blocked by server, reason: {}.", reason);
    }
    async fn unblocked(&mut self, _connection: &Connection) {
        info!("connection unblocked by server.");
    }
}

/////////////////////////////////////////////////////////////////////////////
///  Callback interfaces for asynchronous `Channel` class message.
///
/// See [module][`self`] documentation for general guidelines.
#[async_trait]
pub trait ChannelCallback {
    /// Callback to handle `close` channel request from server.
    ///
    /// Returns [`Ok`] to reply server that the request is received and
    /// handled properly.
    ///
    /// # Errors
    ///
    /// If returns [`Err`], no reply to server, which means server won't know
    /// whether the request has been received by client, and may consider
    /// the channel isn't closed.
    async fn close(&mut self, channel: &Channel, close: CloseChannel) -> Result<()>;

    /// Callback to handle server's request to `cancel` the consumer of current channel.
    ///
    /// Returns [`Ok`] to reply server that request has been received and
    /// the consumer will be cancelled.
    ///
    /// # Errors
    ///
    /// If returns [`Err`], no reply to server and no consumer will be cancelled.  
    async fn cancel(&mut self, channel: &Channel, cancel: Cancel) -> Result<()>;

    /// Callback to handle server's `flow` request to pause or restart
    /// the flow of sending content data.
    ///
    /// if `active` = [`true`], request to start, otherwise to pause.
    ///
    /// Returns [`true`] to indicate to server that client starts sending data.
    /// Returns [`false`] to indicate to server that client stops sending data.
    async fn flow(&mut self, channel: &Channel, active: bool) -> Result<bool>;

    /// Callback to handle `ack` indication from server.
    ///
    /// Only occurs in `publish confirm` mode, sent by server to acknowledges
    /// one or more messages published.
    async fn publish_ack(&mut self, channel: &Channel, ack: Ack);

    /// Callback to handle `nack` indication from server.
    ///
    /// Only occurs in `publish confirm` mode, sent by server to inform publisher
    /// of unhandled messages.
    async fn publish_nack(&mut self, channel: &Channel, nack: Nack);

    /// Callback to handle `return` indication with undeliverable message from server.
    ///
    /// The [ret][`Return`] contains the reason why the message is returned.
    ///
    /// The [basic_properties][`BasicProperties`] contains the propertities
    /// of the returned message.
    ///
    /// The [content][`Vec<u8>`] contains the body of the returned message.
    ///
    /// [`Return`]: ../struct.Return.html
    /// [`BasicProperties`]: ../struct.BasicProperties.html
    async fn publish_return(
        &mut self,
        channel: &Channel,
        ret: Return,
        basic_properties: BasicProperties,
        content: Vec<u8>,
    );
}

/// Default type that implements `ChannelCallback`.
///
/// For demo and debugging purpose only.
pub struct DefaultChannelCallback;

#[async_trait]
impl ChannelCallback for DefaultChannelCallback {
    async fn close(&mut self, _channel: &Channel, close: CloseChannel) -> Result<()> {
        error!("{}!", close);
        Ok(())
    }
    async fn cancel(&mut self, _channel: &Channel, cancel: Cancel) -> Result<()> {
        info!("receive cancel for consumer: {}.", cancel.consumer_tag());
        Ok(())
    }
    async fn flow(&mut self, _channel: &Channel, active: bool) -> Result<bool> {
        info!("channel flow request from server, {}.", active);
        Ok(true)
    }
    async fn publish_ack(&mut self, _channel: &Channel, ack: Ack) {
        info!("channel publish ack from server, {}.", ack.delivery_tag());
    }
    async fn publish_nack(&mut self, _channel: &Channel, nack: Nack) {
        info!("channel publish nack from server, {}.", nack.delivery_tag());
    }
    async fn publish_return(
        &mut self,
        _channel: &Channel,
        ret: Return,
        basic_properties: BasicProperties,
        content: Vec<u8>,
    ) {
        info!(">>>>> Publish Return Start <<<<<.");
        info!("{}.", ret);
        info!("{}.", basic_properties,);
        info!("{}.", from_utf8(&content).unwrap());
        info!(">>>>> Publish Return End <<<<<.");
    }
}