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
use super::subscribe_loop::{ChannelRx, ControlCommand, ControlTx, ListenerType, SubscriptionID};
use crate::data::message::Message;
use crate::runtime::Runtime;
use futures_channel::mpsc;
use futures_util::sink::SinkExt;
use futures_util::stream::Stream;
use futures_util::task::{Context, Poll};
use log::debug;
use std::pin::Pin;
#[derive(Debug)]
pub struct Subscription<TRuntime: Runtime> {
pub(crate) runtime: TRuntime,
pub(crate) name: ListenerType,
pub(crate) id: SubscriptionID,
pub(crate) control_tx: ControlTx,
pub(crate) channel_rx: ChannelRx,
}
impl<TRuntime: Runtime> Stream for Subscription<TRuntime> {
type Item = Message;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
Stream::poll_next(Pin::new(&mut self.get_mut().channel_rx), cx)
}
fn size_hint(&self) -> (usize, Option<usize>) {
Stream::size_hint(&self.channel_rx)
}
}
impl<TRuntime: Runtime> Subscription<TRuntime> {
fn drop_command(&self) -> ControlCommand {
ControlCommand::Drop(self.id, self.name.clone())
}
}
impl<TRuntime: Runtime> Drop for Subscription<TRuntime> {
fn drop(&mut self) {
debug!("Dropping Subscription: {:?}", self.name);
let command = self.drop_command();
let mut control_tx = self.control_tx.clone();
self.runtime.spawn(async move {
let drop_send_result = control_tx.send(command).await;
if is_drop_send_result_error(drop_send_result) {
panic!("Unable to unsubscribe");
}
});
}
}
fn is_drop_send_result_error(result: Result<(), mpsc::SendError>) -> bool {
match result {
Ok(_) => false,
Err(err @ mpsc::SendError { .. }) if err.is_disconnected() => {
false
}
_ => true,
}
}