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::sync::Arc;

use serde::{Deserialize, Serialize};
use serde_json::Value;

pub(crate) const DEFAULT_ENDPOINT: &str = "https://api.oluso.dev/api/v1/error/report";
pub(crate) const DEFAULT_MONITOR_ENDPOINT: &str = "https://api.oluso.dev/api/v1/monitors/events";

/// How severe a captured error is. Mirrors the string values the other
/// Oluso SDKs send (`critical`/`high`/`medium`/`low`) so the ingestion API
/// treats reports from every language the same way.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Severity {
    Critical,
    High,
    #[default]
    Medium,
    Low,
}

/// A single event on the trail leading up to an error (a request started, a
/// button was clicked, a query ran). Attached to the next error report,
/// then cleared.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Breadcrumb {
    pub message: String,
    pub level: BreadcrumbLevel,
    pub category: Option<String>,
    pub data: Option<HashMap<String, Value>>,
    pub timestamp: u64,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum BreadcrumbLevel {
    Debug,
    #[default]
    Info,
    Warning,
    Error,
}

/// A breadcrumb as given to `add_breadcrumb` -- the timestamp is filled in
/// automatically, so callers don't provide one.
#[derive(Debug, Clone, Default)]
pub struct NewBreadcrumb {
    pub message: String,
    pub level: BreadcrumbLevel,
    pub category: Option<String>,
    pub data: Option<HashMap<String, Value>>,
}

impl NewBreadcrumb {
    pub fn new(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
            level: BreadcrumbLevel::Info,
            category: None,
            data: None,
        }
    }

    pub fn level(mut self, level: BreadcrumbLevel) -> Self {
        self.level = level;
        self
    }

    pub fn category(mut self, category: impl Into<String>) -> Self {
        self.category = Some(category.into());
        self
    }

    pub fn data(mut self, data: HashMap<String, Value>) -> Self {
        self.data = Some(data);
        self
    }
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct UserContext {
    pub id: Option<String>,
    pub email: Option<String>,
    pub username: Option<String>,
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

impl UserContext {
    pub fn new(id: impl Into<String>) -> Self {
        Self {
            id: Some(id.into()),
            ..Default::default()
        }
    }
}

/// Info about the request in flight when the error was captured. Framework
/// integrations build this; there's nothing generic enough in std to derive
/// it from automatically.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct RequestContext {
    pub url: String,
    pub method: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub headers: Option<HashMap<String, String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub query: Option<HashMap<String, String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub body: Option<Value>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ServerContext {
    pub hostname: String,
    pub os: String,
    pub arch: String,
    pub pid: u32,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ErrorContext {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub request: Option<RequestContext>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user: Option<UserContext>,
    pub server: ServerContext,
    #[serde(skip_serializing_if = "HashMap::is_empty")]
    pub custom: HashMap<String, Value>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub breadcrumbs: Vec<Breadcrumb>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExceptionDetails {
    pub r#type: String,
    pub message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stack_trace: Option<String>,
    #[serde(skip_serializing_if = "HashMap::is_empty")]
    pub attributes: HashMap<String, Value>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub causes: Vec<ExceptionDetails>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SdkInfo {
    pub name: String,
    pub version: String,
    pub language: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct ErrorReport {
    pub schema_version: u8,
    pub title: String,
    pub message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stack_trace: Option<String>,
    pub environment: String,
    pub severity: Severity,
    pub tags: Vec<String>,
    pub fingerprint: String,
    pub context: ErrorContext,
    pub timestamp: u64,
    pub exception: ExceptionDetails,
    pub sdk: SdkInfo,
}

/// Configuration for a [`crate::Client`]. Construct with [`Options::new`],
/// which fills in every default; override individual fields with the
/// builder methods.
#[derive(Clone)]
pub struct Options {
    pub api_key: String,
    pub endpoint: String,
    pub monitor_endpoint: String,
    pub monitor_retries: usize,
    pub environment: String,
    pub default_severity: Severity,
    pub tags: Vec<String>,
    pub timeout: std::time::Duration,
    pub log_to_console: bool,
    pub max_breadcrumbs: usize,
    pub enable_offline_queue: bool,
    pub max_queue_size: usize,
    pub max_errors_per_minute: u32,
    pub sensitive_keys: Vec<String>,
    pub should_report: Option<ShouldReportFn>,
    pub fingerprint: Option<FingerprintFn>,
}

pub type ShouldReportFn = Arc<dyn Fn(&str) -> bool + Send + Sync>;
pub type FingerprintFn = Arc<dyn Fn(&str, &ErrorContext) -> String + Send + Sync>;

impl std::fmt::Debug for Options {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Options")
            .field("api_key", &"<redacted>")
            .field("endpoint", &self.endpoint)
            .field("monitor_endpoint", &self.monitor_endpoint)
            .field("monitor_retries", &self.monitor_retries)
            .field("environment", &self.environment)
            .field("default_severity", &self.default_severity)
            .field("tags", &self.tags)
            .field("timeout", &self.timeout)
            .field("log_to_console", &self.log_to_console)
            .field("max_breadcrumbs", &self.max_breadcrumbs)
            .field("enable_offline_queue", &self.enable_offline_queue)
            .field("max_queue_size", &self.max_queue_size)
            .field("max_errors_per_minute", &self.max_errors_per_minute)
            .field("sensitive_keys", &self.sensitive_keys)
            .finish_non_exhaustive()
    }
}

impl Options {
    pub fn new(api_key: impl Into<String>) -> Self {
        Self {
            api_key: api_key.into(),
            endpoint: DEFAULT_ENDPOINT.to_string(),
            monitor_endpoint: DEFAULT_MONITOR_ENDPOINT.to_string(),
            monitor_retries: 2,
            environment: "production".to_string(),
            default_severity: Severity::Medium,
            tags: Vec::new(),
            timeout: std::time::Duration::from_secs(5),
            log_to_console: true,
            max_breadcrumbs: 30,
            enable_offline_queue: true,
            max_queue_size: 100,
            max_errors_per_minute: 60,
            sensitive_keys: Vec::new(),
            should_report: None,
            fingerprint: None,
        }
    }

    pub fn endpoint(mut self, endpoint: impl Into<String>) -> Self {
        self.endpoint = endpoint.into();
        self
    }

    pub fn monitor_endpoint(mut self, endpoint: impl Into<String>) -> Self {
        self.monitor_endpoint = endpoint.into();
        self
    }

    pub fn monitor_retries(mut self, retries: usize) -> Self {
        self.monitor_retries = retries.min(5);
        self
    }

    pub fn environment(mut self, environment: impl Into<String>) -> Self {
        self.environment = environment.into();
        self
    }

    pub fn default_severity(mut self, severity: Severity) -> Self {
        self.default_severity = severity;
        self
    }

    pub fn tags(mut self, tags: Vec<String>) -> Self {
        self.tags = tags;
        self
    }

    pub fn timeout(mut self, timeout: std::time::Duration) -> Self {
        self.timeout = timeout;
        self
    }

    pub fn log_to_console(mut self, log_to_console: bool) -> Self {
        self.log_to_console = log_to_console;
        self
    }

    pub fn max_breadcrumbs(mut self, max_breadcrumbs: usize) -> Self {
        self.max_breadcrumbs = max_breadcrumbs;
        self
    }

    pub fn enable_offline_queue(mut self, enable: bool) -> Self {
        self.enable_offline_queue = enable;
        self
    }

    pub fn max_queue_size(mut self, max_queue_size: usize) -> Self {
        self.max_queue_size = max_queue_size;
        self
    }

    pub fn max_errors_per_minute(mut self, max: u32) -> Self {
        self.max_errors_per_minute = max;
        self
    }

    pub fn sensitive_keys(mut self, keys: Vec<String>) -> Self {
        self.sensitive_keys = keys;
        self
    }

    pub fn should_report(mut self, f: impl Fn(&str) -> bool + Send + Sync + 'static) -> Self {
        self.should_report = Some(Arc::new(f));
        self
    }

    pub fn fingerprint(
        mut self,
        f: impl Fn(&str, &ErrorContext) -> String + Send + Sync + 'static,
    ) -> Self {
        self.fingerprint = Some(Arc::new(f));
        self
    }
}