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
use futures_util::StreamExt;
use snafu::{ResultExt, Snafu};

use crate::{
    internal_events::RedisReceiveEventError,
    sources::{
        redis::{ConnectionInfo, InputHandler},
        Source,
    },
};

#[derive(Debug, Snafu)]
enum BuildError {
    #[snafu(display("Failed to create connection: {}", source))]
    Connection { source: redis::RedisError },
    #[snafu(display("Failed to subscribe to channel: {}", source))]
    Subscribe { source: redis::RedisError },
}

impl InputHandler {
    pub(super) async fn subscribe(
        mut self,
        connection_info: ConnectionInfo,
    ) -> crate::Result<Source> {
        let conn = self
            .client
            .get_async_connection()
            .await
            .context(ConnectionSnafu {})?;

        trace!(endpoint = %connection_info.endpoint.as_str(), "Connected.");

        let mut pubsub_conn = conn.into_pubsub();
        pubsub_conn
            .subscribe(&self.key)
            .await
            .context(SubscribeSnafu {})?;
        trace!(endpoint = %connection_info.endpoint.as_str(), channel = %self.key, "Subscribed to channel.");

        Ok(Box::pin(async move {
            let shutdown = self.cx.shutdown.clone();
            let mut pubsub_stream = pubsub_conn.on_message().take_until(shutdown);
            while let Some(msg) = pubsub_stream.next().await {
                match msg.get_payload::<String>() {
                    Ok(line) => {
                        if let Err(()) = self.handle_line(line).await {
                            break;
                        }
                    }
                    Err(error) => emit!(RedisReceiveEventError::from(error)),
                }
            }
            Ok(())
        }))
    }
}