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