Skip to main content

systemprompt_runtime/
context.rs

1use crate::registry::ModuleApiRegistry;
2use anyhow::Result;
3use std::sync::Arc;
4use systemprompt_analytics::{AnalyticsService, FingerprintRepository, GeoIpReader};
5use systemprompt_database::{Database, DbPool};
6use systemprompt_extension::{Extension, ExtensionContext, ExtensionRegistry};
7use systemprompt_logging::CliService;
8use systemprompt_models::{
9    AppPaths, Config, ContentConfigRaw, ContentRouting, ProfileBootstrap, RouteClassifier,
10};
11use systemprompt_traits::{
12    AnalyticsProvider, AppContext as AppContextTrait, ConfigProvider, DatabaseHandle,
13    FingerprintProvider, UserProvider,
14};
15use systemprompt_users::UserService;
16
17#[derive(Clone)]
18pub struct AppContext {
19    config: Arc<Config>,
20    database: DbPool,
21    api_registry: Arc<ModuleApiRegistry>,
22    extension_registry: Arc<ExtensionRegistry>,
23    geoip_reader: Option<GeoIpReader>,
24    content_config: Option<Arc<ContentConfigRaw>>,
25    route_classifier: Arc<RouteClassifier>,
26    analytics_service: Arc<AnalyticsService>,
27    fingerprint_repo: Option<Arc<FingerprintRepository>>,
28    user_service: Option<Arc<UserService>>,
29}
30
31impl std::fmt::Debug for AppContext {
32    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33        f.debug_struct("AppContext")
34            .field("config", &"Config")
35            .field("database", &"DbPool")
36            .field("api_registry", &"ModuleApiRegistry")
37            .field("extension_registry", &self.extension_registry)
38            .field("geoip_reader", &self.geoip_reader.is_some())
39            .field("content_config", &self.content_config.is_some())
40            .field("route_classifier", &"RouteClassifier")
41            .field("analytics_service", &"AnalyticsService")
42            .field("fingerprint_repo", &self.fingerprint_repo.is_some())
43            .field("user_service", &self.user_service.is_some())
44            .finish()
45    }
46}
47
48impl AppContext {
49    pub async fn new() -> Result<Self> {
50        Self::builder().build().await
51    }
52
53    #[must_use]
54    pub fn builder() -> AppContextBuilder {
55        AppContextBuilder::new()
56    }
57
58    async fn new_internal(
59        extension_registry: Option<ExtensionRegistry>,
60        show_startup_warnings: bool,
61    ) -> Result<Self> {
62        let profile = ProfileBootstrap::get()?;
63        AppPaths::init(&profile.paths)?;
64        systemprompt_files::FilesConfig::init()?;
65        let config = Arc::new(Config::get()?.clone());
66        let database = Arc::new(
67            Database::from_config_with_write(
68                &config.database_type,
69                &config.database_url,
70                config.database_write_url.as_deref(),
71            )
72            .await?,
73        );
74
75        if config.database_write_url.is_some() {
76            tracing::info!(
77                "Database read/write separation enabled: reads from replica, writes to primary"
78            );
79        }
80
81        let api_registry = Arc::new(ModuleApiRegistry::new());
82
83        let registry = extension_registry.unwrap_or_else(ExtensionRegistry::discover);
84        registry.validate()?;
85
86        let extension_registry = Arc::new(registry);
87
88        let geoip_reader = Self::load_geoip_database(&config, show_startup_warnings);
89        let content_config = Self::load_content_config(&config);
90
91        #[allow(trivial_casts)]
92        let content_routing: Option<Arc<dyn ContentRouting>> =
93            content_config.clone().map(|c| c as Arc<dyn ContentRouting>);
94
95        let route_classifier = Arc::new(RouteClassifier::new(content_routing.clone()));
96
97        let analytics_service = Arc::new(AnalyticsService::new(
98            &database,
99            geoip_reader.clone(),
100            content_routing,
101        )?);
102
103        let fingerprint_repo = FingerprintRepository::new(&database).ok().map(Arc::new);
104
105        let user_service = UserService::new(&database).ok().map(Arc::new);
106
107        systemprompt_logging::init_logging(Arc::clone(&database));
108
109        Ok(Self {
110            config,
111            database,
112            api_registry,
113            extension_registry,
114            geoip_reader,
115            content_config,
116            route_classifier,
117            analytics_service,
118            fingerprint_repo,
119            user_service,
120        })
121    }
122
123    fn load_geoip_database(config: &Config, show_warnings: bool) -> Option<GeoIpReader> {
124        let Some(geoip_path) = &config.geoip_database_path else {
125            if show_warnings {
126                CliService::warning(
127                    "GeoIP database not configured - geographic data will not be available",
128                );
129                CliService::info("  To enable geographic data:");
130                CliService::info("  1. Download MaxMind GeoLite2-City database from: https://dev.maxmind.com/geoip/geolite2-free-geolocation-data");
131                CliService::info(
132                    "  2. Add paths.geoip_database to your profile pointing to the .mmdb file",
133                );
134            }
135            return None;
136        };
137
138        match maxminddb::Reader::open_readfile(geoip_path) {
139            Ok(reader) => Some(Arc::new(reader)),
140            Err(e) => {
141                if show_warnings {
142                    CliService::warning(&format!(
143                        "Could not load GeoIP database from {geoip_path}: {e}"
144                    ));
145                    CliService::info(
146                        "  Geographic data (country/region/city) will not be available.",
147                    );
148                    CliService::info(
149                        "  To fix: Ensure the path is correct and the file is a valid MaxMind \
150                         .mmdb database",
151                    );
152                }
153                None
154            },
155        }
156    }
157
158    fn load_content_config(config: &Config) -> Option<Arc<ContentConfigRaw>> {
159        let content_config_path = AppPaths::get()
160            .ok()?
161            .system()
162            .content_config()
163            .to_path_buf();
164
165        if !content_config_path.exists() {
166            CliService::warning(&format!(
167                "Content config not found at: {}",
168                content_config_path.display()
169            ));
170            CliService::info("  Landing page detection will not be available.");
171            return None;
172        }
173
174        let yaml_content = match std::fs::read_to_string(&content_config_path) {
175            Ok(c) => c,
176            Err(e) => {
177                CliService::warning(&format!(
178                    "Could not read content config from {}: {}",
179                    content_config_path.display(),
180                    e
181                ));
182                CliService::info("  Landing page detection will not be available.");
183                return None;
184            },
185        };
186
187        match serde_yaml::from_str::<ContentConfigRaw>(&yaml_content) {
188            Ok(mut content_cfg) => {
189                let base_url = config.api_external_url.trim_end_matches('/');
190
191                content_cfg.metadata.structured_data.organization.url = base_url.to_string();
192
193                let logo = &content_cfg.metadata.structured_data.organization.logo;
194                if logo.starts_with('/') {
195                    content_cfg.metadata.structured_data.organization.logo =
196                        format!("{base_url}{logo}");
197                }
198
199                Some(Arc::new(content_cfg))
200            },
201            Err(e) => {
202                CliService::warning(&format!(
203                    "Could not parse content config from {}: {}",
204                    content_config_path.display(),
205                    e
206                ));
207                CliService::info("  Landing page detection will not be available.");
208                None
209            },
210        }
211    }
212
213    pub fn config(&self) -> &Config {
214        &self.config
215    }
216
217    pub fn content_config(&self) -> Option<&ContentConfigRaw> {
218        self.content_config.as_ref().map(AsRef::as_ref)
219    }
220
221    #[allow(trivial_casts)]
222    pub fn content_routing(&self) -> Option<Arc<dyn ContentRouting>> {
223        self.content_config
224            .clone()
225            .map(|c| c as Arc<dyn ContentRouting>)
226    }
227
228    pub const fn db_pool(&self) -> &DbPool {
229        &self.database
230    }
231
232    pub const fn database(&self) -> &DbPool {
233        &self.database
234    }
235
236    pub fn api_registry(&self) -> &ModuleApiRegistry {
237        &self.api_registry
238    }
239
240    pub fn extension_registry(&self) -> &ExtensionRegistry {
241        &self.extension_registry
242    }
243
244    pub fn server_address(&self) -> String {
245        format!("{}:{}", self.config.host, self.config.port)
246    }
247
248    pub fn get_provided_audiences() -> Vec<String> {
249        vec!["a2a".to_string(), "api".to_string(), "mcp".to_string()]
250    }
251
252    pub fn get_valid_audiences(_module_name: &str) -> Vec<String> {
253        Self::get_provided_audiences()
254    }
255
256    pub fn get_server_audiences(_server_name: &str, _port: u16) -> Vec<String> {
257        Self::get_provided_audiences()
258    }
259
260    pub const fn geoip_reader(&self) -> Option<&GeoIpReader> {
261        self.geoip_reader.as_ref()
262    }
263
264    pub const fn analytics_service(&self) -> &Arc<AnalyticsService> {
265        &self.analytics_service
266    }
267
268    pub const fn route_classifier(&self) -> &Arc<RouteClassifier> {
269        &self.route_classifier
270    }
271}
272
273#[allow(clippy::clone_on_ref_ptr)]
274impl AppContextTrait for AppContext {
275    fn config(&self) -> Arc<dyn ConfigProvider> {
276        self.config.clone()
277    }
278
279    fn database_handle(&self) -> Arc<dyn DatabaseHandle> {
280        self.database.clone()
281    }
282
283    fn analytics_provider(&self) -> Option<Arc<dyn AnalyticsProvider>> {
284        Some(self.analytics_service.clone())
285    }
286
287    fn fingerprint_provider(&self) -> Option<Arc<dyn FingerprintProvider>> {
288        let provider: Arc<dyn FingerprintProvider> = self.fingerprint_repo.clone()?;
289        Some(provider)
290    }
291
292    fn user_provider(&self) -> Option<Arc<dyn UserProvider>> {
293        let provider: Arc<dyn UserProvider> = self.user_service.clone()?;
294        Some(provider)
295    }
296}
297
298#[allow(clippy::clone_on_ref_ptr)]
299impl ExtensionContext for AppContext {
300    fn config(&self) -> Arc<dyn ConfigProvider> {
301        self.config.clone()
302    }
303
304    fn database(&self) -> Arc<dyn DatabaseHandle> {
305        self.database.clone()
306    }
307
308    fn get_extension(&self, id: &str) -> Option<Arc<dyn Extension>> {
309        self.extension_registry.get(id).cloned()
310    }
311}
312
313#[derive(Debug, Default)]
314pub struct AppContextBuilder {
315    extension_registry: Option<ExtensionRegistry>,
316    show_startup_warnings: bool,
317}
318
319impl AppContextBuilder {
320    #[must_use]
321    pub fn new() -> Self {
322        Self::default()
323    }
324
325    #[must_use]
326    pub fn with_extensions(mut self, registry: ExtensionRegistry) -> Self {
327        self.extension_registry = Some(registry);
328        self
329    }
330
331    #[must_use]
332    pub const fn with_startup_warnings(mut self, show: bool) -> Self {
333        self.show_startup_warnings = show;
334        self
335    }
336
337    pub async fn build(self) -> Result<AppContext> {
338        AppContext::new_internal(self.extension_registry, self.show_startup_warnings).await
339    }
340}