eyes-subscriber 0.8.1

Tracing subscriber for sending traces to Eyes (eyes.coreyja.com)
Documentation
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
use async_trait::async_trait;
use reqwest::Client;
use std::time::Duration;
use tokio::sync::Mutex;
use tokio::time::Instant;
use url::Url;
use uuid::Uuid;

use crate::{
    transport::{Transport, TransportError},
    EventData,
};

/// Configuration for batching behavior
#[derive(Debug, Clone)]
pub struct BatchConfig {
    /// Maximum number of events in a batch before flushing
    pub max_batch_size: usize,
    /// Maximum time to wait before flushing a non-empty batch
    pub max_batch_age: Duration,
}

impl Default for BatchConfig {
    fn default() -> Self {
        Self {
            max_batch_size: 500,
            max_batch_age: Duration::from_secs(1),
        }
    }
}

impl BatchConfig {
    pub fn new(max_batch_size: usize, max_batch_age: Duration) -> Self {
        Self {
            max_batch_size,
            max_batch_age,
        }
    }
}

// Stay below the server's 10 MiB request limit for ordinary events. A single
// larger event is sent alone, preserving the single-event transport behavior.
const MAX_BATCH_BYTES: usize = 4 * 1024 * 1024;

/// HTTP transport with batching support
///
/// Buffers events and sends them in batches to reduce HTTP overhead.
/// Flushes when either:
/// - A full batch is flushed before accepting another event
/// - The transport loop timer fires within `max_batch_age`
/// - `close()` is called (flush remaining events)
pub struct BatchingHttpTransport {
    client: Client,
    batch_url: Url,
    config: BatchConfig,
    auth_token: Option<String>,
    buffer: Mutex<BatchBuffer>,
}

struct BatchBuffer {
    events: Vec<EventData>,
    oldest_event_time: Option<Instant>,
    serialized_bytes: usize,
}

impl BatchBuffer {
    fn new() -> Self {
        Self {
            events: Vec::new(),
            oldest_event_time: None,
            serialized_bytes: 2,
        }
    }

    fn push(&mut self, event: EventData) {
        if self.events.is_empty() {
            self.oldest_event_time = Some(Instant::now());
        }
        self.serialized_bytes += Self::event_bytes(&event);
        self.events.push(event);
    }

    fn take(&mut self) -> Vec<EventData> {
        self.oldest_event_time = None;
        self.serialized_bytes = 2;
        std::mem::take(&mut self.events)
    }

    fn event_bytes(event: &EventData) -> usize {
        // Include one comma; the final event's extra byte is conservative.
        serde_json::to_vec(event)
            .expect("event payload is JSON")
            .len()
            + 1
    }

    fn is_empty(&self) -> bool {
        self.events.is_empty()
    }

    fn len(&self) -> usize {
        self.events.len()
    }

    fn age(&self) -> Option<Duration> {
        self.oldest_event_time.map(|t| t.elapsed())
    }
}

impl BatchingHttpTransport {
    pub fn new(
        base_url: Url,
        org_id: Uuid,
        app_id: Uuid,
        config: BatchConfig,
        auth_token: Option<String>,
    ) -> Result<Self, TransportError> {
        let batch_url = base_url
            .join(&format!(
                "/api/orgs/{}/apps/{}/events/batch",
                org_id, app_id
            ))
            .map_err(|e| TransportError::Configuration(format!("Invalid URL: {}", e)))?;

        Ok(Self {
            client: Client::builder()
                .timeout(Duration::from_secs(10))
                .build()
                .map_err(|error| TransportError::Configuration(error.to_string()))?,
            batch_url,
            config,
            auth_token,
            buffer: Mutex::new(BatchBuffer::new()),
        })
    }

    pub fn with_default_config(
        base_url: Url,
        org_id: Uuid,
        app_id: Uuid,
        auth_token: Option<String>,
    ) -> Result<Self, TransportError> {
        Self::new(base_url, org_id, app_id, BatchConfig::default(), auth_token)
    }

    async fn flush_buffer(&self) -> Result<(), TransportError> {
        // Keep ownership until the server acknowledges the whole request.
        // A failed or cancelled flush must leave the accepted batch retryable.
        let mut buffer = self.buffer.lock().await;
        if buffer.is_empty() {
            return Ok(());
        }
        self.send_batch(&buffer.events).await?;
        buffer.take();
        Ok(())
    }

    async fn send_batch(&self, events: &[EventData]) -> Result<(), TransportError> {
        if events.is_empty() {
            return Ok(());
        }

        let mut request = self.client.post(self.batch_url.clone()).json(&events);
        if let Some(token) = &self.auth_token {
            request = request.bearer_auth(token);
        }
        let response = request
            .send()
            .await
            .map_err(|e| TransportError::Send(format!("HTTP batch request failed: {}", e)))?;

        if !response.status().is_success() {
            return Err(TransportError::Send(format!(
                "Server returned error status for batch: {}",
                response.status()
            )));
        }

        Ok(())
    }

    async fn should_flush(&self) -> bool {
        let buffer = self.buffer.lock().await;
        if buffer.len() >= self.config.max_batch_size {
            return true;
        }
        if let Some(age) = buffer.age() {
            if age >= self.config.max_batch_age {
                return true;
            }
        }
        false
    }
}

#[async_trait]
impl Transport for BatchingHttpTransport {
    async fn connect(&mut self) -> Result<(), TransportError> {
        Ok(())
    }

    async fn send(&mut self, event: EventData) -> Result<(), TransportError> {
        // Flush BEFORE accepting another event. On failure the caller retries
        // this event; appending first would duplicate it on every retry.
        let exceeds_bytes = {
            let buffer = self.buffer.lock().await;
            !buffer.is_empty()
                && buffer
                    .serialized_bytes
                    .saturating_add(BatchBuffer::event_bytes(&event))
                    > MAX_BATCH_BYTES
        };
        if self.should_flush().await || exceeds_bytes {
            self.flush_buffer().await?;
        }
        self.buffer.lock().await.push(event);
        Ok(())
    }

    async fn flush(&mut self) -> Result<(), TransportError> {
        self.flush_buffer().await
    }

    fn flush_interval(&self) -> Option<Duration> {
        Some(self.config.max_batch_age)
    }

    async fn close(&mut self) -> Result<(), TransportError> {
        self.flush_buffer().await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::Utc;

    #[test]
    fn test_batch_config_default() {
        let config = BatchConfig::default();
        assert_eq!(config.max_batch_size, 500);
        assert_eq!(config.max_batch_age, Duration::from_secs(1));
    }

    #[test]
    fn test_batch_config_custom() {
        let config = BatchConfig::new(50, Duration::from_millis(500));
        assert_eq!(config.max_batch_size, 50);
        assert_eq!(config.max_batch_age, Duration::from_millis(500));
    }

    #[test]
    fn test_batch_buffer_operations() {
        let mut buffer = BatchBuffer::new();
        assert!(buffer.is_empty());
        assert_eq!(buffer.len(), 0);
        assert!(buffer.age().is_none());

        let event = EventData {
            event_type: "test".to_string(),
            event_data: serde_json::json!({}),
            event_timestamp: Utc::now(),
            process_instance_id: None,
        };

        buffer.push(event);
        assert!(!buffer.is_empty());
        assert_eq!(buffer.len(), 1);
        assert!(buffer.age().is_some());

        let events = buffer.take();
        assert_eq!(events.len(), 1);
        assert!(buffer.is_empty());
        assert!(buffer.age().is_none());
    }

    #[test]
    fn test_batching_transport_creation() {
        let base_url = Url::parse("http://localhost:4318").unwrap();
        let org_id = Uuid::new_v4();
        let app_id = Uuid::new_v4();

        let transport =
            BatchingHttpTransport::with_default_config(base_url.clone(), org_id, app_id, None);
        assert!(transport.is_ok());

        let custom_config = BatchConfig::new(50, Duration::from_millis(100));
        let transport = BatchingHttpTransport::new(base_url, org_id, app_id, custom_config, None);
        assert!(transport.is_ok());
    }

    #[tokio::test]
    async fn test_batching_transport_url() {
        let base_url = Url::parse("http://localhost:4318").unwrap();
        let org_id = Uuid::parse_str("12345678-1234-1234-1234-123456789012").unwrap();
        let app_id = Uuid::parse_str("87654321-4321-4321-4321-210987654321").unwrap();

        let transport = BatchingHttpTransport::with_default_config(base_url, org_id, app_id, None)
            .expect("should create transport");

        assert_eq!(
            transport.batch_url.as_str(),
            "http://localhost:4318/api/orgs/12345678-1234-1234-1234-123456789012/apps/87654321-4321-4321-4321-210987654321/events/batch"
        );
    }

    #[tokio::test]
    async fn test_should_flush_by_size() {
        let base_url = Url::parse("http://localhost:4318").unwrap();
        let org_id = Uuid::new_v4();
        let app_id = Uuid::new_v4();
        let config = BatchConfig::new(2, Duration::from_secs(60)); // Small batch for testing

        let transport = BatchingHttpTransport::new(base_url, org_id, app_id, config, None)
            .expect("should create transport");

        // Add first event
        {
            let mut buffer = transport.buffer.lock().await;
            buffer.push(EventData {
                event_type: "test".to_string(),
                event_data: serde_json::json!({}),
                event_timestamp: Utc::now(),
                process_instance_id: None,
            });
        }
        assert!(!transport.should_flush().await);

        // Add second event - should now want to flush
        {
            let mut buffer = transport.buffer.lock().await;
            buffer.push(EventData {
                event_type: "test".to_string(),
                event_data: serde_json::json!({}),
                event_timestamp: Utc::now(),
                process_instance_id: None,
            });
        }
        assert!(transport.should_flush().await);
    }

    #[tokio::test]
    async fn test_should_flush_by_age() {
        let base_url = Url::parse("http://localhost:4318").unwrap();
        let org_id = Uuid::new_v4();
        let app_id = Uuid::new_v4();
        let config = BatchConfig::new(1000, Duration::from_millis(10)); // Short age for testing

        let transport = BatchingHttpTransport::new(base_url, org_id, app_id, config, None)
            .expect("should create transport");

        {
            let mut buffer = transport.buffer.lock().await;
            buffer.push(EventData {
                event_type: "test".to_string(),
                event_data: serde_json::json!({}),
                event_timestamp: Utc::now(),
                process_instance_id: None,
            });
        }

        assert!(!transport.should_flush().await);

        // Wait for age threshold
        tokio::time::sleep(Duration::from_millis(15)).await;

        assert!(transport.should_flush().await);
    }

    fn test_event(name: &str) -> EventData {
        EventData {
            event_type: name.into(),
            event_data: serde_json::json!({}),
            event_timestamp: Utc::now(),
            process_instance_id: None,
        }
    }

    fn server(
        replies: Vec<(u16, Duration)>,
    ) -> (Url, tokio::sync::oneshot::Receiver<Vec<Vec<EventData>>>) {
        use std::io::{BufRead, BufReader, Read, Write};
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        listener.set_nonblocking(true).unwrap();
        let address = listener.local_addr().unwrap();
        let (sent, received) = tokio::sync::oneshot::channel();
        std::thread::spawn(move || {
            let mut requests = Vec::new();
            for (status, delay) in replies {
                let deadline = std::time::Instant::now() + Duration::from_secs(3);
                let mut stream = loop {
                    match listener.accept() {
                        Ok((stream, _)) => break stream,
                        Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
                            assert!(std::time::Instant::now() < deadline, "batch never arrived");
                            std::thread::sleep(Duration::from_millis(1));
                        }
                        Err(error) => panic!("{error}"),
                    }
                };
                stream
                    .set_read_timeout(Some(Duration::from_secs(2)))
                    .unwrap();
                let mut reader = BufReader::new(&mut stream);
                let mut length = 0;
                loop {
                    let mut line = String::new();
                    assert!(reader.read_line(&mut line).unwrap() > 0);
                    if line == "\r\n" {
                        break;
                    }
                    if let Some(value) = line.to_ascii_lowercase().strip_prefix("content-length:") {
                        length = value.trim().parse::<usize>().unwrap();
                    }
                }
                let mut body = vec![0; length];
                reader.read_exact(&mut body).unwrap();
                requests.push(serde_json::from_slice(&body).unwrap());
                std::thread::sleep(delay);
                // A cancelled client can close its socket before the reply.
                let _ = write!(stream, "HTTP/1.1 {status} Result\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{{}}");
            }
            let _ = sent.send(requests);
        });
        (Url::parse(&format!("http://{address}")).unwrap(), received)
    }

    #[tokio::test]
    async fn failed_batch_is_retained_and_retry_does_not_duplicate_the_next_event() {
        let (url, received) = server(vec![
            (500, Duration::ZERO),
            (201, Duration::ZERO),
            (201, Duration::ZERO),
        ]);
        let mut transport = BatchingHttpTransport::new(
            url,
            Uuid::new_v4(),
            Uuid::new_v4(),
            BatchConfig::new(2, Duration::from_secs(60)),
            None,
        )
        .unwrap();
        transport.send(test_event("first")).await.unwrap();
        transport.send(test_event("second")).await.unwrap();
        assert!(transport.send(test_event("third")).await.is_err());
        assert_eq!(transport.buffer.lock().await.len(), 2);
        transport.send(test_event("third")).await.unwrap();
        transport.close().await.unwrap();
        let requests = received.await.unwrap();
        let names: Vec<Vec<_>> = requests
            .iter()
            .map(|batch| {
                batch
                    .iter()
                    .map(|event| event.event_type.as_str())
                    .collect()
            })
            .collect();
        assert_eq!(
            names,
            vec![
                vec!["first", "second"],
                vec!["first", "second"],
                vec!["third"]
            ]
        );
    }

    #[tokio::test]
    async fn cancelling_a_flush_keeps_every_accepted_event_for_retry() {
        let (url, received) = server(vec![
            (201, Duration::from_millis(100)),
            (201, Duration::ZERO),
        ]);
        let mut transport =
            BatchingHttpTransport::with_default_config(url, Uuid::new_v4(), Uuid::new_v4(), None)
                .unwrap();
        transport.send(test_event("retained")).await.unwrap();
        assert!(
            tokio::time::timeout(Duration::from_millis(30), transport.flush_buffer())
                .await
                .is_err()
        );
        assert_eq!(transport.buffer.lock().await.len(), 1);
        transport.close().await.unwrap();
        let requests = received.await.unwrap();
        assert_eq!(requests.len(), 2);
        assert!(requests
            .iter()
            .all(|batch| batch.len() == 1 && batch[0].event_type == "retained"));
    }

    #[tokio::test]
    async fn idle_batch_flushes_without_another_event_or_shutdown() {
        use std::sync::{atomic::AtomicU64, Arc};
        let (url, received) = server(vec![(201, Duration::ZERO)]);
        let transport = BatchingHttpTransport::new(
            url,
            Uuid::new_v4(),
            Uuid::new_v4(),
            BatchConfig::new(100, Duration::from_millis(25)),
            None,
        )
        .unwrap();
        let (sender, receiver) = tokio::sync::mpsc::channel(10);
        let (shutdown, shutdown_rx) = tokio::sync::oneshot::channel();
        let (completed, completion) = tokio::sync::oneshot::channel();
        tokio::spawn(crate::transport::run_transport_loop(
            Box::new(transport),
            receiver,
            shutdown_rx,
            completed,
            Arc::new(AtomicU64::new(0)),
            crate::transport::TransportLoopConfig::default(),
        ));
        sender.send(test_event("quiet tail")).await.unwrap();
        let requests = tokio::time::timeout(Duration::from_secs(1), received)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(requests[0][0].event_type, "quiet tail");
        shutdown.send(()).unwrap();
        completion.await.unwrap();
    }
    #[tokio::test]
    async fn large_events_split_batches_before_the_http_body_limit() {
        let (url, received) = server(vec![(201, Duration::ZERO), (201, Duration::ZERO)]);
        let mut transport =
            BatchingHttpTransport::with_default_config(url, Uuid::new_v4(), Uuid::new_v4(), None)
                .unwrap();
        let mut event = test_event("large");
        event.event_data = serde_json::json!({"message":"x".repeat(3 * 1024 * 1024)});
        transport.send(event.clone()).await.unwrap();
        transport.send(event).await.unwrap();
        transport.close().await.unwrap();
        let requests = received.await.unwrap();
        assert_eq!(requests.len(), 2);
        assert!(requests.iter().all(|batch| batch.len() == 1));
    }
}