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
use std::fmt::Debug;
use std::num::NonZeroUsize;
use std::time::Duration;

use tokio::{sync::mpsc::UnboundedReceiver, time::interval};

use crate::{client::NoopClient, dispatch::LogEvent, CloudWatchClient};

#[derive(Debug, Clone)]
pub struct ExportConfig {
    batch_size: NonZeroUsize,
    interval: Duration,
    destination: LogDestination,
}

#[derive(Debug, Clone, Default)]
pub struct LogDestination {
    pub log_group_name: String,
    pub log_stream_name: String,
}

impl Default for ExportConfig {
    fn default() -> Self {
        Self {
            batch_size: NonZeroUsize::new(5).unwrap(),
            interval: Duration::from_secs(5),
            destination: LogDestination::default(),
        }
    }
}

impl ExportConfig {
    pub fn with_batch_size<T>(self, batch_size: T) -> Self
    where
        T: TryInto<NonZeroUsize>,
        <T as TryInto<NonZeroUsize>>::Error: Debug,
    {
        Self {
            batch_size: batch_size
                .try_into()
                .expect("batch size must be greater than or equal to 1"),
            ..self
        }
    }

    pub fn with_interval(self, interval: Duration) -> Self {
        Self { interval, ..self }
    }

    pub fn with_log_group_name(self, log_group_name: impl Into<String>) -> Self {
        Self {
            destination: LogDestination {
                log_group_name: log_group_name.into(),
                log_stream_name: self.destination.log_stream_name,
            },
            ..self
        }
    }

    pub fn with_log_stream_name(self, log_stream_name: impl Into<String>) -> Self {
        Self {
            destination: LogDestination {
                log_stream_name: log_stream_name.into(),
                log_group_name: self.destination.log_group_name,
            },
            ..self
        }
    }
}

pub(crate) struct BatchExporter<C> {
    client: C,
    queue: Vec<LogEvent>,
    config: ExportConfig,
}

impl Default for BatchExporter<NoopClient> {
    fn default() -> Self {
        Self::new(NoopClient::new(), ExportConfig::default())
    }
}

impl<C> BatchExporter<C> {
    pub(crate) fn new(client: C, config: ExportConfig) -> Self {
        Self {
            client,
            config,
            queue: Vec::new(),
        }
    }
}

impl<C> BatchExporter<C>
where
    C: CloudWatchClient + Send + Sync + 'static,
{
    pub(crate) async fn run(self, mut rx: UnboundedReceiver<LogEvent>) {
        let BatchExporter {
            client,
            mut queue,
            config,
        } = self;

        let mut interval = interval(config.interval);

        loop {
            tokio::select! {
                 _ = interval.tick() => {
                    if queue.is_empty() {
                        continue;
                    }
                }
                event = rx.recv() => {
                    let Some(event) = event else {
                        break;
                    };

                    queue.push(event);
                    if queue.len() < config.batch_size.into() {
                        continue
                    }
                }
            }

            let logs = queue.drain(..).collect();

            if let Err(err) = client.put_logs(config.destination.clone(), logs).await {
                eprintln!(
                    "[tracing-cloudwatch] Unable to put logs to cloudwatch. Error: {err} {:?}",
                    config.destination
                );
            }
        }
    }
}