Skip to main content

systemprompt_runtime/builder/
mod.rs

1//! Builder that assembles an [`AppContext`] from profile + config state.
2//!
3//! The builder owns the bootstrap order: profile -> paths -> files ->
4//! database -> logging -> extensions -> ancillary services. Failures at
5//! any step propagate as [`RuntimeError`](crate::error::RuntimeError).
6//! Subsystem resolution helpers live in [`assembly`].
7//!
8//! Copyright (c) systemprompt.io — Business Source License 1.1.
9//! See <https://systemprompt.io> for licensing details.
10
11mod assembly;
12mod composition;
13mod core_layer;
14
15use composition::{build_data_plane, build_repositories, build_subsystems, ensure_legacy_context};
16
17use std::sync::{Arc, OnceLock};
18
19use systemprompt_database::MigrationConfig;
20use systemprompt_extension::ExtensionRegistry;
21use systemprompt_marketplace::MarketplaceFilter;
22use systemprompt_mcp::services::registry::RegistryService;
23use systemprompt_security::authz::{AuthzDecisionHook, SharedAuthzHook};
24use systemprompt_security::policy::GovernanceEngine;
25use systemprompt_users::UserService;
26
27use crate::context::{AppContext, ConfigPlane, DataPlane, Plugins, ShutdownRequest, Subsystems};
28use crate::error::RuntimeResult;
29use crate::registry::ModuleApiRegistry;
30pub use core_layer::discover_vertex_models as discover_models;
31use core_layer::{CoreLayer, init_core, init_extensions};
32
33/// Assembles an [`AppContext`], owning the bootstrap order described on the
34/// module.
35///
36/// All fields default to a no-op build: extensions are discovered via
37/// inventory, schema installation is off, and the marketplace filter falls
38/// back to the inventory-registered implementation (or an allow-all filter).
39/// Override these with the `with_*` methods before calling
40/// [`build`](Self::build).
41#[derive(Default)]
42pub struct AppContextBuilder {
43    extension_registry: Option<ExtensionRegistry>,
44    show_startup_warnings: bool,
45    marketplace_filter: Option<Arc<dyn MarketplaceFilter>>,
46    authz_hook: Option<SharedAuthzHook>,
47    install_schemas: bool,
48    migration_config: MigrationConfig,
49    shutdown: Option<ShutdownRequest>,
50}
51
52impl std::fmt::Debug for AppContextBuilder {
53    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54        f.debug_struct("AppContextBuilder")
55            .field("extension_registry", &self.extension_registry.is_some())
56            .field("show_startup_warnings", &self.show_startup_warnings)
57            .field("marketplace_filter", &self.marketplace_filter.is_some())
58            .field("authz_hook", &self.authz_hook.is_some())
59            .field("install_schemas", &self.install_schemas)
60            .field("migration_config", &self.migration_config)
61            .field("shutdown", &self.shutdown.is_some())
62            .finish()
63    }
64}
65
66impl AppContextBuilder {
67    #[must_use]
68    pub fn new() -> Self {
69        Self::default()
70    }
71
72    #[must_use]
73    pub fn with_extensions(mut self, registry: ExtensionRegistry) -> Self {
74        self.extension_registry = Some(registry);
75        self
76    }
77
78    #[must_use]
79    pub const fn with_startup_warnings(mut self, show: bool) -> Self {
80        self.show_startup_warnings = show;
81        self
82    }
83
84    #[must_use]
85    pub fn with_marketplace_filter(mut self, filter: Arc<dyn MarketplaceFilter>) -> Self {
86        self.marketplace_filter = Some(filter);
87        self
88    }
89
90    #[must_use]
91    pub const fn with_migrations(mut self, install: bool) -> Self {
92        self.install_schemas = install;
93        self
94    }
95
96    #[must_use]
97    pub fn with_authz_hook<H>(mut self, hook: H) -> Self
98    where
99        H: AuthzDecisionHook + 'static,
100    {
101        self.authz_hook = Some(Arc::new(hook));
102        self
103    }
104
105    #[must_use]
106    pub fn with_shared_authz_hook(mut self, hook: SharedAuthzHook) -> Self {
107        self.authz_hook = Some(hook);
108        self
109    }
110
111    #[must_use]
112    pub fn with_shutdown(mut self, shutdown: ShutdownRequest) -> Self {
113        self.shutdown = Some(shutdown);
114        self
115    }
116
117    #[must_use]
118    pub const fn with_migration_config(mut self, config: MigrationConfig) -> Self {
119        self.migration_config = config;
120        self
121    }
122
123    pub async fn build(self) -> RuntimeResult<AppContext> {
124        let shutdown = self.shutdown.unwrap_or_default();
125        let CoreLayer {
126            config,
127            app_paths,
128            database,
129            authz_hook,
130            file_storage,
131        } = init_core(self.authz_hook).await?;
132
133        let api_registry = Arc::new(ModuleApiRegistry::new());
134        let extension_registry = init_extensions(
135            self.extension_registry,
136            self.install_schemas,
137            self.migration_config,
138            &database,
139        )
140        .await?;
141
142        GovernanceEngine::global()?;
143
144        let assembly::ContentAnalytics {
145            geoip_reader,
146            content_config,
147            route_classifier,
148            analytics_service,
149            analytics_repositories,
150            fingerprint_repo,
151        } = assembly::assemble_content_analytics(
152            &config,
153            &app_paths,
154            &database,
155            self.show_startup_warnings,
156        )?;
157
158        let instance_id = systemprompt_identifiers::InstanceId::new(&config.instance_id);
159        let repositories = build_repositories(&database, analytics_repositories, instance_id)?;
160
161        let user_service = Arc::new(UserService::new(Arc::clone(&repositories.users)));
162
163        let system_admin =
164            assembly::resolve_and_install_system_admin(&config, &user_service).await?;
165        let mcp_registry = RegistryService::new(system_admin.id().clone());
166
167        ensure_legacy_context(&repositories, &system_admin).await?;
168
169        let marketplace_filter = self
170            .marketplace_filter
171            .unwrap_or_else(|| assembly::build_marketplace_filter(&database));
172
173        let subsystems = build_subsystems(
174            system_admin,
175            authz_hook,
176            geoip_reader,
177            file_storage,
178            shutdown,
179        );
180
181        Ok(AppContext::from_parts(
182            build_data_plane(
183                database,
184                analytics_service,
185                fingerprint_repo,
186                user_service,
187                repositories,
188            ),
189            ConfigPlane {
190                config,
191                app_paths,
192                content_config,
193                route_classifier,
194            },
195            Plugins {
196                extension_registry,
197                api_registry,
198                mcp_registry,
199                marketplace_filter,
200            },
201            subsystems,
202        ))
203    }
204}