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
use redis::{aio::ConnectionManager, AsyncCommands, ErrorKind, RedisError, RedisResult};
use snafu::{ResultExt, Snafu};
use std::time::Duration;

use super::{InputHandler, Method};
use crate::{internal_events::RedisReceiveEventError, sources::Source};

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

impl InputHandler {
    pub(super) async fn watch(mut self, method: Method) -> crate::Result<Source> {
        let mut conn = self
            .client
            .get_connection_manager()
            .await
            .context(ConnectionSnafu {})?;

        Ok(Box::pin(async move {
            let mut shutdown = self.cx.shutdown.clone();
            let mut retry: u32 = 0;
            loop {
                let res = match method {
                    Method::Rpop => tokio::select! {
                        res = brpop(&mut conn, &self.key) => res,
                        _ = &mut shutdown => break
                    },
                    Method::Lpop => tokio::select! {
                        res = blpop(&mut conn, &self.key) => res,
                        _ = &mut shutdown => break
                    },
                };

                match res {
                    Err(error) => {
                        let err: RedisError = error;
                        let kind = err.kind();

                        emit!(RedisReceiveEventError::from(err));

                        if kind == ErrorKind::IoError {
                            retry += 1;
                            backoff_exponential(retry).await
                        }
                    }
                    Ok(line) => {
                        if retry > 0 {
                            retry = 0
                        }
                        if let Err(()) = self.handle_line(line).await {
                            break;
                        }
                    }
                }
            }
            Ok(())
        }))
    }
}

async fn backoff_exponential(exp: u32) {
    let ms = if exp <= 4 { 2_u64.pow(exp + 5) } else { 1000 };
    tokio::time::sleep(Duration::from_millis(ms)).await;
}

async fn brpop(conn: &mut ConnectionManager, key: &str) -> RedisResult<String> {
    conn.brpop(key, 0.0)
        .await
        .map(|(_, value): (String, String)| value)
}

async fn blpop(conn: &mut ConnectionManager, key: &str) -> RedisResult<String> {
    conn.blpop(key, 0.0)
        .await
        .map(|(_, value): (String, String)| value)
}