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
use super::RillClient;
use derive_more::From;
use futures::task::{Context, Poll};
use futures::{channel::mpsc, Stream};
use meio::{Address, InstantAction, Interaction, InteractionTask};
use rill_protocol::client::ClientReqId;
use rill_protocol::provider::{Path, RillEvent};
use std::pin::Pin;

#[derive(Debug, From)]
pub struct ClientLink {
    address: Address<RillClient>,
}

pub struct Subscription {
    req_id: ClientReqId,
    receiver: mpsc::Receiver<Vec<RillEvent>>,
    client: Address<RillClient>,
}

impl Stream for Subscription {
    type Item = Vec<RillEvent>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        Pin::new(&mut self.receiver).poll_next(cx)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.receiver.size_hint()
    }
}

impl Subscription {
    pub(super) fn new(
        req_id: ClientReqId,
        receiver: mpsc::Receiver<Vec<RillEvent>>,
        client: Address<RillClient>,
    ) -> Self {
        Self {
            req_id,
            receiver,
            client,
        }
    }
}

pub(crate) struct UnsubscribeFromPath {
    pub req_id: ClientReqId,
}

impl InstantAction for UnsubscribeFromPath {}

/// Asks to close a stream when receiver was closed.
impl Drop for Subscription {
    fn drop(&mut self) {
        let msg = UnsubscribeFromPath {
            req_id: self.req_id,
        };
        if let Err(err) = self.client.instant(msg) {
            log::error!("Can't unsubscribe {:?}: {}", self.req_id, err);
        }
    }
}

pub struct SubscribeToPath {
    pub path: Path,
}

impl Interaction for SubscribeToPath {
    type Output = Subscription;
}

impl ClientLink {
    pub fn subscribe_to_path(&mut self, path: Path) -> InteractionTask<SubscribeToPath> {
        let msg = SubscribeToPath { path };
        self.address.interact(msg)
    }
}