Skip to main content

systemprompt_traits/
context.rs

1//! Application context, module registry, and request-context propagation.
2//!
3//! The async traits here are dispatched as trait objects (`dyn _`), so they
4//! use `#[async_trait]`; native `async fn` in traits is not yet
5//! `dyn`-compatible.
6//!
7//! The traits in this module are the runtime entry points other crates use
8//! to discover configuration, the database handle, and the registered
9//! providers (analytics, fingerprint, user). [`ContextPropagation`] models
10//! how request-scoped state moves across HTTP boundaries.
11//!
12//! Copyright (c) systemprompt.io — Business Source License 1.1.
13//! See <https://systemprompt.io> for licensing details.
14
15use async_trait::async_trait;
16use std::sync::Arc;
17
18use crate::analytics::{AnalyticsProvider, FingerprintProvider};
19use crate::auth::UserProvider;
20
21pub trait AppContext: Send + Sync {
22    fn config(&self) -> Arc<dyn ConfigProvider>;
23    fn database_handle(&self) -> Arc<dyn DatabaseHandle>;
24    fn analytics_provider(&self) -> Option<Arc<dyn AnalyticsProvider>>;
25    fn fingerprint_provider(&self) -> Option<Arc<dyn FingerprintProvider>>;
26    fn user_provider(&self) -> Option<Arc<dyn UserProvider>>;
27}
28
29pub trait InjectContextHeaders {
30    fn inject_headers(&self, headers: &mut http::HeaderMap);
31}
32
33pub type ContextPropagationResult<T> = Result<T, ContextPropagationError>;
34
35#[derive(Debug, thiserror::Error)]
36#[non_exhaustive]
37pub enum ContextPropagationError {
38    #[error("missing header: {0}")]
39    MissingHeader(String),
40
41    #[error("invalid header {name}: {message}")]
42    InvalidHeader { name: String, message: String },
43
44    #[error("invalid context: {0}")]
45    Invalid(String),
46}
47
48pub trait ContextPropagation {
49    fn from_headers(headers: &http::HeaderMap) -> ContextPropagationResult<Self>
50    where
51        Self: Sized;
52
53    fn to_headers(&self) -> http::HeaderMap;
54}
55
56pub trait ConfigProvider: Send + Sync {
57    fn get(&self, key: &str) -> Option<String>;
58    fn database_url(&self) -> &str;
59    fn database_write_url(&self) -> Option<&str> {
60        None
61    }
62    fn system_path(&self) -> &str;
63    fn api_port(&self) -> u16;
64    fn as_any(&self) -> &dyn std::any::Any;
65}
66
67pub trait ModuleRegistry: Send + Sync {
68    fn get_module(&self, name: &str) -> Option<Arc<dyn Module>>;
69    fn list_modules(&self) -> Vec<String>;
70}
71
72pub trait DatabaseHandle: Send + Sync {
73    fn is_connected(&self) -> bool;
74    fn as_any(&self) -> &dyn std::any::Any;
75}
76
77#[async_trait]
78pub trait Module: Send + Sync {
79    fn name(&self) -> &str;
80    fn version(&self) -> &str;
81    fn display_name(&self) -> &str;
82    async fn initialize(&self) -> Result<(), Box<dyn std::error::Error>>;
83}
84
85#[cfg(feature = "web")]
86#[async_trait]
87pub trait ApiModule: Module {
88    fn router(&self, ctx: Arc<dyn AppContext>) -> axum::Router;
89}