flareapp-core 0.3.0

The core of the Flare client: config, the client, and the worker thread that sends data.
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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
//! Holds the records that wait to be sent, and decides when the next batch is due.

use std::borrow::Cow;
use std::collections::VecDeque;
use std::time::{Duration, Instant};

use flareapp_otlp::{
    InstrumentationScope, LogRecord, Resource, ScopeLogs, Span, encode_logs_json,
    encode_logs_protobuf, encode_traces_json, encode_traces_protobuf,
};

use super::retry::RetryPolicy;
use crate::config::{Config, OtlpProtocol};
use crate::report::ResolvedReport;
use crate::time::later;
use crate::transport::Signal;

/// A kind of record that the worker thread sends in batches: log records, traces
/// or error reports.
pub(super) trait Batchable: Sized {
    /// The kind of data. It decides which endpoint the batch goes to.
    const SIGNAL: Signal;

    /// The shortest time between two requests for this kind of record. A flush
    /// does not wait for this time, unless a retry is planned.
    const MIN_INTERVAL: Duration;

    /// How many records go in one request. `None` uses [`Config::batch_size`].
    const BATCH_SIZE: Option<usize> = None;

    /// How long records wait before they are sent. `None` uses
    /// [`Config::batch_interval`].
    const INTERVAL: Option<Duration> = None;

    /// Turns records into the body of one request. Logs and traces use
    /// `protocol`.
    fn encode(
        resource: &Resource,
        scope: &InstrumentationScope,
        records: &[Self],
        protocol: OtlpProtocol,
    ) -> serde_json::Result<Vec<u8>>;

    /// Returns the `content-type` header for a body made by [`Batchable::encode`].
    fn content_type(protocol: OtlpProtocol) -> &'static str {
        protocol.content_type()
    }
}

/// A log record, and the `tracing` or `log` target that wrote it, like
/// `my_app::billing`.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct Log {
    pub(crate) target: Cow<'static, str>,
    pub(crate) record: LogRecord,
}

impl Batchable for Log {
    const SIGNAL: Signal = Signal::Logs;
    const MIN_INTERVAL: Duration = Duration::ZERO;

    fn encode(
        resource: &Resource,
        scope: &InstrumentationScope,
        records: &[Self],
        protocol: OtlpProtocol,
    ) -> serde_json::Result<Vec<u8>> {
        let scope_logs = by_target(scope, records);

        match protocol {
            OtlpProtocol::HttpProtobuf => Ok(encode_logs_protobuf(resource, &scope_logs)),
            OtlpProtocol::HttpJson => encode_logs_json(resource, &scope_logs),
        }
    }
}

/// Groups logs by their target, in the order the targets first appear.
///
/// Each target becomes the name of an instrumentation scope, because Flare shows
/// the scope name as the target of a log. Each new scope copies its version from
/// `scope`, which holds the version of this crate. Flare requires a scope version.
fn by_target<'a>(scope: &InstrumentationScope, logs: &'a [Log]) -> Vec<ScopeLogs<'a>> {
    let mut groups: Vec<ScopeLogs<'a>> = Vec::new();

    for log in logs {
        match groups
            .iter_mut()
            .find(|group| group.scope.name == log.target)
        {
            Some(group) => group.log_records.push(&log.record),
            None => groups.push(ScopeLogs::new(
                InstrumentationScope::new(log.target.clone(), scope.version.clone()),
                vec![&log.record],
            )),
        }
    }

    groups
}

// Error reports go out right away, one per request.
impl Batchable for ResolvedReport {
    const SIGNAL: Signal = Signal::Errors;
    const MIN_INTERVAL: Duration = Duration::ZERO;
    const BATCH_SIZE: Option<usize> = Some(1);
    const INTERVAL: Option<Duration> = Some(Duration::ZERO);

    fn encode(
        resource: &Resource,
        _scope: &InstrumentationScope,
        records: &[Self],
        _protocol: OtlpProtocol,
    ) -> serde_json::Result<Vec<u8>> {
        records
            .first()
            .map_or_else(|| Ok(Vec::new()), |report| report.encode(resource))
    }

    fn content_type(_protocol: OtlpProtocol) -> &'static str {
        "application/json"
    }
}

/// Finished spans of one trace, which the worker thread sends in one request.
///
/// Flare joins the spans of one trace across requests. Still, the Flare client
/// keeps a trace together when the Flare client can, so a trace usually takes one
/// request. The exporter splits a batch between traces, never inside a `Trace`.
/// The spans can have different instrumentation scopes. Each scope then gets its
/// own `scopeSpans` entry in that one request.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct Trace(pub(crate) Vec<Span>);

impl Batchable for Trace {
    const SIGNAL: Signal = Signal::Traces;
    // Flare accepts 15 trace requests a minute for each API key, and the processes
    // of an app share the key. At 20 seconds, each process sends at most 3.
    const MIN_INTERVAL: Duration = Duration::from_secs(20);
    // With so few requests, a count would lower the number of traces that a
    // process can send. So only the size of a request limits a batch of traces.
    const BATCH_SIZE: Option<usize> = Some(usize::MAX);

    fn encode(
        resource: &Resource,
        scope: &InstrumentationScope,
        records: &[Self],
        protocol: OtlpProtocol,
    ) -> serde_json::Result<Vec<u8>> {
        let spans = records.iter().flat_map(|trace| &trace.0);

        match protocol {
            OtlpProtocol::HttpProtobuf => Ok(encode_traces_protobuf(resource, scope, spans)),
            OtlpProtocol::HttpJson => encode_traces_json(resource, scope, spans),
        }
    }
}

/// The records of one kind that wait to be sent, and the timing information that
/// decides when the next batch goes out.
pub(super) struct Batcher<T> {
    records: VecDeque<T>,
    capacity: usize,
    batch_size: usize,
    interval: Duration,
    min_interval: Duration,
    /// When the records started to wait, and the planned retry of the current
    /// batch. `None` when no records wait.
    waiting: Option<Waiting>,
    /// When the last request ended. A request that failed also counts.
    last_attempt: Option<Instant>,
    /// How many times, and how long after, a failed batch is tried again.
    retry_policy: RetryPolicy,
    /// How many records the batcher removed so far. The count includes the
    /// records that were sent and the records that were dropped.
    removed: u64,
    /// The mark of the latest flush. Until `removed` reaches this mark, the
    /// batcher sends without waiting for the batch interval. Records that arrive
    /// after the flush wait for the interval as usual.
    flush_until: u64,
}

/// The state of a batcher while records wait.
struct Waiting {
    /// When the records started to wait: when the first one arrived, or when the
    /// last request was sent.
    since: Instant,
    /// Set when the current batch failed and has to be tried again later.
    retry: Option<Retry>,
}

/// A planned new try of the current batch.
struct Retry {
    /// How many retries happened before this one.
    attempt: u32,
    /// The batch must not be sent before this time.
    not_before: Instant,
}

impl<T: Batchable> Batcher<T> {
    pub(super) fn new(config: &Config) -> Self {
        Self {
            records: VecDeque::new(),
            capacity: config.queue_capacity,
            batch_size: T::BATCH_SIZE.unwrap_or(config.batch_size),
            interval: T::INTERVAL.unwrap_or(config.batch_interval),
            min_interval: T::MIN_INTERVAL,
            waiting: None,
            last_attempt: None,
            retry_policy: config.retry,
            removed: 0,
            flush_until: 0,
        }
    }
}

impl<T> Batcher<T> {
    /// Adds a record to the end of the batcher.
    ///
    /// When the batcher is full, the oldest record is dropped to make room, and
    /// this function returns `false`.
    pub(super) fn push(&mut self, record: T, now: Instant) -> bool {
        let dropped = self.records.len() >= self.capacity && self.records.pop_front().is_some();
        if dropped {
            self.removed += 1;
        }

        if self.records.is_empty() {
            // A planned retry stays when a full batcher dropped its only record.
            let retry = self.waiting.take().and_then(|waiting| waiting.retry);
            self.waiting = Some(Waiting { since: now, retry });
        }
        self.records.push_back(record);

        !dropped
    }

    /// Starts a flush. The records that wait now are sent right away, without the
    /// wait for the batch interval.
    ///
    /// Returns the mark of this flush: the number of removed records at which all
    /// records of this flush are gone. Give the mark to [`Batcher::is_flushed`].
    /// Records that arrive later do not change the mark, so a later flush does not
    /// make an earlier flush wait longer.
    pub(super) fn flush(&mut self) -> u64 {
        self.flush_until = self.removed + self.records.len() as u64;

        self.flush_until
    }

    /// Returns `true` when the records of the flush with this `mark` are sent.
    pub(super) fn is_flushed(&self, mark: u64) -> bool {
        self.removed >= mark
    }

    /// Returns `true` when the flush with this `mark` has nothing more to wait
    /// for before `deadline`: its records are sent, or their next try is planned
    /// at or after `deadline`.
    pub(super) fn is_flush_done_by(&self, mark: u64, deadline: Instant) -> bool {
        let retry_planned = self
            .waiting
            .as_ref()
            .is_some_and(|waiting| waiting.retry.is_some());

        self.is_flushed(mark)
            || (retry_planned
                && self
                    .next_send_at()
                    .is_some_and(|send_at| send_at >= deadline))
    }

    /// Returns when the next batch can be sent, or `None` when nothing waits.
    ///
    /// Records of a flush can be sent right away, unless a retry is planned.
    pub(super) fn next_send_at(&self) -> Option<Instant> {
        let waiting = self.waiting.as_ref()?;

        if let Some(retry) = &waiting.retry {
            let allowed_at = self.last_attempt.map_or(retry.not_before, |attempt| {
                later(attempt, self.min_interval)
            });

            return Some(retry.not_before.max(allowed_at));
        }

        if !self.is_flushed(self.flush_until) {
            return Some(waiting.since);
        }

        let ready_at = if self.records.len() >= self.batch_size {
            waiting.since
        } else {
            later(waiting.since, self.interval)
        };

        let allowed_at = self
            .last_attempt
            .map_or(ready_at, |attempt| later(attempt, self.min_interval));

        Some(ready_at.max(allowed_at))
    }

    /// Returns the records for the next request: at most `batch_size` of the oldest ones.
    pub(super) fn batch(&mut self) -> &[T] {
        let size = self.records.len().min(self.batch_size);

        self.records
            .make_contiguous()
            .get(..size)
            .unwrap_or_default()
    }

    /// Removes the first `count` records after a request, whether the request
    /// succeeded or not, and clears the planned retry.
    pub(super) fn remove(&mut self, count: usize, now: Instant) {
        let count = count.min(self.records.len());
        self.records.drain(..count);
        self.removed += count as u64;
        self.last_attempt = Some(now);
        self.waiting = (!self.records.is_empty()).then_some(Waiting {
            since: now,
            retry: None,
        });
    }

    /// Plans a new try of the current batch.
    ///
    /// `now` is the time that the failed request ended. This time counts as an
    /// attempt. So a retry also keeps the minimum time between two requests.
    ///
    /// Returns `false` when no records wait, or when all retries are used up. The
    /// caller then drops the batch.
    pub(super) fn schedule_retry(&mut self, now: Instant, retry_after: Option<Duration>) -> bool {
        let Some(waiting) = &mut self.waiting else {
            return false;
        };
        self.last_attempt = Some(now);
        let policy = &self.retry_policy;
        let attempt = waiting.retry.as_ref().map_or(0, |retry| retry.attempt + 1);

        if attempt >= policy.max_retries {
            return false;
        }

        waiting.retry = Some(Retry {
            attempt,
            not_before: later(now, policy.delay(attempt, retry_after)),
        });

        true
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_support::{log as record, secs, span};

    /// Returns an info log of the target `shop`, with `body` as its message.
    fn log(body: &str) -> Log {
        log_of("shop", body)
    }

    fn log_of(target: &str, body: &str) -> Log {
        Log {
            target: target.to_owned().into(),
            record: record(body),
        }
    }

    fn config() -> Config {
        Config::new()
            .batch_size(3)
            .batch_interval(Duration::from_secs(5))
            .queue_capacity(5)
    }

    #[test]
    fn an_empty_batcher_has_nothing_to_send() {
        let batcher = Batcher::<Log>::new(&config());

        assert_eq!(batcher.next_send_at(), None);
    }

    #[test]
    fn sends_after_the_interval() {
        let now = Instant::now();
        let mut batcher = Batcher::new(&config());

        batcher.push(log("one"), now);

        assert_eq!(batcher.next_send_at(), Some(now + secs(5)));
    }

    #[test]
    fn sends_right_away_when_a_batch_is_full() {
        let now = Instant::now();
        let mut batcher = Batcher::new(&config());

        for body in ["one", "two", "three"] {
            batcher.push(log(body), now);
        }

        assert_eq!(batcher.next_send_at(), Some(now));
    }

    #[test]
    fn sends_right_away_when_flushing() {
        let now = Instant::now();
        let mut batcher = Batcher::new(&config());

        batcher.push(log("one"), now);
        batcher.flush();

        assert_eq!(batcher.next_send_at(), Some(now));
    }

    #[test]
    fn records_after_a_flush_wait_for_their_batch() {
        let now = Instant::now();
        let mut batcher = Batcher::new(&config());
        batcher.push(log("one"), now);
        let mark = batcher.flush();
        batcher.push(log("two"), now);

        let sent = batcher.batch().len();
        batcher.remove(sent, now);
        batcher.push(log("three"), now);

        assert!(batcher.is_flushed(mark));
        assert_eq!(batcher.next_send_at(), Some(now + secs(5)));
    }

    #[test]
    fn a_dropped_record_no_longer_holds_up_the_flush() {
        let now = Instant::now();
        let mut batcher = Batcher::new(&config());
        batcher.push(log("one"), now);
        let mark = batcher.flush();

        for index in 0..5 {
            batcher.push(log(&index.to_string()), now);
        }

        assert!(batcher.is_flushed(mark));
    }

    #[test]
    fn waits_between_trace_requests() {
        let now = Instant::now();
        let mut batcher = Batcher::<Trace>::new(&config());
        batcher.push(Trace(vec![span()]), now);
        batcher.remove(1, now);

        batcher.push(Trace(vec![span()]), now);

        assert_eq!(batcher.next_send_at(), Some(now + Trace::MIN_INTERVAL));
    }

    #[test]
    fn the_batch_size_does_not_limit_a_batch_of_traces() {
        let now = Instant::now();
        let mut batcher = Batcher::<Trace>::new(&config().batch_size(1).queue_capacity(150));
        for _ in 0..150 {
            batcher.push(Trace(vec![span()]), now);
        }

        assert_eq!(batcher.batch().len(), 150);
    }

    #[test]
    fn a_flush_sends_traces_without_the_minimum_interval() {
        let now = Instant::now();
        let mut batcher = Batcher::<Trace>::new(&config());
        batcher.push(Trace(vec![span()]), now);
        batcher.remove(1, now);

        batcher.push(Trace(vec![span()]), now);
        batcher.push(Trace(vec![span()]), now);
        batcher.flush();
        let first = batcher.next_send_at();
        batcher.remove(1, now);

        assert_eq!((first, batcher.next_send_at()), (Some(now), Some(now)));
    }

    /// Returns a batcher that holds as many records as it can: `0` to `4`.
    fn full_batcher(now: Instant) -> Batcher<Log> {
        let mut batcher = Batcher::new(&config());
        for index in 0..5 {
            batcher.push(log(&index.to_string()), now);
        }

        batcher
    }

    #[test]
    fn push_returns_true_while_there_is_room() {
        let now = Instant::now();
        let mut batcher = Batcher::new(&config());

        let pushed: Vec<bool> = (0..5)
            .map(|index| batcher.push(log(&index.to_string()), now))
            .collect();

        assert_eq!(pushed, [true; 5]);
    }

    #[test]
    fn push_returns_false_when_full() {
        let now = Instant::now();
        let mut batcher = full_batcher(now);

        assert!(!batcher.push(log("5"), now));
    }

    #[test]
    fn drops_the_oldest_record_when_full() {
        let now = Instant::now();
        let mut batcher = full_batcher(now);

        batcher.push(log("5"), now);

        let bodies: Vec<&str> = batcher
            .batch()
            .iter()
            .map(|log| log.record.body.as_str())
            .collect();
        assert_eq!(bodies, ["1", "2", "3"]);
    }

    #[test]
    fn a_batch_holds_at_most_batch_size_records() {
        let now = Instant::now();
        let mut batcher = Batcher::new(&config());

        for index in 0..5 {
            batcher.push(log(&index.to_string()), now);
        }

        assert_eq!(batcher.batch().len(), 3);
    }

    #[test]
    fn removing_records_resets_the_retry() {
        let now = Instant::now();
        let mut batcher = Batcher::new(&config());
        batcher.push(log("one"), now);
        batcher.schedule_retry(now, Some(secs(60)));

        batcher.remove(1, now);
        batcher.push(log("two"), now);

        assert_eq!(batcher.next_send_at(), Some(now + secs(5)));
    }

    #[test]
    fn trace_retries_keep_the_minimum_interval() {
        let now = Instant::now();
        let mut batcher = Batcher::<Trace>::new(&config());
        batcher.push(Trace(vec![span()]), now);

        assert!(batcher.schedule_retry(now, Some(secs(1))));

        assert_eq!(batcher.next_send_at(), Some(now + Trace::MIN_INTERVAL));
    }

    #[test]
    fn a_long_trace_retry_wait_is_kept() {
        let now = Instant::now();
        let mut batcher = Batcher::<Trace>::new(&config());
        batcher.push(Trace(vec![span()]), now);

        assert!(batcher.schedule_retry(now, Some(secs(60))));

        assert_eq!(batcher.next_send_at(), Some(now + secs(60)));
    }

    #[test]
    fn retries_wait_until_the_retry_time() {
        let now = Instant::now();
        let mut batcher = Batcher::new(&config());
        batcher.push(log("one"), now);

        assert!(batcher.schedule_retry(now, Some(secs(60))));
        batcher.flush();

        assert_eq!(batcher.next_send_at(), Some(now + secs(60)));
    }

    #[test]
    fn a_flush_is_not_done_while_its_records_wait() {
        let now = Instant::now();
        let mut batcher = Batcher::new(&config());
        batcher.push(log("one"), now);

        let mark = batcher.flush();

        assert!(!batcher.is_flush_done_by(mark, now + secs(2)));
    }

    /// Returns a batcher whose flush of one record waits for a retry in 60
    /// seconds, and the mark of that flush.
    fn flush_with_a_retry(now: Instant) -> (Batcher<Log>, u64) {
        let mut batcher = Batcher::new(&config());
        batcher.push(log("one"), now);
        let mark = batcher.flush();
        batcher.schedule_retry(now, Some(secs(60)));

        (batcher, mark)
    }

    #[test]
    fn a_flush_is_done_by_a_deadline_before_its_retry() {
        let now = Instant::now();

        let (batcher, mark) = flush_with_a_retry(now);

        assert!(batcher.is_flush_done_by(mark, now + secs(2)));
    }

    #[test]
    fn a_flush_is_not_done_by_a_deadline_after_its_retry() {
        let now = Instant::now();

        let (batcher, mark) = flush_with_a_retry(now);

        assert!(!batcher.is_flush_done_by(mark, now + secs(61)));
    }

    /// Encodes the logs and returns the `scopeLogs` array of the JSON body.
    fn encoded_scope_logs(logs: &[Log]) -> Vec<serde_json::Value> {
        let scope = InstrumentationScope::new("flareapp", "1.2.3");
        let body = Log::encode(
            &Resource::new(Vec::new()),
            &scope,
            logs,
            OtlpProtocol::HttpJson,
        )
        .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();

        json["resourceLogs"][0]["scopeLogs"]
            .as_array()
            .unwrap()
            .clone()
    }

    fn record_bodies(scope_logs: &serde_json::Value) -> Vec<&str> {
        scope_logs["logRecords"]
            .as_array()
            .unwrap()
            .iter()
            .map(|record| record["body"]["stringValue"].as_str().unwrap())
            .collect()
    }

    #[test]
    fn logs_get_one_scope_for_each_target() {
        let scope_logs = encoded_scope_logs(&[
            log_of("shop::auth", "one"),
            log_of("shop::checkout", "two"),
            log_of("shop::auth", "three"),
        ]);

        let names: Vec<_> = scope_logs
            .iter()
            .map(|entry| entry["scope"]["name"].as_str().unwrap())
            .collect();
        assert_eq!(names, ["shop::auth", "shop::checkout"]);
    }

    #[test]
    fn logs_of_one_target_share_a_scope_in_order() {
        let scope_logs = encoded_scope_logs(&[
            log_of("shop::auth", "one"),
            log_of("shop::checkout", "two"),
            log_of("shop::auth", "three"),
        ]);

        assert_eq!(record_bodies(&scope_logs[0]), ["one", "three"]);
        assert_eq!(record_bodies(&scope_logs[1]), ["two"]);
    }

    #[test]
    fn target_scopes_have_the_sdk_version() {
        let scope_logs = encoded_scope_logs(&[log_of("shop::auth", "one")]);

        assert_eq!(scope_logs[0]["scope"]["version"], "1.2.3");
    }

    #[test]
    fn a_trace_with_two_scopes_stays_in_one_request() {
        let scope = InstrumentationScope::new("flareapp", "1.2.3");
        let framework = Span {
            scope: Some(InstrumentationScope::new("laravel", "")),
            ..span()
        };
        let trace = Trace(vec![framework, span()]);

        let body = Trace::encode(
            &Resource::new(Vec::new()),
            &scope,
            &[trace],
            OtlpProtocol::HttpJson,
        )
        .unwrap();

        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        let scopes: Vec<_> = json["resourceSpans"][0]["scopeSpans"]
            .as_array()
            .unwrap()
            .iter()
            .map(|entry| {
                (
                    entry["scope"]["name"].as_str().unwrap(),
                    entry["spans"].as_array().unwrap().len(),
                )
            })
            .collect();
        assert_eq!(scopes, [("laravel", 1), ("flareapp", 1)]);
    }

    #[test]
    fn gives_up_after_the_last_retry() {
        let now = Instant::now();
        let policy = RetryPolicy::default();
        let mut batcher = Batcher::new(&config());
        batcher.push(log("one"), now);

        for _ in 0..policy.max_retries {
            assert!(batcher.schedule_retry(now, None));
        }

        assert!(!batcher.schedule_retry(now, None));
    }
}