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;
const MAX_GLOWS: usize = 30;
const MAX_BREADCRUMBS: usize = 100;
static GLOBAL: RwLock<Scope> = RwLock::new(Scope::empty());
thread_local! {
static SCOPE_STACK: RefCell<Vec<Scope>> = const { RefCell::new(Vec::new()) };
}
#[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 {
pub fn new<S: Into<String>>(id: S) -> Self {
Self {
id: id.into(),
email: None,
name: None,
attributes: BTreeMap::new(),
}
}
pub fn email<S: Into<String>>(mut self, email: S) -> Self {
self.email = Some(email.into());
self
}
pub fn name<S: Into<String>>(mut self, name: S) -> Self {
self.name = Some(name.into());
self
}
pub fn attribute<K: Into<String>, V: Into<Value>>(mut self, key: K, value: V) -> Self {
self.attributes.insert(key.into(), value.into());
self
}
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct Glow {
pub(crate) name: String,
pub(crate) level: Level,
pub(crate) context: Value,
pub(crate) time_unix_nano: u64,
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct Breadcrumb {
pub(crate) message: String,
pub(crate) level: Level,
pub(crate) fields: Vec<KeyValue>,
pub(crate) time_unix_nano: u64,
}
#[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 {
const fn empty() -> Self {
Self {
user: None,
context: BTreeMap::new(),
glows: VecDeque::new(),
breadcrumbs: VecDeque::new(),
attributes: BTreeMap::new(),
entry_point: None,
}
}
pub fn set_user(&mut self, user: User) {
self.user = Some(user);
}
pub fn remove_user(&mut self) {
self.user = None;
}
pub fn set_context<K: Into<String>, V: Into<Value>>(&mut self, key: K, value: V) {
self.context.insert(key.into(), value.into());
}
pub fn remove_context(&mut self, key: &str) {
self.context.remove(key);
}
pub fn set_attribute<K: Into<String>, V: Into<Value>>(&mut self, key: K, value: V) {
self.attributes.insert(key.into(), value.into());
}
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);
}
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()
}
}
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;
}
}
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());
}
}
}
fn clone_entries(map: &BTreeMap<String, Value>) -> impl Iterator<Item = (String, Value)> {
map.iter().map(|(key, value)| (key.clone(), value.clone()))
}
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),
}
}
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);
}
});
}
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);
}
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);
}
}
}
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()
}
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));
}
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));
}
fn add_to_current_scope<F: FnOnce(&mut Scope)>(add: F) {
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! {
#[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> {
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();
with_scope_stack(|stack| stack.push(this.scope.take().unwrap_or_default()));
let _restore = RestoreScopeOnDrop { scope: this.scope };
this.future.poll(context)
}
}
struct RestoreScopeOnDrop<'a> {
scope: &'a mut Option<Scope>,
}
impl Drop for RestoreScopeOnDrop<'_> {
fn drop(&mut self) {
*self.scope = with_scope_stack(Vec::pop).flatten();
}
}
pub trait ScopeFutureExt: Future + Sized {
fn with_flare_scope(self, scope: Scope) -> WithScope<Self> {
WithScope {
future: self,
scope: Some(scope),
}
}
}
impl<F: Future> ScopeFutureExt for F {}
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
}
pub(crate) fn app_entry_point() -> Option<EntryPoint> {
read_app_scope().entry_point.clone()
}
pub(crate) fn has_nested_entry_point() -> bool {
with_scope_stack(|stack| stack.iter().any(|scope| scope.entry_point.is_some())).unwrap_or(false)
}
pub(crate) fn nested_entry_point() -> Option<EntryPoint> {
with_scope_stack(|stack| {
stack
.iter()
.rev()
.find_map(|scope| scope.entry_point.clone())
})
.flatten()
}
#[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);
}
});
}
#[cfg(any(test, feature = "testing"))]
pub(crate) fn set_global_entry_point(entry_point: Option<EntryPoint>) {
write_app_scope().entry_point = entry_point;
}
fn read_app_scope() -> RwLockReadGuard<'static, Scope> {
GLOBAL.read().unwrap_or_else(PoisonError::into_inner)
}
fn write_app_scope() -> RwLockWriteGuard<'static, Scope> {
GLOBAL.write().unwrap_or_else(PoisonError::into_inner)
}
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()
}
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"));
}
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(¤t_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")));
}
}