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
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
//! The scope: the user, context, attributes, entry point, glows and log
//! breadcrumbs that every report includes.
//!
//! There is one app-wide scope, changed with [`configure_scope`]. [`with_scope`]
//! adds a scope for one piece of work on the current thread. A report merges the
//! app-wide scope with the scopes of its thread.
//!
//! The Flare client never holds a lock while your code runs. So a closure that
//! you pass to these functions can call the Flare client without a deadlock.

use std::cell::RefCell;
use std::collections::{BTreeMap, VecDeque};
use std::future::Future;
use std::pin::Pin;
use std::sync::{PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard};
use std::task::{Context as TaskContext, Poll};

use pin_project_lite::pin_project;
use serde_json::Value;

use flareapp_otlp::{KeyValue, now_unix_nanos};

use crate::entry_point::EntryPoint;
use crate::level::Level;

/// The most glows a scope keeps. Older glows are dropped first.
const MAX_GLOWS: usize = 30;

/// The most log breadcrumbs a scope keeps, the same as the PHP client.
const MAX_BREADCRUMBS: usize = 100;

/// The app-wide scope. [`configure_scope`] changes this scope outside a nested
/// scope, and every report on every thread gets it.
static GLOBAL: RwLock<Scope> = RwLock::new(Scope::empty());

thread_local! {
    /// The scopes that [`with_scope`] and [`WithScope`] pushed on this thread,
    /// innermost last.
    static SCOPE_STACK: RefCell<Vec<Scope>> = const { RefCell::new(Vec::new()) };
}

/// The user that was logged in when an error happened.
///
/// Flare uses `id` to count affected users, and shows `email` or `name` as the
/// label.
#[derive(Debug, Clone, PartialEq)]
#[must_use]
pub struct User {
    pub(crate) id: String,
    pub(crate) email: Option<String>,
    pub(crate) name: Option<String>,
    pub(crate) attributes: BTreeMap<String, Value>,
}

impl User {
    /// Creates a user with the id from your application.
    pub fn new<S: Into<String>>(id: S) -> Self {
        Self {
            id: id.into(),
            email: None,
            name: None,
            attributes: BTreeMap::new(),
        }
    }

    /// Sets the email address.
    pub fn email<S: Into<String>>(mut self, email: S) -> Self {
        self.email = Some(email.into());

        self
    }

    /// Sets the full name.
    pub fn name<S: Into<String>>(mut self, name: S) -> Self {
        self.name = Some(name.into());

        self
    }

    /// Adds an extra detail about the user, like their plan.
    pub fn attribute<K: Into<String>, V: Into<Value>>(mut self, key: K, value: V) -> Self {
        self.attributes.insert(key.into(), value.into());

        self
    }
}

/// A breadcrumb that you add with [`glow`], shown on the timeline of a report.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct Glow {
    pub(crate) name: String,
    pub(crate) level: Level,
    pub(crate) context: Value,
    /// When the glow was added, in nanoseconds since the Unix epoch.
    pub(crate) time_unix_nano: u64,
}

/// A log line that the logging integrations recorded, shown on the timeline of a
/// report.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct Breadcrumb {
    pub(crate) message: String,
    pub(crate) level: Level,
    /// The fields of the log line. The encoder turns them into the JSON context of
    /// the breadcrumb. That work runs on the worker thread, not on the app thread.
    pub(crate) fields: Vec<KeyValue>,
    /// When the log line was written, in nanoseconds since the Unix epoch.
    pub(crate) time_unix_nano: u64,
}

/// The user, context, attributes, entry point, glows and log breadcrumbs that
/// reports include.
///
/// Change it with [`configure_scope`], [`with_scope`] or
/// [`ScopeFutureExt::with_flare_scope`].
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Scope {
    pub(crate) user: Option<User>,
    pub(crate) context: BTreeMap<String, Value>,
    pub(crate) glows: VecDeque<Glow>,
    pub(crate) breadcrumbs: VecDeque<Breadcrumb>,
    pub(crate) attributes: BTreeMap<String, Value>,
    pub(crate) entry_point: Option<EntryPoint>,
}

impl Scope {
    /// Creates an empty scope, the same as `Scope::default()`. This function is
    /// `const`, so the [`GLOBAL`] static can use it.
    const fn empty() -> Self {
        Self {
            user: None,
            context: BTreeMap::new(),
            glows: VecDeque::new(),
            breadcrumbs: VecDeque::new(),
            attributes: BTreeMap::new(),
            entry_point: None,
        }
    }

    /// Sets the user that reports belong to.
    pub fn set_user(&mut self, user: User) {
        self.user = Some(user);
    }

    /// Removes the user, for example after a logout.
    pub fn remove_user(&mut self) {
        self.user = None;
    }

    /// Adds a piece of context, shown under "custom context" in Flare.
    ///
    /// # Examples
    ///
    /// ```
    /// flareapp_core::configure_scope(|scope| {
    ///     scope.set_context("order", serde_json::json!({ "id": 7 }));
    /// });
    /// ```
    pub fn set_context<K: Into<String>, V: Into<Value>>(&mut self, key: K, value: V) {
        self.context.insert(key.into(), value.into());
    }

    /// Removes a piece of context.
    pub fn remove_context(&mut self, key: &str) {
        self.context.remove(key);
    }

    /// Sets an attribute that reports include as it is, like `http.request.method`.
    /// Integrations use this for request data.
    pub fn set_attribute<K: Into<String>, V: Into<Value>>(&mut self, key: K, value: V) {
        self.attributes.insert(key.into(), value.into());
    }

    /// Sets what started the current work: a web request, a command or a job.
    ///
    /// Inside [`with_scope`] or [`ScopeFutureExt::with_flare_scope`], this entry
    /// point wins over the entry point of any `tracing` span. In the app-wide
    /// scope, this entry point comes after the spans, so a job span still names
    /// its own job. Without an entry point anywhere, the Flare client uses the
    /// command line of the process. The docs of [`EntryPoint`] explain the order.
    pub fn set_entry_point(&mut self, entry_point: EntryPoint) {
        self.entry_point = Some(entry_point);
    }

    fn add_breadcrumb(&mut self, breadcrumb: Breadcrumb) {
        if self.breadcrumbs.len() >= MAX_BREADCRUMBS {
            self.breadcrumbs.pop_front();
        }
        self.breadcrumbs.push_back(breadcrumb);
    }

    fn add_glow(&mut self, glow: Glow) {
        if self.glows.len() >= MAX_GLOWS {
            self.glows.pop_front();
        }
        self.glows.push_back(glow);
    }

    /// Copies the fields that [`configure_scope`] can change. The copy has no
    /// glows and breadcrumbs, because `configure_scope` does not change them.
    fn settings(&self) -> Self {
        Self {
            user: self.user.clone(),
            context: self.context.clone(),
            attributes: self.attributes.clone(),
            entry_point: self.entry_point.clone(),
            ..Self::empty()
        }
    }

    /// Applies the changes between `before` and `after` to this scope. Fields and
    /// keys that did not change keep their current value, so changes that other
    /// code made in the meantime are kept.
    fn apply_changes(&mut self, before: &Self, after: Self) {
        if after.user != before.user {
            self.user = after.user;
        }
        apply_map_changes(&mut self.context, &before.context, after.context);
        apply_map_changes(&mut self.attributes, &before.attributes, after.attributes);
        if after.entry_point != before.entry_point {
            self.entry_point = after.entry_point;
        }
    }

    /// Puts `top` on top of this scope. Values in `top` win.
    fn merge(&mut self, top: &Scope) {
        if let Some(user) = &top.user {
            self.user = Some(user.clone());
        }
        self.context.extend(clone_entries(&top.context));
        for glow in &top.glows {
            self.add_glow(glow.clone());
        }
        for breadcrumb in &top.breadcrumbs {
            self.add_breadcrumb(breadcrumb.clone());
        }
        self.attributes.extend(clone_entries(&top.attributes));
        if let Some(entry_point) = &top.entry_point {
            self.entry_point = Some(entry_point.clone());
        }
    }
}

/// Returns a copy of each entry of `map`, without a copy of the whole map.
fn clone_entries(map: &BTreeMap<String, Value>) -> impl Iterator<Item = (String, Value)> {
    map.iter().map(|(key, value)| (key.clone(), value.clone()))
}

/// Changes the current scope.
///
/// Outside [`with_scope`], this changes the app-wide scope. Inside `with_scope`,
/// it changes the scope of that piece of work.
///
/// Two calls that change the app-wide scope at the same time keep the changes of
/// both calls. When both calls change the same field or key, the call that ends
/// last wins.
///
/// # Examples
///
/// ```
/// use flareapp_core::User;
///
/// flareapp_core::configure_scope(|scope| scope.set_user(User::new("42")));
/// ```
pub fn configure_scope<F: FnOnce(&mut Scope)>(configure: F) {
    match with_scope_stack(|stack| stack.last().map(Scope::settings)).flatten() {
        Some(before) => configure_nested_scope(&before, configure),
        None => configure_app_scope(configure),
    }
}

/// Runs `configure` on a copy of `before`, the settings of the innermost nested
/// scope. Then the function applies the changes to that scope.
///
/// The scope stays on the stack while `configure` runs, and the code does not
/// borrow the stack. So `configure` can call the Flare client, and a report
/// that `configure` sends has the whole scope. The scope keeps the changes that
/// other code makes in the meantime, like a glow or a nested `configure_scope`
/// call. When `configure` panics, the scope keeps its data.
fn configure_nested_scope<F: FnOnce(&mut Scope)>(before: &Scope, configure: F) {
    let mut after = before.clone();
    configure(&mut after);
    with_scope_stack(|stack| {
        if let Some(innermost) = stack.last_mut() {
            innermost.apply_changes(before, after);
        }
    });
}

/// Runs `configure` on a copy of the settings of the app-wide scope, and then
/// applies the changes to the app-wide scope.
///
/// No lock is held while `configure` runs, so `configure` can call the Flare
/// client. Changes that other code makes in the meantime, also on other threads,
/// are kept.
fn configure_app_scope<F: FnOnce(&mut Scope)>(configure: F) {
    let before = read_app_scope().settings();
    let mut after = before.clone();
    configure(&mut after);
    write_app_scope().apply_changes(&before, after);
}

/// Applies the changes between `before` and `after` to `target`. Removes the keys
/// that `after` no longer has, and sets the keys that are new or changed.
fn apply_map_changes(
    target: &mut BTreeMap<String, Value>,
    before: &BTreeMap<String, Value>,
    after: BTreeMap<String, Value>,
) {
    for key in before.keys().filter(|key| !after.contains_key(*key)) {
        target.remove(key);
    }
    for (key, value) in after {
        if before.get(&key) != Some(&value) {
            target.insert(key, value);
        }
    }
}

/// Runs `work` with an extra scope on the current thread, and removes that scope
/// afterwards, also when `work` panics.
///
/// # Examples
///
/// ```
/// use flareapp_core::User;
///
/// let total = flareapp_core::with_scope(
///     |scope| scope.set_user(User::new("42")),
///     || 1 + 1,
/// );
/// ```
pub fn with_scope<C, W, R>(configure: C, work: W) -> R
where
    C: FnOnce(&mut Scope),
    W: FnOnce() -> R,
{
    let mut scope = Scope::default();
    configure(&mut scope);
    with_scope_stack(|stack| stack.push(scope));

    let _pop = PopScopeOnDrop;

    work()
}

/// Adds a glow: a breadcrumb that shows up on the timeline of the next reports.
///
/// # Examples
///
/// ```
/// use flareapp_core::Level;
///
/// flareapp_core::glow("cart updated", Level::Info, serde_json::json!({ "items": 3 }));
/// ```
pub fn glow<N: Into<String>, C: Into<Value>>(name: N, level: Level, context: C) {
    let glow = Glow {
        name: name.into(),
        level,
        context: context.into(),
        time_unix_nano: now_unix_nanos(),
    };

    add_to_current_scope(|scope| scope.add_glow(glow));
}

/// Records a log line as a breadcrumb in the current scope. The logging
/// integrations call this function. Error reports then show the line on their
/// timeline, with `fields` as the context of the line.
pub fn add_log_breadcrumb<M: Into<String>>(message: M, level: Level, fields: Vec<KeyValue>) {
    let breadcrumb = Breadcrumb {
        message: message.into(),
        level,
        fields,
        time_unix_nano: now_unix_nanos(),
    };

    add_to_current_scope(|scope| scope.add_breadcrumb(breadcrumb));
}

/// Runs `add` on the innermost scope of this thread, or on the app-wide scope
/// when this thread has no nested scope.
fn add_to_current_scope<F: FnOnce(&mut Scope)>(add: F) {
    // The closure below takes `add` out of the `Option` only when this thread has
    // a nested scope. Otherwise `add` stays here, and the code after the closure
    // runs `add` on the app-wide scope.
    let mut add = Some(add);
    with_scope_stack(|stack| {
        if let Some(scope) = stack.last_mut()
            && let Some(add) = add.take()
        {
            add(scope);
        }
    });

    if let Some(add) = add {
        add(&mut write_app_scope());
    }
}

pin_project! {
    /// A future that runs with its own scope. Create it with
    /// [`ScopeFutureExt::with_flare_scope`].
    #[derive(Debug)]
    #[must_use = "futures do nothing unless you `.await` or poll them"]
    pub struct WithScope<F> {
        #[pin]
        future: F,
        scope: Option<Scope>,
    }
}

impl<F> WithScope<F> {
    /// Creates the future by calling `make_future` with `scope` on top of the
    /// scope stack of the current thread.
    ///
    /// Use this function when the code that creates the future also runs other
    /// code on the current thread, like the synchronous part of `Service::call`.
    /// [`with_flare_scope`](ScopeFutureExt::with_flare_scope) puts the scope on
    /// the stack only while the future is polled. Before the first poll, a
    /// `configure_scope`, [`glow`] or log line in that other code changes the
    /// app-wide scope.
    ///
    /// The scope of the returned future keeps what `make_future` adds to the
    /// scope. This function takes the scope off the stack when `make_future`
    /// returns. This function also takes the scope off the stack when `make_future`
    /// panics.
    ///
    /// # Examples
    ///
    /// ```
    /// use flareapp_core::{Scope, User, WithScope};
    ///
    /// let future = WithScope::build(Scope::default(), || {
    ///     // This change goes to the scope of the future, not to the app-wide scope.
    ///     flareapp_core::configure_scope(|scope| scope.set_user(User::new("42")));
    ///
    ///     async { /* handle the request */ }
    /// });
    /// ```
    pub fn build<M: FnOnce() -> F>(scope: Scope, make_future: M) -> Self {
        with_scope_stack(|stack| stack.push(scope));
        let mut scope = None;
        let restore = RestoreScopeOnDrop { scope: &mut scope };
        let future = make_future();
        drop(restore);

        Self { future, scope }
    }
}

impl<F: Future> Future for WithScope<F> {
    type Output = F::Output;

    fn poll(self: Pin<&mut Self>, context: &mut TaskContext<'_>) -> Poll<F::Output> {
        let this = self.project();

        // An async task can move to another thread at each `.await`. So each poll
        // puts the scope on the current thread, and takes the scope back after.
        with_scope_stack(|stack| stack.push(this.scope.take().unwrap_or_default()));
        let _restore = RestoreScopeOnDrop { scope: this.scope };

        this.future.poll(context)
    }
}

/// Takes the future's scope back from the thread, also when the poll panics.
struct RestoreScopeOnDrop<'a> {
    scope: &'a mut Option<Scope>,
}

impl Drop for RestoreScopeOnDrop<'_> {
    fn drop(&mut self) {
        *self.scope = with_scope_stack(Vec::pop).flatten();
    }
}

/// Gives a future its own scope, so the user, context and breadcrumbs of one
/// request stay with that request, across every `.await`.
///
/// # Examples
///
/// ```
/// use flareapp_core::{Scope, ScopeFutureExt, User};
///
/// let mut scope = Scope::default();
/// scope.set_user(User::new("42"));
/// let request = async { /* handle the request */ }.with_flare_scope(scope);
/// ```
pub trait ScopeFutureExt: Future + Sized {
    /// Runs this future with `scope` on top of the app-wide scope.
    fn with_flare_scope(self, scope: Scope) -> WithScope<Self> {
        WithScope {
            future: self,
            scope: Some(scope),
        }
    }
}

impl<F: Future> ScopeFutureExt for F {}

/// Returns the scope a report on this thread gets: the app-wide scope with the
/// scopes of this thread on top.
pub(crate) fn current_scope() -> Scope {
    let mut scope = read_app_scope().clone();
    with_scope_stack(|stack| {
        for nested in stack.iter() {
            scope.merge(nested);
        }
    });

    scope
}

/// Returns the entry point of the app-wide scope.
pub(crate) fn app_entry_point() -> Option<EntryPoint> {
    read_app_scope().entry_point.clone()
}

/// Returns `true` when a nested scope on this thread has an entry point. This
/// function does not clone the entry point.
pub(crate) fn has_nested_entry_point() -> bool {
    with_scope_stack(|stack| stack.iter().any(|scope| scope.entry_point.is_some())).unwrap_or(false)
}

/// Returns the entry point of the innermost nested scope that has one.
///
/// [`resolve_entry_point`](crate::resolve_entry_point) calls this function first,
/// because a nested scope wins over every span and over the app-wide scope.
pub(crate) fn nested_entry_point() -> Option<EntryPoint> {
    with_scope_stack(|stack| {
        stack
            .iter()
            .rev()
            .find_map(|scope| scope.entry_point.clone())
    })
    .flatten()
}

/// Runs `read` with the entry point of the innermost nested scope that has one.
/// Does not run `read` when no nested scope has an entry point.
///
/// Unlike [`nested_entry_point`], this function does not clone the entry point.
/// The `tracing` layer calls it each time a root span exits, and clones the entry
/// point only when it changed.
///
/// Used by the Flare integrations. Not part of the public API.
#[doc(hidden)]
pub fn with_nested_entry_point<F: FnOnce(&EntryPoint)>(read: F) {
    with_scope_stack(|stack| {
        if let Some(entry_point) = stack
            .iter()
            .rev()
            .find_map(|scope| scope.entry_point.as_ref())
        {
            read(entry_point);
        }
    });
}

/// Sets the entry point of the app-wide scope, for tests.
#[cfg(any(test, feature = "testing"))]
pub(crate) fn set_global_entry_point(entry_point: Option<EntryPoint>) {
    write_app_scope().entry_point = entry_point;
}

/// Locks the app-wide scope for reading.
///
/// A panic in another thread poisons the lock. The scope inside stays valid, so
/// Flare keeps using it.
fn read_app_scope() -> RwLockReadGuard<'static, Scope> {
    GLOBAL.read().unwrap_or_else(PoisonError::into_inner)
}

/// Locks the app-wide scope for writing. A poisoned lock is fine here, for the
/// same reason as in [`read_app_scope`].
fn write_app_scope() -> RwLockWriteGuard<'static, Scope> {
    GLOBAL.write().unwrap_or_else(PoisonError::into_inner)
}

/// Runs `f` with the scope stack of this thread. Returns `None` when the thread is
/// shutting down and its scopes are already gone, or when the stack is already
/// borrowed.
fn with_scope_stack<R, F: FnOnce(&mut Vec<Scope>) -> R>(f: F) -> Option<R> {
    SCOPE_STACK
        .try_with(|stack| stack.try_borrow_mut().ok().map(|mut stack| f(&mut stack)))
        .ok()
        .flatten()
}

/// Removes the innermost scope of this thread when this guard is dropped, also
/// during a panic.
struct PopScopeOnDrop;

impl Drop for PopScopeOnDrop {
    fn drop(&mut self) {
        with_scope_stack(Vec::pop);
    }
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::*;
    use crate::test_support::block_on;

    fn glow_names(scope: &Scope) -> Vec<&str> {
        scope.glows.iter().map(|glow| glow.name.as_str()).collect()
    }

    #[test]
    fn keeps_the_last_thirty_glows() {
        let mut scope = Scope::default();

        for index in 0..35 {
            scope.add_glow(Glow {
                name: index.to_string(),
                level: Level::Info,
                context: Value::Null,
                time_unix_nano: 0,
            });
        }

        assert_eq!(scope.glows.len(), 30);
        assert_eq!(
            scope.glows.front().map(|glow| glow.name.as_str()),
            Some("5")
        );
    }

    #[test]
    fn keeps_the_last_hundred_breadcrumbs() {
        let mut scope = Scope::default();

        for index in 0..105 {
            scope.add_breadcrumb(Breadcrumb {
                message: index.to_string(),
                level: Level::Info,
                fields: Vec::new(),
                time_unix_nano: 0,
            });
        }

        assert_eq!(scope.breadcrumbs.len(), 100);
        assert_eq!(
            scope
                .breadcrumbs
                .front()
                .map(|breadcrumb| breadcrumb.message.as_str()),
            Some("5")
        );
    }

    #[test]
    fn with_scope_adds_a_scope_for_the_work_only() {
        let inside = with_scope(
            |scope| {
                scope.set_user(User::new("42"));
                scope.set_context("order", json!({ "id": 7 }));
            },
            current_scope,
        );

        assert_eq!(
            inside.user.as_ref().map(|user| user.id.as_str()),
            Some("42")
        );
        assert_eq!(inside.context.get("order"), Some(&json!({ "id": 7 })));
        assert!(!current_scope().context.contains_key("order"));
    }

    #[test]
    fn configure_scope_inside_with_scope_changes_that_scope() {
        let inside = with_scope(
            |_| {},
            || {
                configure_scope(|scope| scope.set_context("step", "checkout"));
                glow("paid", Level::Info, Value::Null);

                current_scope()
            },
        );

        assert_eq!(inside.context.get("step"), Some(&json!("checkout")));
        assert_eq!(glow_names(&inside), ["paid"]);
        assert!(!current_scope().context.contains_key("step"));
    }

    #[test]
    fn the_scope_is_removed_when_the_work_panics() {
        let result = std::panic::catch_unwind(|| {
            with_scope(|scope| scope.set_context("doomed", true), || panic!("boom"));
        });

        assert!(result.is_err());
        assert!(!current_scope().context.contains_key("doomed"));
    }

    /// A future that is pending once, so it is polled twice.
    struct YieldOnce(bool);

    impl Future for YieldOnce {
        type Output = ();

        fn poll(mut self: Pin<&mut Self>, context: &mut TaskContext<'_>) -> Poll<()> {
            if self.0 {
                Poll::Ready(())
            } else {
                self.0 = true;
                context.waker().wake_by_ref();
                Poll::Pending
            }
        }
    }

    #[test]
    fn a_future_keeps_its_scope_across_awaits() {
        let mut scope = Scope::default();
        scope.set_user(User::new("42"));

        let (before, after) = block_on(
            async {
                configure_scope(|scope| scope.set_context("step", "checkout"));
                let before = current_scope();
                YieldOnce(false).await;

                (before, current_scope())
            }
            .with_flare_scope(scope),
        );

        assert_eq!(
            before.user.as_ref().map(|user| user.id.as_str()),
            Some("42")
        );
        assert_eq!(after.user.as_ref().map(|user| user.id.as_str()), Some("42"));
        assert_eq!(after.context.get("step"), Some(&json!("checkout")));
        assert!(!current_scope().context.contains_key("step"));
    }

    #[test]
    fn glows_added_inside_configure_scope_are_kept() {
        let inside = with_scope(
            |_| {},
            || {
                glow("before", Level::Debug, Value::Null);
                configure_scope(|scope| {
                    glow("nested", Level::Debug, Value::Null);
                    scope.set_context("nested", true);
                });

                current_scope()
            },
        );

        assert_eq!(glow_names(&inside), ["before", "nested"]);
    }

    #[test]
    fn an_entry_point_set_in_a_nested_configure_scope_is_kept() {
        let entry_point = EntryPoint::queue("send-invoice");

        let nested = with_scope(
            |_| {},
            || {
                configure_scope(|_| {
                    configure_scope(|scope| scope.set_entry_point(entry_point.clone()));
                });

                nested_entry_point()
            },
        );

        assert_eq!(nested, Some(entry_point));
    }

    #[test]
    fn there_is_no_nested_entry_point_outside_a_scope() {
        assert!(!has_nested_entry_point());
    }

    #[test]
    fn a_scope_with_an_entry_point_has_a_nested_entry_point() {
        let inside = with_scope(
            |scope| scope.set_entry_point(EntryPoint::queue("send-invoice")),
            has_nested_entry_point,
        );

        assert!(inside);
    }

    #[test]
    fn the_innermost_entry_point_wins() {
        let outer = EntryPoint::queue("send-invoice");
        let inner = EntryPoint::web("https://shop.test/users/7");

        let (between, inside) = with_scope(
            |scope| scope.set_entry_point(outer.clone()),
            || {
                let between = with_scope(|_| {}, nested_entry_point);
                let inside = with_scope(
                    |scope| scope.set_entry_point(inner.clone()),
                    nested_entry_point,
                );

                (between, inside)
            },
        );

        assert_eq!(between, Some(outer));
        assert_eq!(inside, Some(inner));
    }

    #[test]
    fn applying_changes_keeps_the_glows() {
        let mut scope = Scope::default();
        scope.add_glow(Glow {
            name: "added meanwhile".to_owned(),
            level: Level::Info,
            context: Value::Null,
            time_unix_nano: 0,
        });
        let mut after = Scope::default();
        after.set_user(User::new("42"));

        scope.apply_changes(&Scope::default(), after);

        assert_eq!(glow_names(&scope), ["added meanwhile"]);
    }

    #[test]
    fn applying_changes_takes_the_new_user() {
        let mut scope = Scope::default();
        let mut after = Scope::default();
        after.set_user(User::new("42"));

        scope.apply_changes(&Scope::default(), after);

        assert_eq!(scope.user.as_ref().map(|user| user.id.as_str()), Some("42"));
    }

    #[test]
    fn applying_changes_keeps_context_that_was_added_meanwhile() {
        let mut scope = Scope::default();
        scope.set_context("added meanwhile", true);
        let mut after = Scope::default();
        after.set_context("step", "checkout");

        scope.apply_changes(&Scope::default(), after);

        assert_eq!(
            scope.context.keys().collect::<Vec<_>>(),
            ["added meanwhile", "step"]
        );
    }

    #[test]
    fn applying_changes_removes_context_that_was_removed() {
        let mut before = Scope::default();
        before.set_context("step", "checkout");
        let mut scope = before.clone();

        scope.apply_changes(&before, Scope::default());

        assert!(scope.context.is_empty());
    }

    fn user_id(scope: &Scope) -> Option<&str> {
        scope.user.as_ref().map(|user| user.id.as_str())
    }

    #[test]
    fn the_nested_scope_is_visible_while_configure_scope_runs() {
        let seen = with_scope(
            |scope| scope.set_user(User::new("42")),
            || {
                let mut seen = None;
                configure_scope(|scope| {
                    scope.set_context("step", "checkout");
                    seen = Some(current_scope());
                });

                seen
            },
        );

        let seen = seen.unwrap();
        assert_eq!(user_id(&seen), Some("42"));
    }

    #[test]
    fn nested_configure_scope_calls_keep_both_changes() {
        let inside = with_scope(
            |_| {},
            || {
                configure_scope(|scope| {
                    scope.set_context("outer", true);
                    configure_scope(|scope| scope.set_context("inner", true));
                });

                current_scope()
            },
        );

        assert_eq!(
            inside.context.keys().collect::<Vec<_>>(),
            ["inner", "outer"]
        );
    }

    #[test]
    fn a_panic_in_configure_scope_keeps_the_nested_scope() {
        with_scope(
            |scope| scope.set_user(User::new("42")),
            || {
                let result = std::panic::catch_unwind(|| {
                    configure_scope(|_| panic!("boom"));
                });

                assert!(result.is_err());
                assert_eq!(user_id(&current_scope()), Some("42"));
            },
        );
    }

    #[test]
    fn build_runs_the_closure_inside_the_scope() {
        let mut scope = Scope::default();
        scope.set_user(User::new("42"));

        let future = WithScope::build(scope, || {
            configure_scope(|scope| scope.set_context("step", "checkout"));
            let seen = current_scope();

            async move { seen }
        });
        let seen = block_on(future);

        assert_eq!(user_id(&seen), Some("42"));
        assert!(current_scope().user.is_none());
        assert!(!current_scope().context.contains_key("step"));
    }

    #[test]
    fn build_keeps_the_changes_of_the_closure_for_the_future() {
        let future = WithScope::build(Scope::default(), || {
            configure_scope(|scope| scope.set_context("step", "checkout"));
            glow("built", Level::Info, Value::Null);

            async { current_scope() }
        });
        let seen = block_on(future);

        assert_eq!(seen.context.get("step"), Some(&json!("checkout")));
        assert_eq!(glow_names(&seen), ["built"]);
    }

    #[test]
    fn build_removes_the_scope_when_the_closure_panics() {
        let result = std::panic::catch_unwind(|| {
            let mut scope = Scope::default();
            scope.set_context("doomed", true);

            WithScope::build(scope, || -> std::future::Ready<()> { panic!("boom") })
        });

        assert!(result.is_err());
        assert!(!current_scope().context.contains_key("doomed"));
    }

    #[test]
    fn a_nested_configure_scope_keeps_its_change_in_the_app_wide_scope() {
        let _serial = crate::test_support::serial();
        let _reset = crate::test_support::GlobalEntryPoint;

        configure_scope(|_| {
            configure_scope(|scope| scope.set_entry_point(EntryPoint::queue("send-invoice")));
        });

        assert_eq!(app_entry_point(), Some(EntryPoint::queue("send-invoice")));
    }
}