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