Skip to main content

systemprompt_models/config/
mod.rs

1use anyhow::Result;
2use std::sync::OnceLock;
3use systemprompt_traits::ConfigProvider;
4
5use crate::auth::JwtAudience;
6use crate::profile::{ContentNegotiationConfig, Profile, SecurityHeadersConfig};
7use crate::profile_bootstrap::ProfileBootstrap;
8use crate::secrets_bootstrap::SecretsBootstrap;
9
10mod environment;
11mod paths;
12mod rate_limits;
13mod validation;
14mod verbosity;
15
16pub use environment::Environment;
17pub use paths::PathNotConfiguredError;
18pub use rate_limits::RateLimitConfig;
19pub use validation::{
20    format_path_errors, validate_optional_path, validate_postgres_url, validate_profile_paths,
21    validate_required_optional_path, validate_required_path,
22};
23pub use verbosity::VerbosityLevel;
24
25static CONFIG: OnceLock<Config> = OnceLock::new();
26
27struct BuildConfigPaths {
28    system: String,
29    skills: String,
30    settings: String,
31    content_config: String,
32    web: String,
33    web_config: String,
34    web_metadata: String,
35}
36
37#[derive(Debug, Clone)]
38pub struct Config {
39    pub sitename: String,
40    pub database_type: String,
41    pub database_url: String,
42    pub database_write_url: Option<String>,
43    pub github_link: String,
44    pub github_token: Option<String>,
45    pub system_path: String,
46    pub services_path: String,
47    pub bin_path: String,
48    pub skills_path: String,
49    pub settings_path: String,
50    pub content_config_path: String,
51    pub geoip_database_path: Option<String>,
52    pub web_path: String,
53    pub web_config_path: String,
54    pub web_metadata_path: String,
55    pub host: String,
56    pub port: u16,
57    pub api_server_url: String,
58    pub api_internal_url: String,
59    pub api_external_url: String,
60    pub jwt_issuer: String,
61    pub jwt_access_token_expiration: i64,
62    pub jwt_refresh_token_expiration: i64,
63    pub jwt_audiences: Vec<JwtAudience>,
64    pub use_https: bool,
65    pub rate_limits: RateLimitConfig,
66    pub cors_allowed_origins: Vec<String>,
67    pub is_cloud: bool,
68    pub content_negotiation: ContentNegotiationConfig,
69    pub security_headers: SecurityHeadersConfig,
70    pub allow_registration: bool,
71}
72
73impl Config {
74    pub fn is_initialized() -> bool {
75        CONFIG.get().is_some()
76    }
77
78    pub fn init() -> Result<()> {
79        let profile = ProfileBootstrap::get()
80            .map_err(|e| anyhow::anyhow!("Profile not initialized: {}", e))?;
81
82        let config = Self::from_profile(profile)?;
83        CONFIG
84            .set(config)
85            .map_err(|_| anyhow::anyhow!("Config already initialized"))?;
86        Ok(())
87    }
88
89    pub fn try_init() -> Result<()> {
90        if Self::is_initialized() {
91            return Ok(());
92        }
93        Self::init()
94    }
95
96    pub fn get() -> Result<&'static Self> {
97        CONFIG
98            .get()
99            .ok_or_else(|| anyhow::anyhow!("Config not initialized. Call Config::init() first."))
100    }
101
102    pub fn from_profile(profile: &Profile) -> Result<Self> {
103        let profile_path = ProfileBootstrap::get_path()
104            .map_or_else(|_| "<not set>".to_string(), ToString::to_string);
105
106        let path_report = validate_profile_paths(profile, &profile_path);
107        if path_report.has_errors() {
108            return Err(anyhow::anyhow!(
109                "{}",
110                format_path_errors(&path_report, &profile_path)
111            ));
112        }
113
114        let system_path = Self::canonicalize_path(&profile.paths.system, "system")?;
115
116        let skills_path = profile.paths.skills();
117        let settings_path =
118            Self::require_yaml_path("config", Some(&profile.paths.config()), &profile_path)?;
119        let content_config_path = Self::require_yaml_path(
120            "content_config",
121            Some(&profile.paths.content_config()),
122            &profile_path,
123        )?;
124        let web_path = profile.paths.web_path_resolved();
125        let web_config_path = Self::require_yaml_path(
126            "web_config",
127            Some(&profile.paths.web_config()),
128            &profile_path,
129        )?;
130        let web_metadata_path = Self::require_yaml_path(
131            "web_metadata",
132            Some(&profile.paths.web_metadata()),
133            &profile_path,
134        )?;
135
136        let paths = BuildConfigPaths {
137            system: system_path,
138            skills: skills_path,
139            settings: settings_path,
140            content_config: content_config_path,
141            web: web_path,
142            web_config: web_config_path,
143            web_metadata: web_metadata_path,
144        };
145        let config = Self::build_config(profile, paths)?;
146
147        config.validate_database_config()?;
148        Ok(config)
149    }
150
151    fn canonicalize_path(path: &str, name: &str) -> Result<String> {
152        std::fs::canonicalize(path)
153            .map(|p| p.to_string_lossy().to_string())
154            .map_err(|e| anyhow::anyhow!("Failed to canonicalize {} path: {}", name, e))
155    }
156
157    fn require_yaml_path(field: &str, value: Option<&str>, profile_path: &str) -> Result<String> {
158        let path =
159            value.ok_or_else(|| anyhow::anyhow!("Missing required path: paths.{}", field))?;
160
161        let content = std::fs::read_to_string(path).map_err(|e| {
162            anyhow::anyhow!(
163                "Profile Error: Cannot read file\n\n  Field: paths.{}\n  Path: {}\n  Error: {}\n  \
164                 Profile: {}",
165                field,
166                path,
167                e,
168                profile_path
169            )
170        })?;
171
172        serde_yaml::from_str::<serde_yaml::Value>(&content).map_err(|e| {
173            anyhow::anyhow!(
174                "Profile Error: Invalid YAML syntax\n\n  Field: paths.{}\n  Path: {}\n  Error: \
175                 {}\n  Profile: {}",
176                field,
177                path,
178                e,
179                profile_path
180            )
181        })?;
182
183        Ok(path.to_string())
184    }
185
186    fn build_config(profile: &Profile, paths: BuildConfigPaths) -> Result<Self> {
187        let secrets = SecretsBootstrap::get().map_err(|_| {
188            anyhow::anyhow!(
189                "Secrets not initialized. Call SecretsBootstrap::init() before \
190                 Config::from_profile()"
191            )
192        })?;
193
194        Ok(Self {
195            sitename: profile.site.name.clone(),
196            database_type: profile.database.db_type.clone(),
197            database_url: secrets.database_url.clone(),
198            database_write_url: secrets.database_write_url.clone(),
199            github_link: profile
200                .site
201                .github_link
202                .clone()
203                .unwrap_or_else(|| "https://github.com/systemprompt/systemprompt-os".to_string()),
204            github_token: secrets.github.clone(),
205            system_path: paths.system,
206            services_path: profile.paths.services.clone(),
207            bin_path: profile.paths.bin.clone(),
208            skills_path: paths.skills,
209            settings_path: paths.settings,
210            content_config_path: paths.content_config,
211            geoip_database_path: profile.paths.geoip_database.clone(),
212            web_path: paths.web,
213            web_config_path: paths.web_config,
214            web_metadata_path: paths.web_metadata,
215            host: profile.server.host.clone(),
216            port: profile.server.port,
217            api_server_url: profile.server.api_server_url.clone(),
218            api_internal_url: profile.server.api_internal_url.clone(),
219            api_external_url: profile.server.api_external_url.clone(),
220            jwt_issuer: profile.security.issuer.clone(),
221            jwt_access_token_expiration: profile.security.access_token_expiration,
222            jwt_refresh_token_expiration: profile.security.refresh_token_expiration,
223            jwt_audiences: profile.security.audiences.clone(),
224            use_https: profile.server.use_https,
225            rate_limits: (&profile.rate_limits).into(),
226            cors_allowed_origins: profile.server.cors_allowed_origins.clone(),
227            is_cloud: profile.target.is_cloud(),
228            content_negotiation: profile.server.content_negotiation.clone(),
229            security_headers: profile.server.security_headers.clone(),
230            allow_registration: profile.security.allow_registration,
231        })
232    }
233
234    pub fn init_from_profile(profile: &Profile) -> Result<()> {
235        let config = Self::from_profile(profile)?;
236        CONFIG
237            .set(config)
238            .map_err(|_| anyhow::anyhow!("Config already initialized"))?;
239        Ok(())
240    }
241
242    pub fn validate_database_config(&self) -> Result<()> {
243        let db_type = self.database_type.to_lowercase();
244
245        if db_type != "postgres" && db_type != "postgresql" {
246            return Err(anyhow::anyhow!(
247                "Unsupported database type '{}'. Only 'postgres' is supported.",
248                self.database_type
249            ));
250        }
251
252        validate_postgres_url(&self.database_url)?;
253        if let Some(write_url) = &self.database_write_url {
254            validate_postgres_url(write_url)?;
255        }
256        Ok(())
257    }
258}
259
260impl ConfigProvider for Config {
261    fn get(&self, key: &str) -> Option<String> {
262        match key {
263            "database_type" => Some(self.database_type.clone()),
264            "database_url" => Some(self.database_url.clone()),
265            "database_write_url" => self.database_write_url.clone(),
266            "host" => Some(self.host.clone()),
267            "port" => Some(self.port.to_string()),
268            "system_path" => Some(self.system_path.clone()),
269            "services_path" => Some(self.services_path.clone()),
270            "bin_path" => Some(self.bin_path.clone()),
271            "skills_path" => Some(self.skills_path.clone()),
272            "settings_path" => Some(self.settings_path.clone()),
273            "content_config_path" => Some(self.content_config_path.clone()),
274            "web_path" => Some(self.web_path.clone()),
275            "web_config_path" => Some(self.web_config_path.clone()),
276            "web_metadata_path" => Some(self.web_metadata_path.clone()),
277            "sitename" => Some(self.sitename.clone()),
278            "github_link" => Some(self.github_link.clone()),
279            "github_token" => self.github_token.clone(),
280            "api_server_url" => Some(self.api_server_url.clone()),
281            "api_external_url" => Some(self.api_external_url.clone()),
282            "jwt_issuer" => Some(self.jwt_issuer.clone()),
283            "is_cloud" => Some(self.is_cloud.to_string()),
284            _ => None,
285        }
286    }
287
288    fn database_url(&self) -> &str {
289        &self.database_url
290    }
291
292    fn database_write_url(&self) -> Option<&str> {
293        self.database_write_url.as_deref()
294    }
295
296    fn system_path(&self) -> &str {
297        &self.system_path
298    }
299
300    fn api_port(&self) -> u16 {
301        self.port
302    }
303
304    fn as_any(&self) -> &dyn std::any::Any {
305        self
306    }
307}