tracing_betterstack/
export.rs

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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
use std::time::Duration;
use tokio::sync::mpsc::UnboundedReceiver;
use tokio::time::interval;

use crate::{
    client::{BetterstackClientTrait, NoopBetterstackClient},
    dispatch::LogEvent,
};

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

impl Default for ExportConfig {
    fn default() -> Self {
        Self {
            batch_size: 100,
            interval: Duration::from_secs(5),
        }
    }
}

impl ExportConfig {
    pub fn with_batch_size(self, batch_size: usize) -> Self {
        Self { batch_size, ..self }
    }

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

#[derive(Debug, Clone, Default)]
pub struct LogDestination;

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

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

impl<C> BatchExporter<C> {
    pub(crate) fn new(client: C, config: ExportConfig) -> Self {
        let queue = Vec::with_capacity(config.batch_size);
        Self {
            client,
            config,
            queue,
        }
    }
}

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

        loop {
            tokio::select! {
                _ = interval.tick() => {
                    if !self.queue.is_empty() {
                        self.flush_queue().await;
                    }
                }
                event = rx.recv() => {
                    match event {
                        Some(event) => {
                            self.queue.push(event);
                            if self.queue.len() >= self.config.batch_size {
                                self.flush_queue().await;
                            }
                        }
                        None => {
                            // Channel closed, flush remaining events
                            if !self.queue.is_empty() {
                                self.flush_queue().await;
                            }
                            break;
                        }
                    }
                }
            }
        }
    }

    async fn flush_queue(&mut self) {
        if let Err(err) = self
            .client
            .put_logs(LogDestination, std::mem::take(&mut self.queue))
            .await
        {
            eprintln!("[tracing-betterstack] Failed to send logs: {}", err);
        }
        self.queue.clear();
        self.queue.reserve(self.config.batch_size);
    }
}

#[cfg(test)]
mod tests {
    use crate::client::BetterstackError;

    use super::*;
    use std::{
        future::Future,
        pin::Pin,
        sync::{Arc, Mutex},
    };
    use tokio::sync::mpsc;

    struct TestClient {
        received_logs: Arc<Mutex<Vec<LogEvent>>>,
    }

    impl TestClient {
        fn new() -> Self {
            Self {
                received_logs: Arc::new(Mutex::new(Vec::new())),
            }
        }
    }

    impl BetterstackClientTrait for TestClient {
        fn put_logs<'a>(
            &'a self,
            _: LogDestination,
            logs: Vec<LogEvent>,
        ) -> Pin<Box<dyn Future<Output = Result<(), BetterstackError>> + Send + 'a>> {
            let received_logs = self.received_logs.clone();
            Box::pin(async move {
                received_logs.lock().unwrap().extend(logs);
                Ok(())
            })
        }
    }

    #[tokio::test]
    async fn test_batch_exporter_sends_on_full_batch() {
        let client = TestClient::new();
        let received_logs = client.received_logs.clone();
        let config = ExportConfig {
            batch_size: 2,
            interval: Duration::from_secs(5),
        };

        let (tx, rx) = mpsc::unbounded_channel();
        let exporter = BatchExporter::new(client, config);

        let handle = tokio::spawn(exporter.run(rx));

        // Send events
        let event1 = LogEvent::new("test1".into());
        let event2 = LogEvent::new("test2".into());
        tx.send(event1).unwrap();
        tx.send(event2).unwrap();

        // Give some time for processing
        tokio::time::sleep(Duration::from_millis(100)).await;

        // Check received logs
        let logs = received_logs.lock().unwrap();
        assert_eq!(logs.len(), 2);
        assert_eq!(logs[0].message, "test1");
        assert_eq!(logs[1].message, "test2");

        // Cleanup
        drop(tx);
        let _ = handle.await;
    }

    #[tokio::test]
    async fn test_batch_exporter_sends_on_interval() {
        let client = TestClient::new();
        let received_logs = client.received_logs.clone();
        let config = ExportConfig {
            batch_size: 10,                       // Larger than what we'll send
            interval: Duration::from_millis(100), // Short interval for testing
        };

        let (tx, rx) = mpsc::unbounded_channel();
        let exporter = BatchExporter::new(client, config);

        let handle = tokio::spawn(exporter.run(rx));

        // Send one event
        let event = LogEvent::new("test".into());
        tx.send(event).unwrap();

        // Wait for interval to trigger
        tokio::time::sleep(Duration::from_millis(150)).await;

        // Check received logs
        let logs = received_logs.lock().unwrap();
        assert_eq!(logs.len(), 1);
        assert_eq!(logs[0].message, "test");

        // Cleanup
        drop(tx);
        let _ = handle.await;
    }

    #[tokio::test]
    async fn test_batch_exporter_flushes_on_drop() {
        let client = TestClient::new();
        let received_logs = client.received_logs.clone();
        let config = ExportConfig {
            batch_size: 10,
            interval: Duration::from_secs(5),
        };

        let (tx, rx) = mpsc::unbounded_channel();
        let exporter = BatchExporter::new(client, config);

        let handle = tokio::spawn(exporter.run(rx));

        // Send an event
        let event = LogEvent::new("test".into());
        tx.send(event).unwrap();

        // Drop the sender to trigger flush
        drop(tx);
        let _ = handle.await;

        // Check that logs were flushed
        let logs = received_logs.lock().unwrap();
        assert_eq!(logs.len(), 1);
        assert_eq!(logs[0].message, "test");
    }

    #[test]
    fn test_export_config() {
        let config = ExportConfig::default()
            .with_batch_size(50)
            .with_interval(Duration::from_secs(10));

        assert_eq!(config.batch_size, 50);
        assert_eq!(config.interval, Duration::from_secs(10));
    }
}