oluso 0.2.0

AI-powered error monitoring for Rust applications: automatic panic reporting, breadcrumb tracking, and intelligent error grouping.
Documentation
use std::collections::HashMap;
use std::future::Future;
use std::sync::{Arc, Mutex};

use serde_json::Value;

use crate::time::now_millis;
use crate::types::{Breadcrumb, NewBreadcrumb, UserContext};

#[derive(Default)]
struct ScopeData {
    breadcrumbs: Vec<Breadcrumb>,
    user: Option<UserContext>,
    custom: HashMap<String, Value>,
}

tokio::task_local! {
    static SCOPE: Arc<Mutex<ScopeData>>;
}

/// Request-scoped breadcrumb/user/custom-context store -- the Rust
/// counterpart to @oluso/node's `AsyncLocalStorage`-backed `ContextManager`.
/// Built on `tokio::task_local!` rather than a plain global, so concurrent
/// requests handled on the same worker thread (the normal case for any
/// tokio-based web framework) don't bleed breadcrumbs into each other.
///
/// Unlike Node's `AsyncLocalStorage`, a `tokio::task_local!` value only
/// propagates through `.await`s *within the same top-level task* -- it does
/// not follow into a `tokio::spawn`ed task. If you spawn work that should
/// still report to the same request's scope, re-enter it explicitly with
/// [`ScopeManager::run`] inside the spawned task.
///
/// Falls back to a single shared store outside `run()` (e.g. a call made
/// before any request has started), mirroring @oluso/browser's flat,
/// non-request-scoped behavior instead of silently dropping the data.
pub(crate) struct ScopeManager {
    global: Mutex<ScopeData>,
    max_breadcrumbs: usize,
}

impl ScopeManager {
    pub fn new(max_breadcrumbs: usize) -> Self {
        Self {
            global: Mutex::new(ScopeData::default()),
            max_breadcrumbs,
        }
    }

    /// Runs `f` with a fresh, isolated scope. Route/middleware integrations
    /// call this once per request.
    pub async fn run<F, Fut, T>(&self, f: F) -> T
    where
        F: FnOnce() -> Fut,
        Fut: Future<Output = T>,
    {
        let data = Arc::new(Mutex::new(ScopeData::default()));
        SCOPE.scope(data, f()).await
    }

    fn with_current<R>(&self, f: impl FnOnce(&mut ScopeData) -> R) -> R {
        // Clone the Arc (a cheap refcount bump) rather than calling `f`
        // from inside the `try_with` closure directly -- `f` is `FnOnce`,
        // so the compiler considers it moved as soon as a closure
        // capturing it is constructed, even on the branch that never runs.
        // Cloning first means `f` is only ever referenced once below.
        let current = SCOPE.try_with(|data| data.clone()).ok();

        match current {
            Some(scope) => {
                let mut guard = scope.lock().unwrap_or_else(|e| e.into_inner());
                f(&mut guard)
            }
            None => {
                let mut guard = self.global.lock().unwrap_or_else(|e| e.into_inner());
                f(&mut guard)
            }
        }
    }

    pub fn add_breadcrumb(&self, breadcrumb: NewBreadcrumb) {
        let max = self.max_breadcrumbs;
        self.with_current(|data| {
            data.breadcrumbs.push(Breadcrumb {
                message: breadcrumb.message,
                level: breadcrumb.level,
                category: breadcrumb.category,
                data: breadcrumb.data,
                timestamp: now_millis(),
            });
            if data.breadcrumbs.len() > max {
                data.breadcrumbs.remove(0);
            }
        });
    }

    pub fn set_user_context(&self, user: UserContext) {
        self.with_current(|data| data.user = Some(user));
    }

    pub fn set_custom_context(&self, key: impl Into<String>, value: Value) {
        self.with_current(|data| {
            data.custom.insert(key.into(), value);
        });
    }

    pub fn snapshot(&self) -> (Vec<Breadcrumb>, Option<UserContext>, HashMap<String, Value>) {
        self.with_current(|data| {
            (
                data.breadcrumbs.clone(),
                data.user.clone(),
                data.custom.clone(),
            )
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::BreadcrumbLevel;

    #[tokio::test]
    async fn isolates_breadcrumbs_between_concurrent_scopes() {
        let manager = Arc::new(ScopeManager::new(30));

        let m1 = manager.clone();
        let task_a = tokio::spawn(async move {
            m1.run(|| async {
                m1.add_breadcrumb(NewBreadcrumb::new("a1"));
                tokio::time::sleep(std::time::Duration::from_millis(10)).await;
                m1.add_breadcrumb(NewBreadcrumb::new("a2"));
                m1.snapshot()
                    .0
                    .iter()
                    .map(|b| b.message.clone())
                    .collect::<Vec<_>>()
            })
            .await
        });

        let m2 = manager.clone();
        let task_b = tokio::spawn(async move {
            m2.run(|| async {
                m2.add_breadcrumb(NewBreadcrumb::new("b1"));
                m2.snapshot()
                    .0
                    .iter()
                    .map(|b| b.message.clone())
                    .collect::<Vec<_>>()
            })
            .await
        });

        let (a, b) = tokio::join!(task_a, task_b);
        assert_eq!(a.unwrap(), vec!["a1", "a2"]);
        assert_eq!(b.unwrap(), vec!["b1"]);
    }

    #[tokio::test]
    async fn falls_back_to_a_shared_store_outside_run() {
        let manager = ScopeManager::new(30);
        manager.add_breadcrumb(NewBreadcrumb::new("no scope"));
        let (breadcrumbs, _, _) = manager.snapshot();
        assert_eq!(breadcrumbs.len(), 1);
        assert_eq!(breadcrumbs[0].message, "no scope");
    }

    #[tokio::test]
    async fn caps_breadcrumbs_at_max_breadcrumbs() {
        let manager = ScopeManager::new(2);
        manager
            .run(|| async {
                manager.add_breadcrumb(NewBreadcrumb::new("1").level(BreadcrumbLevel::Info));
                manager.add_breadcrumb(NewBreadcrumb::new("2"));
                manager.add_breadcrumb(NewBreadcrumb::new("3"));
                let (breadcrumbs, _, _) = manager.snapshot();
                assert_eq!(
                    breadcrumbs
                        .iter()
                        .map(|b| b.message.as_str())
                        .collect::<Vec<_>>(),
                    vec!["2", "3"]
                );
            })
            .await;
    }
}