1use 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
26const MAX_GLOWS: usize = 30;
28
29const MAX_BREADCRUMBS: usize = 100;
31
32static GLOBAL: RwLock<Scope> = RwLock::new(Scope::empty());
35
36thread_local! {
37 static SCOPE_STACK: RefCell<Vec<Scope>> = const { RefCell::new(Vec::new()) };
40}
41
42#[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 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 pub fn email<S: Into<String>>(mut self, email: S) -> Self {
68 self.email = Some(email.into());
69
70 self
71 }
72
73 pub fn name<S: Into<String>>(mut self, name: S) -> Self {
75 self.name = Some(name.into());
76
77 self
78 }
79
80 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#[derive(Debug, Clone, PartialEq)]
90pub(crate) struct Glow {
91 pub(crate) name: String,
92 pub(crate) level: Level,
93 pub(crate) context: Value,
94 pub(crate) time_unix_nano: u64,
96}
97
98#[derive(Debug, Clone, PartialEq)]
101pub(crate) struct Breadcrumb {
102 pub(crate) message: String,
103 pub(crate) level: Level,
104 pub(crate) fields: Vec<KeyValue>,
107 pub(crate) time_unix_nano: u64,
109}
110
111#[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 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 pub fn set_user(&mut self, user: User) {
142 self.user = Some(user);
143 }
144
145 pub fn remove_user(&mut self) {
147 self.user = None;
148 }
149
150 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 pub fn remove_context(&mut self, key: &str) {
165 self.context.remove(key);
166 }
167
168 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 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 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 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 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
244fn clone_entries(map: &BTreeMap<String, Value>) -> impl Iterator<Item = (String, Value)> {
246 map.iter().map(|(key, value)| (key.clone(), value.clone()))
247}
248
249pub 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
272fn 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
290fn 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
303fn 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
320pub 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
347pub 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
367pub 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
381fn add_to_current_scope<F: FnOnce(&mut Scope)>(add: F) {
384 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 #[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 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 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
467struct 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
478pub trait ScopeFutureExt: Future + Sized {
491 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
502pub(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
515pub(crate) fn app_entry_point() -> Option<EntryPoint> {
517 read_app_scope().entry_point.clone()
518}
519
520pub(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
526pub(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#[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#[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
567fn read_app_scope() -> RwLockReadGuard<'static, Scope> {
572 GLOBAL.read().unwrap_or_else(PoisonError::into_inner)
573}
574
575fn write_app_scope() -> RwLockWriteGuard<'static, Scope> {
578 GLOBAL.write().unwrap_or_else(PoisonError::into_inner)
579}
580
581fn 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
591struct 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 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(¤t_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}