Skip to main content

flareapp_core/
scope.rs

1//! The scope: the user, context, attributes, entry point, glows and log
2//! breadcrumbs that every report includes.
3//!
4//! There is one app-wide scope, changed with [`configure_scope`]. [`with_scope`]
5//! adds a scope for one piece of work on the current thread. A report merges the
6//! app-wide scope with the scopes of its thread.
7//!
8//! The Flare client never holds a lock while your code runs. So a closure that
9//! you pass to these functions can call the Flare client without a deadlock.
10
11use std::cell::RefCell;
12use std::collections::{BTreeMap, VecDeque};
13use std::future::Future;
14use std::pin::Pin;
15use std::sync::{PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard};
16use std::task::{Context as TaskContext, Poll};
17
18use pin_project_lite::pin_project;
19use serde_json::Value;
20
21use flareapp_otlp::{KeyValue, now_unix_nanos};
22
23use crate::entry_point::EntryPoint;
24use crate::level::Level;
25
26/// The most glows a scope keeps. Older glows are dropped first.
27const MAX_GLOWS: usize = 30;
28
29/// The most log breadcrumbs a scope keeps, the same as the PHP client.
30const MAX_BREADCRUMBS: usize = 100;
31
32/// The app-wide scope. [`configure_scope`] changes this scope outside a nested
33/// scope, and every report on every thread gets it.
34static GLOBAL: RwLock<Scope> = RwLock::new(Scope::empty());
35
36thread_local! {
37    /// The scopes that [`with_scope`] and [`WithScope`] pushed on this thread,
38    /// innermost last.
39    static SCOPE_STACK: RefCell<Vec<Scope>> = const { RefCell::new(Vec::new()) };
40}
41
42/// The user that was logged in when an error happened.
43///
44/// Flare uses `id` to count affected users, and shows `email` or `name` as the
45/// label.
46#[derive(Debug, Clone, PartialEq)]
47#[must_use]
48pub struct User {
49    pub(crate) id: String,
50    pub(crate) email: Option<String>,
51    pub(crate) name: Option<String>,
52    pub(crate) attributes: BTreeMap<String, Value>,
53}
54
55impl User {
56    /// Creates a user with the id from your application.
57    pub fn new<S: Into<String>>(id: S) -> Self {
58        Self {
59            id: id.into(),
60            email: None,
61            name: None,
62            attributes: BTreeMap::new(),
63        }
64    }
65
66    /// Sets the email address.
67    pub fn email<S: Into<String>>(mut self, email: S) -> Self {
68        self.email = Some(email.into());
69
70        self
71    }
72
73    /// Sets the full name.
74    pub fn name<S: Into<String>>(mut self, name: S) -> Self {
75        self.name = Some(name.into());
76
77        self
78    }
79
80    /// Adds an extra detail about the user, like their plan.
81    pub fn attribute<K: Into<String>, V: Into<Value>>(mut self, key: K, value: V) -> Self {
82        self.attributes.insert(key.into(), value.into());
83
84        self
85    }
86}
87
88/// A breadcrumb that you add with [`glow`], shown on the timeline of a report.
89#[derive(Debug, Clone, PartialEq)]
90pub(crate) struct Glow {
91    pub(crate) name: String,
92    pub(crate) level: Level,
93    pub(crate) context: Value,
94    /// When the glow was added, in nanoseconds since the Unix epoch.
95    pub(crate) time_unix_nano: u64,
96}
97
98/// A log line that the logging integrations recorded, shown on the timeline of a
99/// report.
100#[derive(Debug, Clone, PartialEq)]
101pub(crate) struct Breadcrumb {
102    pub(crate) message: String,
103    pub(crate) level: Level,
104    /// The fields of the log line. The encoder turns them into the JSON context of
105    /// the breadcrumb. That work runs on the worker thread, not on the app thread.
106    pub(crate) fields: Vec<KeyValue>,
107    /// When the log line was written, in nanoseconds since the Unix epoch.
108    pub(crate) time_unix_nano: u64,
109}
110
111/// The user, context, attributes, entry point, glows and log breadcrumbs that
112/// reports include.
113///
114/// Change it with [`configure_scope`], [`with_scope`] or
115/// [`ScopeFutureExt::with_flare_scope`].
116#[derive(Debug, Clone, Default, PartialEq)]
117pub struct Scope {
118    pub(crate) user: Option<User>,
119    pub(crate) context: BTreeMap<String, Value>,
120    pub(crate) glows: VecDeque<Glow>,
121    pub(crate) breadcrumbs: VecDeque<Breadcrumb>,
122    pub(crate) attributes: BTreeMap<String, Value>,
123    pub(crate) entry_point: Option<EntryPoint>,
124}
125
126impl Scope {
127    /// Creates an empty scope, the same as `Scope::default()`. This function is
128    /// `const`, so the [`GLOBAL`] static can use it.
129    const fn empty() -> Self {
130        Self {
131            user: None,
132            context: BTreeMap::new(),
133            glows: VecDeque::new(),
134            breadcrumbs: VecDeque::new(),
135            attributes: BTreeMap::new(),
136            entry_point: None,
137        }
138    }
139
140    /// Sets the user that reports belong to.
141    pub fn set_user(&mut self, user: User) {
142        self.user = Some(user);
143    }
144
145    /// Removes the user, for example after a logout.
146    pub fn remove_user(&mut self) {
147        self.user = None;
148    }
149
150    /// Adds a piece of context, shown under "custom context" in Flare.
151    ///
152    /// # Examples
153    ///
154    /// ```
155    /// flareapp_core::configure_scope(|scope| {
156    ///     scope.set_context("order", serde_json::json!({ "id": 7 }));
157    /// });
158    /// ```
159    pub fn set_context<K: Into<String>, V: Into<Value>>(&mut self, key: K, value: V) {
160        self.context.insert(key.into(), value.into());
161    }
162
163    /// Removes a piece of context.
164    pub fn remove_context(&mut self, key: &str) {
165        self.context.remove(key);
166    }
167
168    /// Sets an attribute that reports include as it is, like `http.request.method`.
169    /// Integrations use this for request data.
170    pub fn set_attribute<K: Into<String>, V: Into<Value>>(&mut self, key: K, value: V) {
171        self.attributes.insert(key.into(), value.into());
172    }
173
174    /// Sets what started the current work: a web request, a command or a job.
175    ///
176    /// Inside [`with_scope`] or [`ScopeFutureExt::with_flare_scope`], this entry
177    /// point wins over the entry point of any `tracing` span. In the app-wide
178    /// scope, this entry point comes after the spans, so a job span still names
179    /// its own job. Without an entry point anywhere, the Flare client uses the
180    /// command line of the process. The docs of [`EntryPoint`] explain the order.
181    pub fn set_entry_point(&mut self, entry_point: EntryPoint) {
182        self.entry_point = Some(entry_point);
183    }
184
185    fn add_breadcrumb(&mut self, breadcrumb: Breadcrumb) {
186        if self.breadcrumbs.len() >= MAX_BREADCRUMBS {
187            self.breadcrumbs.pop_front();
188        }
189        self.breadcrumbs.push_back(breadcrumb);
190    }
191
192    fn add_glow(&mut self, glow: Glow) {
193        if self.glows.len() >= MAX_GLOWS {
194            self.glows.pop_front();
195        }
196        self.glows.push_back(glow);
197    }
198
199    /// Copies the fields that [`configure_scope`] can change. The copy has no
200    /// glows and breadcrumbs, because `configure_scope` does not change them.
201    fn settings(&self) -> Self {
202        Self {
203            user: self.user.clone(),
204            context: self.context.clone(),
205            attributes: self.attributes.clone(),
206            entry_point: self.entry_point.clone(),
207            ..Self::empty()
208        }
209    }
210
211    /// Applies the changes between `before` and `after` to this scope. Fields and
212    /// keys that did not change keep their current value, so changes that other
213    /// code made in the meantime are kept.
214    fn apply_changes(&mut self, before: &Self, after: Self) {
215        if after.user != before.user {
216            self.user = after.user;
217        }
218        apply_map_changes(&mut self.context, &before.context, after.context);
219        apply_map_changes(&mut self.attributes, &before.attributes, after.attributes);
220        if after.entry_point != before.entry_point {
221            self.entry_point = after.entry_point;
222        }
223    }
224
225    /// Puts `top` on top of this scope. Values in `top` win.
226    fn merge(&mut self, top: &Scope) {
227        if let Some(user) = &top.user {
228            self.user = Some(user.clone());
229        }
230        self.context.extend(clone_entries(&top.context));
231        for glow in &top.glows {
232            self.add_glow(glow.clone());
233        }
234        for breadcrumb in &top.breadcrumbs {
235            self.add_breadcrumb(breadcrumb.clone());
236        }
237        self.attributes.extend(clone_entries(&top.attributes));
238        if let Some(entry_point) = &top.entry_point {
239            self.entry_point = Some(entry_point.clone());
240        }
241    }
242}
243
244/// Returns a copy of each entry of `map`, without a copy of the whole map.
245fn clone_entries(map: &BTreeMap<String, Value>) -> impl Iterator<Item = (String, Value)> {
246    map.iter().map(|(key, value)| (key.clone(), value.clone()))
247}
248
249/// Changes the current scope.
250///
251/// Outside [`with_scope`], this changes the app-wide scope. Inside `with_scope`,
252/// it changes the scope of that piece of work.
253///
254/// Two calls that change the app-wide scope at the same time keep the changes of
255/// both calls. When both calls change the same field or key, the call that ends
256/// last wins.
257///
258/// # Examples
259///
260/// ```
261/// use flareapp_core::User;
262///
263/// flareapp_core::configure_scope(|scope| scope.set_user(User::new("42")));
264/// ```
265pub fn configure_scope<F: FnOnce(&mut Scope)>(configure: F) {
266    match with_scope_stack(|stack| stack.last().map(Scope::settings)).flatten() {
267        Some(before) => configure_nested_scope(&before, configure),
268        None => configure_app_scope(configure),
269    }
270}
271
272/// Runs `configure` on a copy of `before`, the settings of the innermost nested
273/// scope. Then the function applies the changes to that scope.
274///
275/// The scope stays on the stack while `configure` runs, and the code does not
276/// borrow the stack. So `configure` can call the Flare client, and a report
277/// that `configure` sends has the whole scope. The scope keeps the changes that
278/// other code makes in the meantime, like a glow or a nested `configure_scope`
279/// call. When `configure` panics, the scope keeps its data.
280fn configure_nested_scope<F: FnOnce(&mut Scope)>(before: &Scope, configure: F) {
281    let mut after = before.clone();
282    configure(&mut after);
283    with_scope_stack(|stack| {
284        if let Some(innermost) = stack.last_mut() {
285            innermost.apply_changes(before, after);
286        }
287    });
288}
289
290/// Runs `configure` on a copy of the settings of the app-wide scope, and then
291/// applies the changes to the app-wide scope.
292///
293/// No lock is held while `configure` runs, so `configure` can call the Flare
294/// client. Changes that other code makes in the meantime, also on other threads,
295/// are kept.
296fn configure_app_scope<F: FnOnce(&mut Scope)>(configure: F) {
297    let before = read_app_scope().settings();
298    let mut after = before.clone();
299    configure(&mut after);
300    write_app_scope().apply_changes(&before, after);
301}
302
303/// Applies the changes between `before` and `after` to `target`. Removes the keys
304/// that `after` no longer has, and sets the keys that are new or changed.
305fn apply_map_changes(
306    target: &mut BTreeMap<String, Value>,
307    before: &BTreeMap<String, Value>,
308    after: BTreeMap<String, Value>,
309) {
310    for key in before.keys().filter(|key| !after.contains_key(*key)) {
311        target.remove(key);
312    }
313    for (key, value) in after {
314        if before.get(&key) != Some(&value) {
315            target.insert(key, value);
316        }
317    }
318}
319
320/// Runs `work` with an extra scope on the current thread, and removes that scope
321/// afterwards, also when `work` panics.
322///
323/// # Examples
324///
325/// ```
326/// use flareapp_core::User;
327///
328/// let total = flareapp_core::with_scope(
329///     |scope| scope.set_user(User::new("42")),
330///     || 1 + 1,
331/// );
332/// ```
333pub fn with_scope<C, W, R>(configure: C, work: W) -> R
334where
335    C: FnOnce(&mut Scope),
336    W: FnOnce() -> R,
337{
338    let mut scope = Scope::default();
339    configure(&mut scope);
340    with_scope_stack(|stack| stack.push(scope));
341
342    let _pop = PopScopeOnDrop;
343
344    work()
345}
346
347/// Adds a glow: a breadcrumb that shows up on the timeline of the next reports.
348///
349/// # Examples
350///
351/// ```
352/// use flareapp_core::Level;
353///
354/// flareapp_core::glow("cart updated", Level::Info, serde_json::json!({ "items": 3 }));
355/// ```
356pub fn glow<N: Into<String>, C: Into<Value>>(name: N, level: Level, context: C) {
357    let glow = Glow {
358        name: name.into(),
359        level,
360        context: context.into(),
361        time_unix_nano: now_unix_nanos(),
362    };
363
364    add_to_current_scope(|scope| scope.add_glow(glow));
365}
366
367/// Records a log line as a breadcrumb in the current scope. The logging
368/// integrations call this function. Error reports then show the line on their
369/// timeline, with `fields` as the context of the line.
370pub fn add_log_breadcrumb<M: Into<String>>(message: M, level: Level, fields: Vec<KeyValue>) {
371    let breadcrumb = Breadcrumb {
372        message: message.into(),
373        level,
374        fields,
375        time_unix_nano: now_unix_nanos(),
376    };
377
378    add_to_current_scope(|scope| scope.add_breadcrumb(breadcrumb));
379}
380
381/// Runs `add` on the innermost scope of this thread, or on the app-wide scope
382/// when this thread has no nested scope.
383fn add_to_current_scope<F: FnOnce(&mut Scope)>(add: F) {
384    // The closure below takes `add` out of the `Option` only when this thread has
385    // a nested scope. Otherwise `add` stays here, and the code after the closure
386    // runs `add` on the app-wide scope.
387    let mut add = Some(add);
388    with_scope_stack(|stack| {
389        if let Some(scope) = stack.last_mut()
390            && let Some(add) = add.take()
391        {
392            add(scope);
393        }
394    });
395
396    if let Some(add) = add {
397        add(&mut write_app_scope());
398    }
399}
400
401pin_project! {
402    /// A future that runs with its own scope. Create it with
403    /// [`ScopeFutureExt::with_flare_scope`].
404    #[derive(Debug)]
405    #[must_use = "futures do nothing unless you `.await` or poll them"]
406    pub struct WithScope<F> {
407        #[pin]
408        future: F,
409        scope: Option<Scope>,
410    }
411}
412
413impl<F> WithScope<F> {
414    /// Creates the future by calling `make_future` with `scope` on top of the
415    /// scope stack of the current thread.
416    ///
417    /// Use this function when the code that creates the future also runs other
418    /// code on the current thread, like the synchronous part of `Service::call`.
419    /// [`with_flare_scope`](ScopeFutureExt::with_flare_scope) puts the scope on
420    /// the stack only while the future is polled. Before the first poll, a
421    /// `configure_scope`, [`glow`] or log line in that other code changes the
422    /// app-wide scope.
423    ///
424    /// The scope of the returned future keeps what `make_future` adds to the
425    /// scope. This function takes the scope off the stack when `make_future`
426    /// returns. This function also takes the scope off the stack when `make_future`
427    /// panics.
428    ///
429    /// # Examples
430    ///
431    /// ```
432    /// use flareapp_core::{Scope, User, WithScope};
433    ///
434    /// let future = WithScope::build(Scope::default(), || {
435    ///     // This change goes to the scope of the future, not to the app-wide scope.
436    ///     flareapp_core::configure_scope(|scope| scope.set_user(User::new("42")));
437    ///
438    ///     async { /* handle the request */ }
439    /// });
440    /// ```
441    pub fn build<M: FnOnce() -> F>(scope: Scope, make_future: M) -> Self {
442        with_scope_stack(|stack| stack.push(scope));
443        let mut scope = None;
444        let restore = RestoreScopeOnDrop { scope: &mut scope };
445        let future = make_future();
446        drop(restore);
447
448        Self { future, scope }
449    }
450}
451
452impl<F: Future> Future for WithScope<F> {
453    type Output = F::Output;
454
455    fn poll(self: Pin<&mut Self>, context: &mut TaskContext<'_>) -> Poll<F::Output> {
456        let this = self.project();
457
458        // An async task can move to another thread at each `.await`. So each poll
459        // puts the scope on the current thread, and takes the scope back after.
460        with_scope_stack(|stack| stack.push(this.scope.take().unwrap_or_default()));
461        let _restore = RestoreScopeOnDrop { scope: this.scope };
462
463        this.future.poll(context)
464    }
465}
466
467/// Takes the future's scope back from the thread, also when the poll panics.
468struct RestoreScopeOnDrop<'a> {
469    scope: &'a mut Option<Scope>,
470}
471
472impl Drop for RestoreScopeOnDrop<'_> {
473    fn drop(&mut self) {
474        *self.scope = with_scope_stack(Vec::pop).flatten();
475    }
476}
477
478/// Gives a future its own scope, so the user, context and breadcrumbs of one
479/// request stay with that request, across every `.await`.
480///
481/// # Examples
482///
483/// ```
484/// use flareapp_core::{Scope, ScopeFutureExt, User};
485///
486/// let mut scope = Scope::default();
487/// scope.set_user(User::new("42"));
488/// let request = async { /* handle the request */ }.with_flare_scope(scope);
489/// ```
490pub trait ScopeFutureExt: Future + Sized {
491    /// Runs this future with `scope` on top of the app-wide scope.
492    fn with_flare_scope(self, scope: Scope) -> WithScope<Self> {
493        WithScope {
494            future: self,
495            scope: Some(scope),
496        }
497    }
498}
499
500impl<F: Future> ScopeFutureExt for F {}
501
502/// Returns the scope a report on this thread gets: the app-wide scope with the
503/// scopes of this thread on top.
504pub(crate) fn current_scope() -> Scope {
505    let mut scope = read_app_scope().clone();
506    with_scope_stack(|stack| {
507        for nested in stack.iter() {
508            scope.merge(nested);
509        }
510    });
511
512    scope
513}
514
515/// Returns the entry point of the app-wide scope.
516pub(crate) fn app_entry_point() -> Option<EntryPoint> {
517    read_app_scope().entry_point.clone()
518}
519
520/// Returns `true` when a nested scope on this thread has an entry point. This
521/// function does not clone the entry point.
522pub(crate) fn has_nested_entry_point() -> bool {
523    with_scope_stack(|stack| stack.iter().any(|scope| scope.entry_point.is_some())).unwrap_or(false)
524}
525
526/// Returns the entry point of the innermost nested scope that has one.
527///
528/// [`resolve_entry_point`](crate::resolve_entry_point) calls this function first,
529/// because a nested scope wins over every span and over the app-wide scope.
530pub(crate) fn nested_entry_point() -> Option<EntryPoint> {
531    with_scope_stack(|stack| {
532        stack
533            .iter()
534            .rev()
535            .find_map(|scope| scope.entry_point.clone())
536    })
537    .flatten()
538}
539
540/// Runs `read` with the entry point of the innermost nested scope that has one.
541/// Does not run `read` when no nested scope has an entry point.
542///
543/// Unlike [`nested_entry_point`], this function does not clone the entry point.
544/// The `tracing` layer calls it each time a root span exits, and clones the entry
545/// point only when it changed.
546///
547/// Used by the Flare integrations. Not part of the public API.
548#[doc(hidden)]
549pub fn with_nested_entry_point<F: FnOnce(&EntryPoint)>(read: F) {
550    with_scope_stack(|stack| {
551        if let Some(entry_point) = stack
552            .iter()
553            .rev()
554            .find_map(|scope| scope.entry_point.as_ref())
555        {
556            read(entry_point);
557        }
558    });
559}
560
561/// Sets the entry point of the app-wide scope, for tests.
562#[cfg(any(test, feature = "testing"))]
563pub(crate) fn set_global_entry_point(entry_point: Option<EntryPoint>) {
564    write_app_scope().entry_point = entry_point;
565}
566
567/// Locks the app-wide scope for reading.
568///
569/// A panic in another thread poisons the lock. The scope inside stays valid, so
570/// Flare keeps using it.
571fn read_app_scope() -> RwLockReadGuard<'static, Scope> {
572    GLOBAL.read().unwrap_or_else(PoisonError::into_inner)
573}
574
575/// Locks the app-wide scope for writing. A poisoned lock is fine here, for the
576/// same reason as in [`read_app_scope`].
577fn write_app_scope() -> RwLockWriteGuard<'static, Scope> {
578    GLOBAL.write().unwrap_or_else(PoisonError::into_inner)
579}
580
581/// Runs `f` with the scope stack of this thread. Returns `None` when the thread is
582/// shutting down and its scopes are already gone, or when the stack is already
583/// borrowed.
584fn with_scope_stack<R, F: FnOnce(&mut Vec<Scope>) -> R>(f: F) -> Option<R> {
585    SCOPE_STACK
586        .try_with(|stack| stack.try_borrow_mut().ok().map(|mut stack| f(&mut stack)))
587        .ok()
588        .flatten()
589}
590
591/// Removes the innermost scope of this thread when this guard is dropped, also
592/// during a panic.
593struct PopScopeOnDrop;
594
595impl Drop for PopScopeOnDrop {
596    fn drop(&mut self) {
597        with_scope_stack(Vec::pop);
598    }
599}
600
601#[cfg(test)]
602mod tests {
603    use serde_json::json;
604
605    use super::*;
606    use crate::test_support::block_on;
607
608    fn glow_names(scope: &Scope) -> Vec<&str> {
609        scope.glows.iter().map(|glow| glow.name.as_str()).collect()
610    }
611
612    #[test]
613    fn keeps_the_last_thirty_glows() {
614        let mut scope = Scope::default();
615
616        for index in 0..35 {
617            scope.add_glow(Glow {
618                name: index.to_string(),
619                level: Level::Info,
620                context: Value::Null,
621                time_unix_nano: 0,
622            });
623        }
624
625        assert_eq!(scope.glows.len(), 30);
626        assert_eq!(
627            scope.glows.front().map(|glow| glow.name.as_str()),
628            Some("5")
629        );
630    }
631
632    #[test]
633    fn keeps_the_last_hundred_breadcrumbs() {
634        let mut scope = Scope::default();
635
636        for index in 0..105 {
637            scope.add_breadcrumb(Breadcrumb {
638                message: index.to_string(),
639                level: Level::Info,
640                fields: Vec::new(),
641                time_unix_nano: 0,
642            });
643        }
644
645        assert_eq!(scope.breadcrumbs.len(), 100);
646        assert_eq!(
647            scope
648                .breadcrumbs
649                .front()
650                .map(|breadcrumb| breadcrumb.message.as_str()),
651            Some("5")
652        );
653    }
654
655    #[test]
656    fn with_scope_adds_a_scope_for_the_work_only() {
657        let inside = with_scope(
658            |scope| {
659                scope.set_user(User::new("42"));
660                scope.set_context("order", json!({ "id": 7 }));
661            },
662            current_scope,
663        );
664
665        assert_eq!(
666            inside.user.as_ref().map(|user| user.id.as_str()),
667            Some("42")
668        );
669        assert_eq!(inside.context.get("order"), Some(&json!({ "id": 7 })));
670        assert!(!current_scope().context.contains_key("order"));
671    }
672
673    #[test]
674    fn configure_scope_inside_with_scope_changes_that_scope() {
675        let inside = with_scope(
676            |_| {},
677            || {
678                configure_scope(|scope| scope.set_context("step", "checkout"));
679                glow("paid", Level::Info, Value::Null);
680
681                current_scope()
682            },
683        );
684
685        assert_eq!(inside.context.get("step"), Some(&json!("checkout")));
686        assert_eq!(glow_names(&inside), ["paid"]);
687        assert!(!current_scope().context.contains_key("step"));
688    }
689
690    #[test]
691    fn the_scope_is_removed_when_the_work_panics() {
692        let result = std::panic::catch_unwind(|| {
693            with_scope(|scope| scope.set_context("doomed", true), || panic!("boom"));
694        });
695
696        assert!(result.is_err());
697        assert!(!current_scope().context.contains_key("doomed"));
698    }
699
700    /// A future that is pending once, so it is polled twice.
701    struct YieldOnce(bool);
702
703    impl Future for YieldOnce {
704        type Output = ();
705
706        fn poll(mut self: Pin<&mut Self>, context: &mut TaskContext<'_>) -> Poll<()> {
707            if self.0 {
708                Poll::Ready(())
709            } else {
710                self.0 = true;
711                context.waker().wake_by_ref();
712                Poll::Pending
713            }
714        }
715    }
716
717    #[test]
718    fn a_future_keeps_its_scope_across_awaits() {
719        let mut scope = Scope::default();
720        scope.set_user(User::new("42"));
721
722        let (before, after) = block_on(
723            async {
724                configure_scope(|scope| scope.set_context("step", "checkout"));
725                let before = current_scope();
726                YieldOnce(false).await;
727
728                (before, current_scope())
729            }
730            .with_flare_scope(scope),
731        );
732
733        assert_eq!(
734            before.user.as_ref().map(|user| user.id.as_str()),
735            Some("42")
736        );
737        assert_eq!(after.user.as_ref().map(|user| user.id.as_str()), Some("42"));
738        assert_eq!(after.context.get("step"), Some(&json!("checkout")));
739        assert!(!current_scope().context.contains_key("step"));
740    }
741
742    #[test]
743    fn glows_added_inside_configure_scope_are_kept() {
744        let inside = with_scope(
745            |_| {},
746            || {
747                glow("before", Level::Debug, Value::Null);
748                configure_scope(|scope| {
749                    glow("nested", Level::Debug, Value::Null);
750                    scope.set_context("nested", true);
751                });
752
753                current_scope()
754            },
755        );
756
757        assert_eq!(glow_names(&inside), ["before", "nested"]);
758    }
759
760    #[test]
761    fn an_entry_point_set_in_a_nested_configure_scope_is_kept() {
762        let entry_point = EntryPoint::queue("send-invoice");
763
764        let nested = with_scope(
765            |_| {},
766            || {
767                configure_scope(|_| {
768                    configure_scope(|scope| scope.set_entry_point(entry_point.clone()));
769                });
770
771                nested_entry_point()
772            },
773        );
774
775        assert_eq!(nested, Some(entry_point));
776    }
777
778    #[test]
779    fn there_is_no_nested_entry_point_outside_a_scope() {
780        assert!(!has_nested_entry_point());
781    }
782
783    #[test]
784    fn a_scope_with_an_entry_point_has_a_nested_entry_point() {
785        let inside = with_scope(
786            |scope| scope.set_entry_point(EntryPoint::queue("send-invoice")),
787            has_nested_entry_point,
788        );
789
790        assert!(inside);
791    }
792
793    #[test]
794    fn the_innermost_entry_point_wins() {
795        let outer = EntryPoint::queue("send-invoice");
796        let inner = EntryPoint::web("https://shop.test/users/7");
797
798        let (between, inside) = with_scope(
799            |scope| scope.set_entry_point(outer.clone()),
800            || {
801                let between = with_scope(|_| {}, nested_entry_point);
802                let inside = with_scope(
803                    |scope| scope.set_entry_point(inner.clone()),
804                    nested_entry_point,
805                );
806
807                (between, inside)
808            },
809        );
810
811        assert_eq!(between, Some(outer));
812        assert_eq!(inside, Some(inner));
813    }
814
815    #[test]
816    fn applying_changes_keeps_the_glows() {
817        let mut scope = Scope::default();
818        scope.add_glow(Glow {
819            name: "added meanwhile".to_owned(),
820            level: Level::Info,
821            context: Value::Null,
822            time_unix_nano: 0,
823        });
824        let mut after = Scope::default();
825        after.set_user(User::new("42"));
826
827        scope.apply_changes(&Scope::default(), after);
828
829        assert_eq!(glow_names(&scope), ["added meanwhile"]);
830    }
831
832    #[test]
833    fn applying_changes_takes_the_new_user() {
834        let mut scope = Scope::default();
835        let mut after = Scope::default();
836        after.set_user(User::new("42"));
837
838        scope.apply_changes(&Scope::default(), after);
839
840        assert_eq!(scope.user.as_ref().map(|user| user.id.as_str()), Some("42"));
841    }
842
843    #[test]
844    fn applying_changes_keeps_context_that_was_added_meanwhile() {
845        let mut scope = Scope::default();
846        scope.set_context("added meanwhile", true);
847        let mut after = Scope::default();
848        after.set_context("step", "checkout");
849
850        scope.apply_changes(&Scope::default(), after);
851
852        assert_eq!(
853            scope.context.keys().collect::<Vec<_>>(),
854            ["added meanwhile", "step"]
855        );
856    }
857
858    #[test]
859    fn applying_changes_removes_context_that_was_removed() {
860        let mut before = Scope::default();
861        before.set_context("step", "checkout");
862        let mut scope = before.clone();
863
864        scope.apply_changes(&before, Scope::default());
865
866        assert!(scope.context.is_empty());
867    }
868
869    fn user_id(scope: &Scope) -> Option<&str> {
870        scope.user.as_ref().map(|user| user.id.as_str())
871    }
872
873    #[test]
874    fn the_nested_scope_is_visible_while_configure_scope_runs() {
875        let seen = with_scope(
876            |scope| scope.set_user(User::new("42")),
877            || {
878                let mut seen = None;
879                configure_scope(|scope| {
880                    scope.set_context("step", "checkout");
881                    seen = Some(current_scope());
882                });
883
884                seen
885            },
886        );
887
888        let seen = seen.unwrap();
889        assert_eq!(user_id(&seen), Some("42"));
890    }
891
892    #[test]
893    fn nested_configure_scope_calls_keep_both_changes() {
894        let inside = with_scope(
895            |_| {},
896            || {
897                configure_scope(|scope| {
898                    scope.set_context("outer", true);
899                    configure_scope(|scope| scope.set_context("inner", true));
900                });
901
902                current_scope()
903            },
904        );
905
906        assert_eq!(
907            inside.context.keys().collect::<Vec<_>>(),
908            ["inner", "outer"]
909        );
910    }
911
912    #[test]
913    fn a_panic_in_configure_scope_keeps_the_nested_scope() {
914        with_scope(
915            |scope| scope.set_user(User::new("42")),
916            || {
917                let result = std::panic::catch_unwind(|| {
918                    configure_scope(|_| panic!("boom"));
919                });
920
921                assert!(result.is_err());
922                assert_eq!(user_id(&current_scope()), Some("42"));
923            },
924        );
925    }
926
927    #[test]
928    fn build_runs_the_closure_inside_the_scope() {
929        let mut scope = Scope::default();
930        scope.set_user(User::new("42"));
931
932        let future = WithScope::build(scope, || {
933            configure_scope(|scope| scope.set_context("step", "checkout"));
934            let seen = current_scope();
935
936            async move { seen }
937        });
938        let seen = block_on(future);
939
940        assert_eq!(user_id(&seen), Some("42"));
941        assert!(current_scope().user.is_none());
942        assert!(!current_scope().context.contains_key("step"));
943    }
944
945    #[test]
946    fn build_keeps_the_changes_of_the_closure_for_the_future() {
947        let future = WithScope::build(Scope::default(), || {
948            configure_scope(|scope| scope.set_context("step", "checkout"));
949            glow("built", Level::Info, Value::Null);
950
951            async { current_scope() }
952        });
953        let seen = block_on(future);
954
955        assert_eq!(seen.context.get("step"), Some(&json!("checkout")));
956        assert_eq!(glow_names(&seen), ["built"]);
957    }
958
959    #[test]
960    fn build_removes_the_scope_when_the_closure_panics() {
961        let result = std::panic::catch_unwind(|| {
962            let mut scope = Scope::default();
963            scope.set_context("doomed", true);
964
965            WithScope::build(scope, || -> std::future::Ready<()> { panic!("boom") })
966        });
967
968        assert!(result.is_err());
969        assert!(!current_scope().context.contains_key("doomed"));
970    }
971
972    #[test]
973    fn a_nested_configure_scope_keeps_its_change_in_the_app_wide_scope() {
974        let _serial = crate::test_support::serial();
975        let _reset = crate::test_support::GlobalEntryPoint;
976
977        configure_scope(|_| {
978            configure_scope(|scope| scope.set_entry_point(EntryPoint::queue("send-invoice")));
979        });
980
981        assert_eq!(app_entry_point(), Some(EntryPoint::queue("send-invoice")));
982    }
983}