1use std::{
2 collections::BTreeMap,
3 env,
4 error::Error,
5 ffi::OsString,
6 fmt, fs, io,
7 path::{Path, PathBuf},
8 time::Duration,
9};
10
11pub use crate::activity::ActivityConfig;
12use cortexkit_log::Retention;
13use serde::Deserialize;
14use subc_control::ModuleProtocol;
15use subc_jsonc::jsonc_to_json;
16use subc_protocol::manifest::is_valid_capability_identifier;
17
18use crate::{
19 supervise::{ModuleOverlap, ScriptEntry, ScriptRuntime, SUBC_SPAWN_ROLE_ENV},
20 HealthAction, HealthConfig, ModuleSpec, RestartPolicy,
21};
22
23const DAEMON_CONFIG_RELATIVE_PATH: &str = "cortexkit/subc.jsonc";
24const SUPPORTED_CONFIG_VERSION: u32 = 1;
25pub(crate) const CK_LOG_ENV: &str = "CK_LOG";
26pub(crate) const CAPTURE_MAX_FILE_MB_ENV: &str = "__SUBC_CAPTURE_LOG_MAX_FILE_MB";
27pub(crate) const CAPTURE_KEEP_ENV: &str = "__SUBC_CAPTURE_LOG_KEEP";
28pub(crate) const CAPTURE_MAX_AGE_DAYS_ENV: &str = "__SUBC_CAPTURE_LOG_MAX_AGE_DAYS";
29pub(crate) const CHILD_LOG_MAX_AGE_DAYS_ENV: &str = "CK_LOG_MAX_AGE_DAYS";
33pub(crate) const CHILD_LOG_ALARM_SEGMENT_MB_ENV: &str = "CK_LOG_ALARM_SEGMENT_MB";
34
35#[derive(Clone, Copy, Debug, Eq, PartialEq)]
49pub enum RestartRequiredSection {
50 Port,
51 Storage,
52 AdmissionFactsCarrierModuleId,
53 AdmissionFactsTargets,
54 ScopeAuthorityOwners,
55 FederatedScopeOwner,
56 PrivilegedOperatorPrompt,
57}
58
59impl RestartRequiredSection {
60 pub const ALL: [Self; 7] = [
61 Self::Port,
62 Self::Storage,
63 Self::AdmissionFactsCarrierModuleId,
64 Self::AdmissionFactsTargets,
65 Self::ScopeAuthorityOwners,
66 Self::FederatedScopeOwner,
67 Self::PrivilegedOperatorPrompt,
68 ];
69
70 pub const fn label(self) -> &'static str {
71 match self {
72 Self::Port => "port",
73 Self::Storage => "storage",
74 Self::AdmissionFactsCarrierModuleId => "admission_facts_carrier_module_id",
75 Self::AdmissionFactsTargets => "admission_facts_targets",
76 Self::ScopeAuthorityOwners => "scope_authority_owners",
77 Self::FederatedScopeOwner => "federated_scope_owner",
78 Self::PrivilegedOperatorPrompt => "privileged_operator_prompt",
79 }
80 }
81}
82
83#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq)]
85#[serde(rename_all = "lowercase")]
86pub enum PrivilegedOperatorPrompt {
87 #[default]
88 Log,
89 Enforce,
90}
91
92pub fn default_scope_authority_owners() -> Vec<String> {
96 vec!["prefrontal-core".to_string(), "prefrontal".to_string()]
97}
98
99pub fn default_federated_scope_owner() -> String {
100 "callosum".to_string()
101}
102
103const ROUTE_BIND_RELAY_ZERO_MESSAGE: &str = "route_bind_relay_timeout_ms must be greater than 0 (a zero budget fails every bind to the module; to make a module unreachable use enabled: false)";
114
115const RESTART_WINDOW_ZERO_MESSAGE: &str = "restart.window_secs must be greater than 0 (a zero window holds no crash, so the budget can never be spent; for effectively unlimited restarts set a deliberately large window_secs, and to stop restarting entirely set restart.max_restarts: 0)";
122
123#[derive(Debug, Clone, PartialEq, Eq)]
130pub struct LoggingConfig {
131 pub level: String,
132 pub tags: BTreeMap<String, String>,
137 pub retention: Retention,
138 pub alarm_segment_mb: u32,
140}
141
142impl LoggingConfig {
143 pub fn filter_spec(&self, module_id: &str) -> String {
152 let mut directives = vec![self.level.clone()];
153 directives.extend(self.tags.iter().map(|(logger, level)| {
154 if logger == module_id || logger.contains('.') {
155 format!("{logger}={level}")
156 } else {
157 format!("{module_id}.{logger}={level}")
158 }
159 }));
160 directives.join(",")
161 }
162
163 pub fn segment_retention(&self) -> cortexkit_log::SegmentRetention {
164 cortexkit_log::SegmentRetention {
165 max_age_days: self.retention.max_age_days,
166 alarm_segment_mb: self.alarm_segment_mb,
167 }
168 }
169}
170
171#[derive(Debug, Clone, PartialEq, Eq)]
172pub struct DaemonConfig {
173 pub path: PathBuf,
174 pub port: Option<u16>,
175 pub privileged_operator_prompt: PrivilegedOperatorPrompt,
177 pub drain_timeout_ms: Option<u64>,
181 pub route_bind_relay_timeout_ms: Option<u64>,
190 pub modules: Vec<ConfiguredModule>,
191 pub storage: Option<StorageConfig>,
194 pub admission_facts_carrier_module_id: Option<String>,
196 pub admission_facts_targets: Option<Vec<String>>,
198 pub scope_authority_owners: Vec<String>,
204 pub federated_scope_owner: String,
206 pub reserved_capabilities: BTreeMap<String, String>,
210}
211
212#[derive(Debug, Clone, PartialEq, Eq)]
216pub enum StorageConfig {
217 Sqlite { data_home: PathBuf },
219}
220
221impl StorageConfig {
222 pub fn descriptor_for(&self, module_id: &str) -> serde_json::Value {
248 match self {
249 StorageConfig::Sqlite { data_home } => {
258 let data_home = data_home.to_string_lossy();
259 let path = format!(
260 "{}/cortexkit/{module_id}/store.db",
261 data_home.trim_end_matches('/')
262 );
263 serde_json::json!({
264 "module_id": module_id,
265 "storage_namespace": "default",
266 "isolation": { "kind": "module" },
267 "backend": { "backend": "sqlite", "path": path },
268 })
269 }
270 }
271 }
272}
273
274#[derive(Debug, Clone, PartialEq, Eq)]
275pub struct ConfiguredModule {
276 pub module_id: String,
277 pub program: PathBuf,
278 pub script: Option<ScriptEntry>,
280 pub args: Vec<String>,
281 pub env: Vec<(String, String)>,
282 pub log: Option<LoggingConfig>,
286 pub enabled: bool,
287 pub registration_channel: bool,
290 pub reserved: bool,
296 pub reserved_prefixes: Vec<String>,
300 pub protocol: ModuleProtocol,
303 pub overlap: ModuleOverlap,
306 pub carry_containment: bool,
309 pub health: HealthConfig,
310 pub drain_timeout_ms: Option<u64>,
313 pub register_timeout: Duration,
316 pub route_bind_relay_timeout_ms: Option<u64>,
321 pub restart: RestartPolicy,
333}
334
335impl ConfiguredModule {
336 pub fn module_spec(&self) -> ModuleSpec {
337 let mut env = self.env.clone();
338 if let Some(log) = &self.log {
339 env.retain(|(key, _)| {
340 key != CK_LOG_ENV
341 && key != CAPTURE_MAX_FILE_MB_ENV
342 && key != CAPTURE_KEEP_ENV
343 && key != CAPTURE_MAX_AGE_DAYS_ENV
344 });
345 env.retain(|(key, _)| {
346 key != CHILD_LOG_MAX_AGE_DAYS_ENV && key != CHILD_LOG_ALARM_SEGMENT_MB_ENV
347 });
348 env.push((CK_LOG_ENV.to_string(), log.filter_spec(&self.module_id)));
349 env.push((
350 CHILD_LOG_MAX_AGE_DAYS_ENV.to_string(),
351 log.retention.max_age_days.to_string(),
352 ));
353 env.push((
354 CHILD_LOG_ALARM_SEGMENT_MB_ENV.to_string(),
355 log.alarm_segment_mb.to_string(),
356 ));
357 env.push((
361 CAPTURE_MAX_FILE_MB_ENV.to_string(),
362 log.retention.max_file_mb.to_string(),
363 ));
364 env.push((CAPTURE_KEEP_ENV.to_string(), log.retention.keep.to_string()));
365 env.push((
366 CAPTURE_MAX_AGE_DAYS_ENV.to_string(),
367 log.retention.max_age_days.to_string(),
368 ));
369 }
370 ModuleSpec {
371 script: self.script.clone(),
372 module_id: self.module_id.clone(),
373 program: self.program.clone(),
374 args: self.args.clone(),
375 env,
376 reserved: self.reserved,
377 reserved_prefixes: self.reserved_prefixes.clone(),
378 protocol: self.protocol,
379 overlap: self.overlap,
380 carry_containment: self.carry_containment,
381 }
382 }
383}
384
385#[derive(Debug)]
386pub enum DaemonConfigError {
387 Read {
388 path: PathBuf,
389 source: io::Error,
390 },
391 InvalidJsonc {
392 path: PathBuf,
393 message: String,
394 },
395 InvalidJson {
396 path: PathBuf,
397 source: serde_json::Error,
398 },
399 UnsupportedVersion {
400 path: PathBuf,
401 version: u32,
402 },
403 InvalidValue {
404 path: PathBuf,
405 message: String,
406 },
407}
408
409#[derive(Debug, Deserialize)]
410struct RawDaemonConfig {
411 version: u32,
412 #[serde(default)]
413 activity: ActivityConfig,
414 #[serde(default)]
415 port: Option<u16>,
416 #[serde(default)]
417 privileged_operator_prompt: PrivilegedOperatorPrompt,
418 #[serde(default)]
419 drain_timeout_ms: Option<u64>,
420 #[serde(default)]
421 route_bind_relay_timeout_ms: Option<u64>,
422 #[serde(default)]
423 log: Option<RawLoggingConfig>,
424 #[serde(default)]
425 modules: BTreeMap<String, RawModuleConfig>,
426 #[serde(default)]
427 storage: Option<RawStorageConfig>,
428 #[serde(default)]
429 admission_facts_carrier_module_id: Option<String>,
430 #[serde(default)]
431 admission_facts_targets: Option<Vec<String>>,
432 #[serde(default)]
433 scope_authority_owners: Option<Vec<String>>,
434 #[serde(default = "default_federated_scope_owner")]
435 federated_scope_owner: String,
436 #[serde(default)]
437 reserved_capabilities: BTreeMap<String, String>,
438}
439
440#[derive(Debug, Deserialize)]
441#[serde(tag = "backend", rename_all = "snake_case")]
442enum RawStorageConfig {
443 Sqlite {
444 #[serde(default)]
447 data_home: Option<PathBuf>,
448 },
449}
450
451#[derive(Debug, Deserialize)]
452struct RawModuleConfig {
453 #[serde(default, deserialize_with = "present_value")]
454 program: Option<PathBuf>,
455 #[serde(default, deserialize_with = "present_value")]
456 script: Option<RawScriptConfig>,
457 #[serde(default)]
458 args: Vec<String>,
459 #[serde(default)]
460 env: BTreeMap<String, String>,
461 #[serde(default)]
462 log: Option<RawLoggingConfig>,
463 #[serde(default = "default_enabled")]
464 enabled: bool,
465 #[serde(default)]
466 registration_channel: bool,
467 #[serde(default)]
468 reserved: bool,
469 #[serde(flatten)]
472 ignored: BTreeMap<String, serde_json::Value>,
473 #[serde(default)]
474 reserved_prefixes: Vec<String>,
475 #[serde(default)]
479 protocol: Option<String>,
480 #[serde(default)]
482 overlap: Option<String>,
483 #[serde(default)]
484 carry_containment: bool,
485 #[serde(default)]
486 health: Option<RawHealthConfig>,
487 #[serde(default)]
488 drain_timeout_ms: Option<u64>,
489 #[serde(default)]
490 register_timeout_s: Option<u64>,
491 #[serde(default)]
492 route_bind_relay_timeout_ms: Option<u64>,
493 #[serde(default)]
494 restart: Option<RawRestartConfig>,
495}
496
497#[derive(Debug, Deserialize)]
498#[serde(deny_unknown_fields)]
499struct RawScriptConfig {
500 runtime: String,
501 path: PathBuf,
502}
503
504fn present_value<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
505where
506 D: serde::Deserializer<'de>,
507 T: Deserialize<'de>,
508{
509 T::deserialize(deserializer).map(Some)
510}
511
512#[cfg(test)]
513mod script_config_tests {
514 use super::*;
515
516 fn parse(entry: serde_json::Value) -> Result<DaemonConfig, DaemonConfigError> {
517 parse_doc(
518 &serde_json::json!({"version":1,"modules":{"example":entry}}).to_string(),
519 Path::new("subc.jsonc"),
520 )
521 }
522
523 #[test]
524 fn script_config_accepts_bun_and_resolves_only_the_installed_runner() {
525 let config =
526 parse(serde_json::json!({"script":{"runtime":"bun","path":"bundle.js"}})).unwrap();
527 assert_eq!(
528 config.modules[0].program,
529 crate::supervise::script::runner_path(ScriptRuntime::Bun).unwrap()
530 );
531 assert_eq!(
532 config.modules[0].module_spec().script,
533 Some(ScriptEntry::new(
534 ScriptRuntime::Bun,
535 std::path::absolute("bundle.js").unwrap()
536 ))
537 );
538 }
539
540 #[test]
541 fn script_config_accepts_python_and_resolves_only_the_installed_runner() {
542 let config =
543 parse(serde_json::json!({"script":{"runtime":"python","path":"bundle.py"}})).unwrap();
544 assert_eq!(
545 config.modules[0].program,
546 crate::supervise::script::runner_path(ScriptRuntime::Python).unwrap()
547 );
548 assert_ne!(
549 config.modules[0].program,
550 crate::supervise::script::runner_path(ScriptRuntime::Bun).unwrap()
551 );
552 assert_eq!(
553 config.modules[0].module_spec().script,
554 Some(ScriptEntry::new(
555 ScriptRuntime::Python,
556 std::path::absolute("bundle.py").unwrap()
557 ))
558 );
559 }
560
561 #[test]
562 fn script_config_refuses_conflicting_missing_null_and_unknown_runtime_entries() {
563 for entry in [
564 serde_json::json!({}),
565 serde_json::json!({"program":"node","script":{"runtime":"bun","path":"bundle.js"}}),
566 serde_json::json!({"program":null,"script":{"runtime":"bun","path":"bundle.js"}}),
567 serde_json::json!({"program":"node","script":null}),
568 serde_json::json!({"script":{"runtime":"node","path":"bundle.js"}}),
569 ] {
570 assert!(parse(entry.clone()).is_err(), "accepted {entry}");
571 }
572 let error = parse(serde_json::json!({"script":{"runtime":"node","path":"bundle.js"}}))
573 .unwrap_err()
574 .to_string();
575 assert!(
576 error.contains("example") && error.contains("node"),
577 "{error}"
578 );
579 }
580
581 #[test]
582 fn script_config_refuses_explicit_runtime_preload_environment() {
583 for key in [
584 "NODE_OPTIONS",
585 "BUN_OPTIONS",
586 "BUN_INSTALL",
587 "NODE_PATH",
588 "BUN_CONFIG_PRELOAD",
589 "BUN_CONFIG_any",
590 "PYTHONPATH",
591 "PYTHONHOME",
592 "PYTHONSTARTUP",
593 "PYTHON_any",
594 ] {
595 let env = BTreeMap::from([(key, "unapproved")]);
596 for runtime in ["bun", "python"] {
597 let error = parse(
598 serde_json::json!({"script":{"runtime":runtime,"path":"bundle.js"},"env":env}),
599 )
600 .unwrap_err()
601 .to_string();
602 assert!(error.contains(key) && error.contains("example"), "{error}");
603 }
604 assert!(parse(serde_json::json!({"program":"legacy-interpreter","env":env})).is_ok());
605 }
606 }
607}
608
609#[derive(Debug, Clone, Deserialize)]
610struct RawLoggingConfig {
611 #[serde(default)]
612 level: Option<String>,
613 #[serde(default)]
614 tags: BTreeMap<String, String>,
615 #[serde(default)]
616 alarm_segment_mb: Option<u32>,
617 #[serde(default)]
618 max_file_mb: Option<u32>,
619 #[serde(default)]
620 keep: Option<u8>,
621 #[serde(default)]
622 max_age_days: Option<u32>,
623}
624
625#[derive(Debug, Deserialize)]
626struct RawRestartConfig {
627 #[serde(default)]
628 max_restarts: Option<u32>,
629 #[serde(default)]
630 window_secs: Option<u64>,
631 #[serde(default)]
632 backoff_ms: Option<u64>,
633 #[serde(default)]
634 max_backoff_ms: Option<u64>,
635}
636
637#[derive(Debug, Deserialize)]
638struct RawHealthConfig {
639 #[serde(default)]
640 http: Option<String>,
641 #[serde(default)]
642 cadence_ms: Option<u64>,
643 #[serde(default)]
644 deadline_ms: Option<u64>,
645 #[serde(default)]
646 failure_threshold: Option<u32>,
647 #[serde(default)]
648 on_degraded: Option<RawHealthAction>,
649 #[serde(default)]
650 on_failing: Option<RawHealthAction>,
651 #[serde(default)]
652 critical: bool,
653}
654
655#[derive(Debug, Deserialize)]
656#[serde(rename_all = "snake_case")]
657enum RawHealthAction {
658 Report,
659 Restart,
660 Alert,
661}
662
663pub fn default_config_path() -> PathBuf {
664 default_config_home().join(DAEMON_CONFIG_RELATIVE_PATH)
665}
666
667pub fn default_config_home() -> PathBuf {
689 if let Some(config_home) = non_empty_os_var("XDG_CONFIG_HOME") {
690 return PathBuf::from(config_home);
691 }
692
693 #[cfg(windows)]
694 {
695 if let Some(app_data) = non_empty_os_var("APPDATA") {
696 return PathBuf::from(app_data);
697 }
698 if let Some(user_profile) = non_empty_os_var("USERPROFILE") {
699 return PathBuf::from(user_profile).join("AppData").join("Roaming");
700 }
701 }
702
703 if let Some(home) = non_empty_os_var("HOME") {
704 return PathBuf::from(home).join(".config");
705 }
706
707 PathBuf::from(".config")
708}
709
710pub fn load(path: impl AsRef<Path>) -> Result<Option<DaemonConfig>, DaemonConfigError> {
711 let path = path.as_ref();
712 let Some(doc) = read_config_doc(path)? else {
713 return Ok(None);
714 };
715 parse_doc(&doc, path).map(Some)
716}
717
718pub fn load_with_activity(
722 path: impl AsRef<Path>,
723) -> Result<Option<(DaemonConfig, ActivityConfig)>, DaemonConfigError> {
724 let path = path.as_ref();
725 let Some(doc) = read_config_doc(path)? else {
726 return Ok(None);
727 };
728 parse_doc_with_activity(&doc, path).map(Some)
729}
730
731pub fn parse_with_activity(
736 doc: &str,
737 path: impl AsRef<Path>,
738) -> Result<(DaemonConfig, ActivityConfig), DaemonConfigError> {
739 parse_doc_with_activity(doc, path.as_ref())
740}
741
742pub fn load_logging(path: impl AsRef<Path>) -> Result<Option<LoggingConfig>, DaemonConfigError> {
748 let path = path.as_ref();
749 let Some(doc) = read_config_doc(path)? else {
750 return Ok(None);
751 };
752 let json = jsonc_to_json(&doc).map_err(|message| DaemonConfigError::InvalidJsonc {
753 path: path.to_path_buf(),
754 message,
755 })?;
756 let raw: RawDaemonConfig =
757 serde_json::from_str(&json).map_err(|source| DaemonConfigError::InvalidJson {
758 path: path.to_path_buf(),
759 source,
760 })?;
761 if raw.version != SUPPORTED_CONFIG_VERSION {
762 return Err(DaemonConfigError::UnsupportedVersion {
763 path: path.to_path_buf(),
764 version: raw.version,
765 });
766 }
767 raw.log
768 .map(|log| parse_logging_config(log, path, "daemon log"))
769 .transpose()
770}
771
772pub fn ensure_daemon_run_dir_private() -> Result<PathBuf, io::Error> {
798 let path = daemon_run_dir()
799 .map_err(|error| io::Error::new(io::ErrorKind::InvalidInput, error.to_string()))?;
800 ensure_directory_private(&path)?;
801 Ok(path)
802}
803
804#[cfg(unix)]
809fn ensure_directory_private(path: &Path) -> Result<(), io::Error> {
810 use std::os::unix::fs::{DirBuilderExt, PermissionsExt};
811
812 if !path.exists() {
813 fs::DirBuilder::new()
814 .recursive(true)
815 .mode(0o700)
816 .create(path)?;
817 return Ok(());
818 }
819 let mode = fs::metadata(path)?.permissions().mode() & 0o777;
820 if mode & 0o077 != 0 {
821 fs::set_permissions(path, fs::Permissions::from_mode(0o700))?;
822 }
823 Ok(())
824}
825
826#[cfg(windows)]
829fn ensure_directory_private(path: &Path) -> Result<(), io::Error> {
830 subc_os::windows_acl::create_private_dir(path)
831}
832
833#[cfg(not(any(unix, windows)))]
834fn ensure_directory_private(path: &Path) -> Result<(), io::Error> {
835 if !path.exists() {
836 fs::create_dir_all(path)?;
837 }
838 Ok(())
839}
840
841pub fn daemon_run_dir() -> Result<PathBuf, DaemonRunDirError> {
851 daemon_run_dir_from(default_data_home())
852}
853
854fn daemon_run_dir_from(data_home: PathBuf) -> Result<PathBuf, DaemonRunDirError> {
857 if !data_home.is_absolute() {
858 return Err(DaemonRunDirError::RelativeDataHome { data_home });
859 }
860 Ok(data_home.join("cortexkit").join("run"))
861}
862
863#[derive(Debug, Clone, PartialEq, Eq)]
865pub enum DaemonRunDirError {
866 RelativeDataHome { data_home: PathBuf },
869}
870
871impl fmt::Display for DaemonRunDirError {
872 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
873 match self {
874 Self::RelativeDataHome { data_home } => write!(
875 f,
876 "cannot resolve the daemon run directory: the data home `{}` is relative, \
877 so it would land under the current working directory; {}",
878 data_home.display(),
879 DATA_HOME_REMEDY
880 ),
881 }
882 }
883}
884
885impl std::error::Error for DaemonRunDirError {}
886
887#[cfg(windows)]
889const DATA_HOME_REMEDY: &str =
890 "set XDG_DATA_HOME to an absolute path, or set APPDATA, USERPROFILE or HOME";
891#[cfg(not(windows))]
892const DATA_HOME_REMEDY: &str = "set XDG_DATA_HOME to an absolute path, or set HOME";
893
894fn read_config_doc(path: &Path) -> Result<Option<String>, DaemonConfigError> {
895 match fs::read_to_string(path) {
896 Ok(doc) => Ok(Some(doc)),
897 Err(source) if source.kind() == io::ErrorKind::NotFound => Ok(None),
898 Err(source) => Err(DaemonConfigError::Read {
899 path: path.to_path_buf(),
900 source,
901 }),
902 }
903}
904
905fn parse_doc(doc: &str, path: &Path) -> Result<DaemonConfig, DaemonConfigError> {
906 parse_doc_with_activity(doc, path).map(|(config, _)| config)
907}
908
909fn parse_doc_with_activity(
910 doc: &str,
911 path: &Path,
912) -> Result<(DaemonConfig, ActivityConfig), DaemonConfigError> {
913 let json = jsonc_to_json(doc).map_err(|message| DaemonConfigError::InvalidJsonc {
914 path: path.to_path_buf(),
915 message,
916 })?;
917 let raw: RawDaemonConfig =
918 serde_json::from_str(&json).map_err(|source| DaemonConfigError::InvalidJson {
919 path: path.to_path_buf(),
920 source,
921 })?;
922
923 if raw.version != SUPPORTED_CONFIG_VERSION {
924 return Err(DaemonConfigError::UnsupportedVersion {
925 path: path.to_path_buf(),
926 version: raw.version,
927 });
928 }
929
930 let daemon_logging = raw
931 .log
932 .map(|log| parse_logging_config(log, path, "daemon log"))
933 .transpose()?;
934 let default_drain_timeout_ms = raw.drain_timeout_ms;
935 let default_route_bind_relay_timeout_ms = match raw.route_bind_relay_timeout_ms {
941 Some(0) => {
942 return Err(DaemonConfigError::InvalidValue {
943 path: path.to_path_buf(),
944 message: ROUTE_BIND_RELAY_ZERO_MESSAGE.to_string(),
945 });
946 }
947 Some(value) => Some(value),
948 None => None,
949 };
950 let modules = raw
951 .modules
952 .into_iter()
953 .map(|(module_id, module)| {
954 let (program, script) = match (module.program, module.script) {
955 (Some(program), None) => (program, None),
956 (None, Some(script)) if matches!(script.runtime.as_str(), "bun" | "python") => {
957 let runtime = match script.runtime.as_str() {
958 "python" => ScriptRuntime::Python,
959 _ => ScriptRuntime::Bun,
960 };
961 let script_path = crate::supervise::script::resolve_script_path(&script.path)
962 .map_err(|error| DaemonConfigError::InvalidValue { path: path.into(), message: format!("module '{module_id}': {error}") })?;
963 let runner = crate::supervise::script::runner_path(runtime)
964 .map_err(|error| DaemonConfigError::InvalidValue { path: path.into(), message: format!("module '{module_id}': {error}") })?;
965 (runner, Some(ScriptEntry::new(runtime, script_path)))
966 }
967 (None, Some(script)) => return Err(DaemonConfigError::InvalidValue { path: path.into(), message: format!("module '{module_id}' script runtime '{}' is unsupported; expected bun or python", script.runtime.escape_debug()) }),
968 _ => return Err(DaemonConfigError::InvalidValue { path: path.into(), message: format!("module '{module_id}' must name exactly one of program or script") }),
969 };
970 if script.is_some() {
971 if let Some(key) = module.env.keys().find(|key| crate::supervise::script::forbidden_env(key)) {
972 return Err(DaemonConfigError::InvalidValue { path: path.into(), message: format!("module '{module_id}' script env '{key}' is refused: runtime options can execute code before script verification") });
973 }
974 }
975 let protocol = parse_module_protocol(module.protocol.as_deref(), path, &module_id)?;
976 let health = module
977 .health
978 .map(|health| parse_health_config(health, path, &module_id, protocol))
979 .transpose()?
980 .unwrap_or_default();
981 if let Err(reason) = crate::registry::module_id_path_hazard(&module_id) {
982 return Err(DaemonConfigError::InvalidValue {
983 path: path.to_path_buf(),
984 message: format!(
985 "module id '{}' is not usable as a path component ({reason}): \
986 the daemon derives each module's store path from its id",
987 module_id.escape_debug()
988 ),
989 });
990 }
991 let per_module_route_bind_relay_timeout_ms = match module.route_bind_relay_timeout_ms {
996 Some(0) => {
997 return Err(DaemonConfigError::InvalidValue {
998 path: path.to_path_buf(),
999 message: format!(
1000 "module '{module_id}' {ROUTE_BIND_RELAY_ZERO_MESSAGE}",
1001 module_id = module_id.escape_debug()
1002 ),
1003 });
1004 }
1005 Some(value) => Some(value),
1006 None => default_route_bind_relay_timeout_ms,
1007 };
1008 if module.ignored.contains_key("launch_nonce_env") {
1013 tracing::warn!(
1014 module_id = %module_id.escape_debug(),
1015 "launch_nonce_env is deprecated and ignored; nonce delivery is determined by the platform"
1016 );
1017 }
1018 let overlap = parse_module_overlap(module.overlap.as_deref(), path, &module_id)?;
1019 if module.carry_containment && overlap == ModuleOverlap::Safe {
1020 return Err(DaemonConfigError::InvalidValue {
1021 path: path.to_path_buf(),
1022 message: format!(
1023 "module '{}' sets carry_containment: true with overlap: \"safe\"; carried containment does not support overlapping instances",
1024 module_id.escape_debug()
1025 ),
1026 });
1027 }
1028 if module.env.contains_key(SUBC_SPAWN_ROLE_ENV) {
1032 return Err(DaemonConfigError::InvalidValue {
1033 path: path.to_path_buf(),
1034 message: format!(
1035 "module '{module_id}' sets {SUBC_SPAWN_ROLE_ENV} in env; that variable is set by the supervisor on a swap candidate only and cannot be configured",
1036 module_id = module_id.escape_debug()
1037 ),
1038 });
1039 }
1040 if protocol == ModuleProtocol::None && module.reserved {
1047 return Err(DaemonConfigError::InvalidValue {
1048 path: path.to_path_buf(),
1049 message: format!(
1050 "module '{module_id}' sets reserved: true with protocol: \"none\"; \
1051 reserved is enforced on the module's HELLO and a protocol: \"none\" \
1052 module never registers, so the reservation could never be checked",
1053 module_id = module_id.escape_debug()
1054 ),
1055 });
1056 }
1057 let restart = parse_restart_config(module.restart, path, &module_id)?;
1058 let register_timeout_s = module
1059 .register_timeout_s
1060 .unwrap_or(crate::supervise::DEFAULT_REGISTER_TIMEOUT.as_secs());
1061 if !(10..=3600).contains(®ister_timeout_s) {
1062 return Err(DaemonConfigError::InvalidValue {
1063 path: path.to_path_buf(),
1064 message: format!(
1065 "module '{module_id}' register_timeout_s must be an integer from 10 to 3600"
1066 ),
1067 });
1068 }
1069 let log = module
1070 .log
1071 .map(|log| parse_logging_config(log, path, &format!("module '{module_id}' log")))
1072 .transpose()?
1073 .or_else(|| daemon_logging.clone());
1074 Ok(ConfiguredModule { module_id,
1075 program,
1076 script,
1077 args: module.args,
1078 env: module.env.into_iter().collect(),
1079 log,
1080 enabled: module.enabled,
1081 registration_channel: module.registration_channel,
1082 reserved: module.reserved,
1083 reserved_prefixes: module.reserved_prefixes,
1084 protocol,
1085 overlap,
1086 carry_containment: module.carry_containment,
1087 health,
1088 drain_timeout_ms: module.drain_timeout_ms.or(default_drain_timeout_ms),
1091 register_timeout: Duration::from_secs(register_timeout_s),
1092 route_bind_relay_timeout_ms: per_module_route_bind_relay_timeout_ms,
1097 restart, })
1098 })
1099 .collect::<Result<Vec<_>, DaemonConfigError>>()?;
1100
1101 validate_reserved_prefixes(&modules, path)?;
1102 validate_reserved_capabilities(&raw.reserved_capabilities, path)?;
1103 validate_admission_facts_config(
1104 &modules,
1105 raw.admission_facts_carrier_module_id.as_deref(),
1106 raw.admission_facts_targets.as_deref(),
1107 path,
1108 )?;
1109 let scope_authority_owners = raw
1110 .scope_authority_owners
1111 .unwrap_or_else(default_scope_authority_owners);
1112 subc_protocol::manifest::validate_module_id(&raw.federated_scope_owner).map_err(|error| {
1113 DaemonConfigError::InvalidValue {
1114 path: path.to_path_buf(),
1115 message: format!("federated_scope_owner: {error}"),
1116 }
1117 })?;
1118 if scope_authority_owners.iter().any(|owner| owner.is_empty()) {
1119 return Err(DaemonConfigError::InvalidValue {
1120 path: path.to_path_buf(),
1121 message: "scope_authority_owners must not contain empty module ids".to_string(),
1122 });
1123 }
1124
1125 let storage = raw
1126 .storage
1127 .map(|s| match s {
1128 RawStorageConfig::Sqlite { data_home } => {
1129 let data_home = data_home.unwrap_or_else(default_data_home);
1130 if !data_home.is_absolute() {
1139 return Err(DaemonConfigError::InvalidValue {
1140 path: path.to_path_buf(),
1141 message: format!(
1142 "storage data home resolved to the relative path {} \
1143 (no absolute XDG_DATA_HOME, APPDATA, USERPROFILE, or HOME \
1144 in the daemon's environment); refusing to serve a \
1145 cwd-relative storage descriptor to modules. Set \
1146 XDG_DATA_HOME or HOME to an absolute path, or set \
1147 storage.data_home in this file.",
1148 data_home.display()
1149 ),
1150 });
1151 }
1152 Ok(StorageConfig::Sqlite { data_home })
1153 }
1154 })
1155 .transpose()?;
1156
1157 if raw.activity.max_age_days == 0 || raw.activity.max_total_mb == 0 {
1158 return Err(DaemonConfigError::InvalidValue {
1159 path: path.to_path_buf(),
1160 message: "activity.max_age_days and activity.max_total_mb must be positive".into(),
1161 });
1162 }
1163 Ok((
1164 DaemonConfig {
1165 path: path.to_path_buf(),
1166 port: raw.port,
1167 privileged_operator_prompt: raw.privileged_operator_prompt,
1168 drain_timeout_ms: default_drain_timeout_ms,
1169 route_bind_relay_timeout_ms: default_route_bind_relay_timeout_ms,
1170 modules,
1171 storage,
1172 admission_facts_carrier_module_id: raw.admission_facts_carrier_module_id,
1173 admission_facts_targets: raw.admission_facts_targets,
1174 scope_authority_owners,
1175 federated_scope_owner: raw.federated_scope_owner,
1176 reserved_capabilities: raw.reserved_capabilities,
1177 },
1178 raw.activity,
1179 ))
1180}
1181
1182fn parse_logging_config(
1183 raw: RawLoggingConfig,
1184 path: &Path,
1185 owner: &str,
1186) -> Result<LoggingConfig, DaemonConfigError> {
1187 fn valid_level(level: &str) -> bool {
1188 matches!(level, "off" | "error" | "warn" | "info" | "debug" | "trace")
1189 }
1190
1191 let level = raw.level.unwrap_or_else(|| "info".to_string());
1192 if !valid_level(&level) {
1193 return Err(DaemonConfigError::InvalidValue {
1194 path: path.to_path_buf(),
1195 message: format!(
1196 "{owner}.level must be one of off, error, warn, info, debug, trace; got {level:?}"
1197 ),
1198 });
1199 }
1200 for (tag, tag_level) in &raw.tags {
1201 let well_formed = !tag.is_empty()
1206 && tag.split('.').all(|segment| {
1207 let mut chars = segment.chars();
1208 matches!(chars.next(), Some('a'..='z'))
1209 && chars.all(|c| matches!(c, 'a'..='z' | '0'..='9' | '-'))
1210 });
1211 if !well_formed {
1212 return Err(DaemonConfigError::InvalidValue {
1213 path: path.to_path_buf(),
1214 message: format!(
1215 "{owner}.tags key {tag:?} is not a logger name (dotted segments of [a-z][a-z0-9-]*)"
1216 ),
1217 });
1218 }
1219 if !valid_level(tag_level) {
1220 return Err(DaemonConfigError::InvalidValue {
1221 path: path.to_path_buf(),
1222 message: format!(
1223 "{owner}.tags.{tag} must be one of off, error, warn, info, debug, trace; got {tag_level:?}"
1224 ),
1225 });
1226 }
1227 }
1228
1229 let defaults = Retention::default();
1230 let retention = Retention {
1231 max_file_mb: raw.max_file_mb.unwrap_or(defaults.max_file_mb),
1232 keep: raw.keep.unwrap_or(defaults.keep),
1233 max_age_days: raw.max_age_days.unwrap_or(defaults.max_age_days),
1234 };
1235 if retention.max_file_mb == 0 {
1236 return Err(DaemonConfigError::InvalidValue {
1237 path: path.to_path_buf(),
1238 message: format!("{owner}.max_file_mb must be greater than 0"),
1239 });
1240 }
1241
1242 let alarm_segment_mb = raw
1243 .alarm_segment_mb
1244 .unwrap_or(cortexkit_log::SegmentRetention::default().alarm_segment_mb);
1245 if alarm_segment_mb == 0 {
1246 return Err(DaemonConfigError::InvalidValue {
1247 path: path.to_path_buf(),
1248 message: format!("{owner}.alarm_segment_mb must be greater than 0"),
1249 });
1250 }
1251
1252 Ok(LoggingConfig {
1253 level,
1254 tags: raw.tags,
1255 retention,
1256 alarm_segment_mb,
1257 })
1258}
1259
1260fn parse_module_protocol(
1269 raw: Option<&str>,
1270 path: &Path,
1271 module_id: &str,
1272) -> Result<ModuleProtocol, DaemonConfigError> {
1273 match raw {
1274 None | Some("subc") => Ok(ModuleProtocol::Subc),
1275 Some("none") => Ok(ModuleProtocol::None),
1276 Some(other) => Err(DaemonConfigError::InvalidValue {
1280 path: path.to_path_buf(),
1281 message: format!(
1282 "module '{module_id}' declares protocol {other:?}; supported values are \
1283 \"subc\" (the default when the key is absent) and \"none\"",
1284 module_id = module_id.escape_debug(),
1285 ),
1286 }),
1287 }
1288}
1289
1290fn parse_module_overlap(
1294 raw: Option<&str>,
1295 path: &Path,
1296 module_id: &str,
1297) -> Result<ModuleOverlap, DaemonConfigError> {
1298 match raw {
1299 None | Some("exclusive") => Ok(ModuleOverlap::Exclusive),
1300 Some("safe") => Ok(ModuleOverlap::Safe),
1301 Some(other) => Err(DaemonConfigError::InvalidValue {
1302 path: path.to_path_buf(),
1303 message: format!(
1304 "module '{module_id}' declares overlap {other:?}; supported values are \
1305 \"exclusive\" (the default when the key is absent) and \"safe\"",
1306 module_id = module_id.escape_debug(),
1307 ),
1308 }),
1309 }
1310}
1311
1312fn validate_reserved_capabilities(
1313 bindings: &BTreeMap<String, String>,
1314 path: &Path,
1315) -> Result<(), DaemonConfigError> {
1316 for (capability, module_id) in bindings {
1317 if !is_valid_capability_identifier(capability) {
1318 return Err(DaemonConfigError::InvalidValue {
1319 path: path.to_path_buf(),
1320 message: format!(
1321 "reserved_capabilities key {:?} is not a valid capability identifier",
1322 capability
1323 ),
1324 });
1325 }
1326 if module_id.trim().is_empty() {
1327 return Err(DaemonConfigError::InvalidValue {
1328 path: path.to_path_buf(),
1329 message: format!(
1330 "reserved_capabilities binding for {:?} has an empty module id",
1331 capability
1332 ),
1333 });
1334 }
1335 if let Err(reason) = crate::registry::module_id_path_hazard(module_id) {
1336 return Err(DaemonConfigError::InvalidValue {
1337 path: path.to_path_buf(),
1338 message: format!(
1339 "reserved_capabilities binding for {:?} has an unusable module id {:?}: {reason}",
1340 capability, module_id
1341 ),
1342 });
1343 }
1344 }
1345 Ok(())
1346}
1347
1348fn validate_admission_facts_config(
1349 modules: &[ConfiguredModule],
1350 carrier_module_id: Option<&str>,
1351 targets: Option<&[String]>,
1352 path: &Path,
1353) -> Result<(), DaemonConfigError> {
1354 let Some(carrier_module_id) = carrier_module_id else {
1355 return Ok(());
1356 };
1357
1358 let Some(carrier) = modules
1359 .iter()
1360 .find(|module| module.module_id == carrier_module_id)
1361 else {
1362 return Err(DaemonConfigError::InvalidValue {
1363 path: path.to_path_buf(),
1364 message: format!(
1365 "admission_facts_carrier_module_id '{carrier_module_id}' must name a configured module"
1366 ),
1367 });
1368 };
1369 if !carrier.enabled || !carrier.reserved {
1370 return Err(DaemonConfigError::InvalidValue {
1371 path: path.to_path_buf(),
1372 message: format!(
1373 "admission_facts_carrier_module_id '{carrier_module_id}' must name an enabled reserved module"
1374 ),
1375 });
1376 }
1377
1378 let Some(targets) = targets else {
1379 return Err(DaemonConfigError::InvalidValue {
1380 path: path.to_path_buf(),
1381 message: "admission_facts_targets must be present when an admission facts carrier is configured".to_string(),
1382 });
1383 };
1384 if targets.is_empty() || targets.iter().any(String::is_empty) {
1385 return Err(DaemonConfigError::InvalidValue {
1386 path: path.to_path_buf(),
1387 message:
1388 "admission_facts_targets must be non-empty and must not contain empty module ids"
1389 .to_string(),
1390 });
1391 }
1392
1393 Ok(())
1394}
1395
1396fn default_enabled() -> bool {
1397 true
1398}
1399
1400fn validate_reserved_prefixes(
1401 modules: &[ConfiguredModule],
1402 path: &Path,
1403) -> Result<(), DaemonConfigError> {
1404 for module in modules {
1405 if module.reserved_prefixes.is_empty() {
1406 continue;
1407 }
1408 if !module.reserved {
1409 return Err(DaemonConfigError::InvalidValue {
1410 path: path.to_path_buf(),
1411 message: format!(
1412 "module '{}' reserved_prefixes require reserved=true so the owner is spawn-nonce protected",
1413 module.module_id
1414 ),
1415 });
1416 }
1417 for prefix in &module.reserved_prefixes {
1418 if !prefix.ends_with(':') {
1419 return Err(DaemonConfigError::InvalidValue {
1420 path: path.to_path_buf(),
1421 message: format!(
1422 "module '{}' reserved prefix '{}' must end with ':'",
1423 module.module_id, prefix
1424 ),
1425 });
1426 }
1427 }
1428 }
1429
1430 for module in modules {
1431 for prefix in &module.reserved_prefixes {
1432 if let Some(colliding) = modules
1433 .iter()
1434 .find(|candidate| candidate.module_id.starts_with(prefix))
1435 {
1436 return Err(DaemonConfigError::InvalidValue {
1437 path: path.to_path_buf(),
1438 message: format!(
1439 "reserved prefix '{}' owned by '{}' collides with configured module id '{}'",
1440 prefix, module.module_id, colliding.module_id
1441 ),
1442 });
1443 }
1444 }
1445 }
1446
1447 for (left_index, left) in modules.iter().enumerate() {
1448 for right in modules.iter().skip(left_index + 1) {
1449 if left.module_id == right.module_id {
1450 continue;
1451 }
1452 for left_prefix in &left.reserved_prefixes {
1453 for right_prefix in &right.reserved_prefixes {
1454 if left_prefix.starts_with(right_prefix)
1455 || right_prefix.starts_with(left_prefix)
1456 {
1457 return Err(DaemonConfigError::InvalidValue {
1458 path: path.to_path_buf(),
1459 message: format!(
1460 "reserved prefixes '{}' owned by '{}' and '{}' owned by '{}' overlap",
1461 left_prefix, left.module_id, right_prefix, right.module_id
1462 ),
1463 });
1464 }
1465 }
1466 }
1467 }
1468 }
1469
1470 Ok(())
1471}
1472
1473fn parse_health_config(
1474 raw: RawHealthConfig,
1475 path: &Path,
1476 module_id: &str,
1477 protocol: ModuleProtocol,
1478) -> Result<HealthConfig, DaemonConfigError> {
1479 if let Some(url) = raw.http.as_deref() {
1480 let reason = if protocol != ModuleProtocol::None {
1481 Some("is valid only for protocol: \"none\" modules".to_string())
1482 } else {
1483 crate::supervise::parse_http_probe_url(url).err()
1484 };
1485 if let Some(reason) = reason {
1486 return Err(DaemonConfigError::InvalidValue {
1487 path: path.to_path_buf(),
1488 message: format!("module '{module_id}' health.http {reason}"),
1489 });
1490 }
1491 }
1492 let defaults = HealthConfig::default();
1493 let cadence = positive_millis(
1494 raw.cadence_ms,
1495 defaults.cadence,
1496 path,
1497 module_id,
1498 "cadence_ms",
1499 )?;
1500 let deadline = positive_millis(
1501 raw.deadline_ms,
1502 defaults.deadline,
1503 path,
1504 module_id,
1505 "deadline_ms",
1506 )?;
1507 let failure_threshold = match raw.failure_threshold {
1508 Some(0) => {
1509 return Err(DaemonConfigError::InvalidValue {
1510 path: path.to_path_buf(),
1511 message: format!("module '{module_id}' health.failure_threshold must be positive"),
1512 })
1513 }
1514 Some(value) => value,
1515 None => defaults.failure_threshold,
1516 };
1517
1518 Ok(HealthConfig {
1519 http: raw.http,
1520 cadence,
1521 deadline,
1522 failure_threshold,
1523 on_degraded: match raw.on_degraded {
1524 Some(RawHealthAction::Restart) => {
1525 return Err(DaemonConfigError::InvalidValue {
1526 path: path.to_path_buf(),
1527 message: format!(
1528 "module '{module_id}' health.on_degraded may not be 'restart': a degraded module is slow-but-moving, so restarting it converts transient load into an outage. Use 'report' or 'alert' (Health-Path v2: only total wreckage or reported-unresponsiveness restarts)."
1529 ),
1530 });
1531 }
1532 Some(action) => health_action(action),
1533 None => defaults.on_degraded,
1534 },
1535 on_failing: raw
1536 .on_failing
1537 .map(health_action)
1538 .unwrap_or(defaults.on_failing),
1539 critical: raw.critical,
1540 })
1541}
1542
1543fn parse_restart_config(
1550 raw: Option<RawRestartConfig>,
1551 path: &Path,
1552 module_id: &str,
1553) -> Result<RestartPolicy, DaemonConfigError> {
1554 let defaults = RestartPolicy::default();
1555 let Some(raw) = raw else {
1556 return Ok(defaults);
1557 };
1558
1559 let window = match raw.window_secs {
1560 Some(0) => {
1561 return Err(DaemonConfigError::InvalidValue {
1562 path: path.to_path_buf(),
1563 message: format!(
1564 "module '{module_id}' {RESTART_WINDOW_ZERO_MESSAGE}",
1565 module_id = module_id.escape_debug()
1566 ),
1567 });
1568 }
1569 Some(secs) => Duration::from_secs(secs),
1570 None => defaults.window,
1571 };
1572 let backoff = raw
1573 .backoff_ms
1574 .map(Duration::from_millis)
1575 .unwrap_or(defaults.backoff);
1576 let max_backoff = raw
1577 .max_backoff_ms
1578 .map(Duration::from_millis)
1579 .unwrap_or(defaults.max_backoff);
1580 if max_backoff < backoff {
1581 return Err(DaemonConfigError::InvalidValue {
1582 path: path.to_path_buf(),
1583 message: format!(
1584 "module '{}' restart.max_backoff_ms must be greater than or equal to restart.backoff_ms (max_backoff_ms={max_backoff:?}, backoff_ms={backoff:?})",
1585 module_id.escape_debug()
1586 ),
1587 });
1588 }
1589
1590 Ok(RestartPolicy {
1591 max_restarts: raw.max_restarts.unwrap_or(defaults.max_restarts),
1594 backoff,
1595 max_backoff,
1596 window,
1597 })
1598}
1599
1600fn positive_millis(
1601 value: Option<u64>,
1602 default: std::time::Duration,
1603 path: &Path,
1604 module_id: &str,
1605 field: &str,
1606) -> Result<std::time::Duration, DaemonConfigError> {
1607 match value {
1608 Some(0) => Err(DaemonConfigError::InvalidValue {
1609 path: path.to_path_buf(),
1610 message: format!("module '{module_id}' health.{field} must be positive"),
1611 }),
1612 Some(value) => Ok(std::time::Duration::from_millis(value)),
1613 None => Ok(default),
1614 }
1615}
1616
1617fn health_action(action: RawHealthAction) -> HealthAction {
1618 match action {
1619 RawHealthAction::Report => HealthAction::Report,
1620 RawHealthAction::Restart => HealthAction::Restart,
1621 RawHealthAction::Alert => HealthAction::Alert,
1622 }
1623}
1624
1625pub(crate) fn default_data_home() -> PathBuf {
1628 if let Some(data_home) = non_empty_os_var("XDG_DATA_HOME") {
1629 return PathBuf::from(data_home);
1630 }
1631
1632 #[cfg(windows)]
1633 {
1634 if let Some(app_data) = non_empty_os_var("APPDATA") {
1635 return PathBuf::from(app_data);
1636 }
1637 if let Some(user_profile) = non_empty_os_var("USERPROFILE") {
1638 return PathBuf::from(user_profile).join("AppData").join("Roaming");
1639 }
1640 }
1641
1642 if let Some(home) = non_empty_os_var("HOME") {
1643 return PathBuf::from(home).join(".local").join("share");
1644 }
1645
1646 PathBuf::from(".local").join("share")
1647}
1648
1649fn non_empty_os_var(key: &str) -> Option<OsString> {
1650 let value = env::var_os(key)?;
1651 if value.is_empty() {
1652 None
1653 } else {
1654 Some(value)
1655 }
1656}
1657
1658impl fmt::Display for DaemonConfigError {
1659 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1660 match self {
1661 Self::Read { path, source } => {
1662 write!(f, "failed to read daemon config {}: {source}", path.display())
1663 }
1664 Self::InvalidJsonc { path, message } => {
1665 write!(f, "invalid JSONC in daemon config {}: {message}", path.display())
1666 }
1667 Self::InvalidJson { path, source } => {
1668 write!(f, "invalid daemon config {}: {source}", path.display())
1669 }
1670 Self::UnsupportedVersion { path, version } => write!(
1671 f,
1672 "invalid daemon config {}: version {version} is unsupported (expected {SUPPORTED_CONFIG_VERSION})",
1673 path.display()
1674 ),
1675 Self::InvalidValue { path, message } => {
1676 write!(f, "invalid daemon config {}: {message}", path.display())
1677 }
1678 }
1679 }
1680}
1681
1682impl Error for DaemonConfigError {
1683 fn source(&self) -> Option<&(dyn Error + 'static)> {
1684 match self {
1685 Self::Read { source, .. } => Some(source),
1686 Self::InvalidJson { source, .. } => Some(source),
1687 Self::InvalidJsonc { .. }
1688 | Self::UnsupportedVersion { .. }
1689 | Self::InvalidValue { .. } => None,
1690 }
1691 }
1692}
1693
1694#[cfg(all(test, windows))]
1695mod windows_run_dir_privacy_tests {
1696 use super::ensure_directory_private;
1697 use cortexkit_test_support::ScratchDir;
1698 use subc_os::windows_acl::test_support::{
1699 assert_dacl_owner_only, assert_owner_only, grant_everyone,
1700 };
1701
1702 #[test]
1703 fn windows_run_dir_has_exact_protected_dacl_at_creation() {
1704 let root = ScratchDir::new("windows-run-dir-create");
1705 grant_everyone(root.path());
1706 let path = root.join("run");
1707 ensure_directory_private(&path).unwrap();
1708 assert_owner_only(&path, true, true);
1709 }
1710
1711 #[test]
1712 fn windows_run_dir_narrows_existing_inherited_descendants() {
1713 let root = ScratchDir::new("windows-run-dir-existing");
1714 grant_everyone(root.path());
1715 let path = root.join("run");
1716 std::fs::create_dir(&path).unwrap();
1717 let child = path.join("old.log");
1718 std::fs::write(&child, b"old log").unwrap();
1719 ensure_directory_private(&path).unwrap();
1720 assert_dacl_owner_only(&path, true, true);
1723 assert_dacl_owner_only(&child, false, false);
1724 }
1725}
1726
1727#[cfg(all(test, unix))]
1728mod run_dir_privacy_tests {
1729 use cortexkit_test_support::ScratchDir;
1730 use std::fs;
1731 use std::os::unix::fs::PermissionsExt;
1732
1733 #[test]
1739 fn run_dir_is_created_private_and_an_inherited_wide_one_is_tightened() {
1740 let temp = ScratchDir::new("subc-run-dir-privacy");
1741 let created = temp.path().join("cortexkit").join("run");
1742 super::ensure_directory_private(&created).expect("create run dir");
1743 let mode = fs::metadata(&created)
1744 .expect("stat created")
1745 .permissions()
1746 .mode()
1747 & 0o777;
1748 assert_eq!(
1749 mode, 0o700,
1750 "observable a run directory this code creates must be 0700, got {mode:o}"
1751 );
1752
1753 fs::set_permissions(&created, fs::Permissions::from_mode(0o755)).expect("widen");
1755 let widened = fs::metadata(&created)
1756 .expect("stat widened")
1757 .permissions()
1758 .mode()
1759 & 0o777;
1760 assert_eq!(
1761 widened, 0o755,
1762 "observable the fixture must actually be wide before the tighten"
1763 );
1764
1765 super::ensure_directory_private(&created).expect("tighten run dir");
1766 let mode = fs::metadata(&created)
1767 .expect("stat tightened")
1768 .permissions()
1769 .mode()
1770 & 0o777;
1771 assert_eq!(
1772 mode, 0o700,
1773 "observable an inherited group- or world-readable run directory must be tightened to 0700, got {mode:o}"
1774 );
1775 }
1776}
1777
1778#[cfg(test)]
1779mod tests {
1780 use super::*;
1781
1782 static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
1791
1792 fn abs(posix: &str) -> PathBuf {
1797 if cfg!(windows) {
1798 PathBuf::from(format!("C:{}", posix.replace('/', "\\")))
1799 } else {
1800 PathBuf::from(posix)
1801 }
1802 }
1803
1804 #[test]
1805 fn default_data_home_matches_golden_fixture() {
1806 let _g = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
1807 let doc: serde_json::Value =
1808 serde_json::from_str(include_str!("../tests/golden/data_home_resolution.json"))
1809 .expect("golden parses");
1810 let vars = ["XDG_DATA_HOME", "APPDATA", "USERPROFILE", "HOME"];
1811 let saved: Vec<(&str, Option<std::ffi::OsString>)> =
1812 vars.iter().map(|v| (*v, env::var_os(v))).collect();
1813 let platform_matches =
1814 |p: &str| p == "any" || p == if cfg!(windows) { "windows" } else { "unix" };
1815
1816 let mut ran = 0usize;
1817 for case in doc["cases"].as_array().expect("cases array") {
1818 let name = case["name"].as_str().expect("name");
1819 if !platform_matches(case["platform"].as_str().expect("platform")) {
1820 continue;
1821 }
1822 for v in vars {
1823 env::remove_var(v);
1824 }
1825 for (k, v) in case["env"].as_object().expect("env map") {
1826 env::set_var(k, v.as_str().expect("env value"));
1827 }
1828 let got = default_data_home();
1829 assert_eq!(
1830 got.to_string_lossy(),
1831 case["expect"].as_str().expect("expect"),
1832 "golden case '{name}' diverged"
1833 );
1834 ran += 1;
1835 }
1836 assert!(
1838 ran >= 6,
1839 "only {ran} golden cases ran; fixture or filter broken"
1840 );
1841
1842 for (k, v) in saved {
1843 match v {
1844 Some(val) => env::set_var(k, val),
1845 None => env::remove_var(k),
1846 }
1847 }
1848 }
1849
1850 #[test]
1855 fn daemon_run_dir_refuses_a_relative_data_home_and_names_the_variables() {
1856 for data_home in [PathBuf::from(".local/share"), PathBuf::from("relative-xdg")] {
1857 let error = daemon_run_dir_from(data_home.clone())
1858 .expect_err("a relative data home must be refused");
1859 assert_eq!(
1860 error,
1861 DaemonRunDirError::RelativeDataHome {
1862 data_home: data_home.clone()
1863 }
1864 );
1865 let message = error.to_string();
1866 assert!(
1867 message.contains("XDG_DATA_HOME") && message.contains("HOME"),
1868 "the refusal must name the variables to set: {message}"
1869 );
1870 }
1871 }
1872
1873 #[test]
1874 fn daemon_run_dir_under_an_absolute_data_home_is_cortexkit_run() {
1875 let data_home = env::temp_dir().join("subc-run-dir-probe").join("data");
1876 assert!(data_home.is_absolute());
1877 assert_eq!(
1878 daemon_run_dir_from(data_home.clone()),
1879 Ok(data_home.join("cortexkit").join("run"))
1880 );
1881 }
1882
1883 #[test]
1889 fn default_config_home_matches_golden_fixture() {
1890 let _g = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
1891 let doc: serde_json::Value =
1892 serde_json::from_str(include_str!("../tests/golden/config_home_resolution.json"))
1893 .expect("golden parses");
1894 let vars = ["XDG_CONFIG_HOME", "APPDATA", "USERPROFILE", "HOME"];
1895 let saved: Vec<(&str, Option<std::ffi::OsString>)> =
1896 vars.iter().map(|v| (*v, env::var_os(v))).collect();
1897 let platform_matches =
1898 |p: &str| p == "any" || p == if cfg!(windows) { "windows" } else { "unix" };
1899
1900 let mut ran = 0usize;
1901 for case in doc["cases"].as_array().expect("cases array") {
1902 let name = case["name"].as_str().expect("name");
1903 if !platform_matches(case["platform"].as_str().expect("platform")) {
1904 continue;
1905 }
1906 for v in vars {
1907 env::remove_var(v);
1908 }
1909 for (k, v) in case["env"].as_object().expect("env map") {
1910 env::set_var(k, v.as_str().expect("env value"));
1911 }
1912 let got = default_config_home();
1913 assert_eq!(
1914 got.to_string_lossy(),
1915 case["expect"].as_str().expect("expect"),
1916 "golden case '{name}' diverged"
1917 );
1918 ran += 1;
1919 }
1920 assert!(
1921 ran >= 6,
1922 "only {ran} golden cases ran; fixture or filter broken"
1923 );
1924
1925 for (k, v) in saved {
1926 match v {
1927 Some(val) => env::set_var(k, val),
1928 None => env::remove_var(k),
1929 }
1930 }
1931 }
1932
1933 #[test]
1940 fn relative_storage_data_home_is_refused_at_parse() {
1941 let _g = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
1942 let path = Path::new("/golden/subc.jsonc");
1943
1944 let doc =
1946 r#"{ "version": 1, "storage": { "backend": "sqlite", "data_home": "relative/home" } }"#;
1947 let err = parse_doc(doc, path).expect_err("relative data_home must refuse");
1948 assert!(
1949 matches!(&err, DaemonConfigError::InvalidValue { message, .. }
1950 if message.contains("relative path relative/home")),
1951 "wrong refusal: {err:?}"
1952 );
1953
1954 let vars = ["XDG_DATA_HOME", "APPDATA", "USERPROFILE", "HOME"];
1956 let saved: Vec<(&str, Option<std::ffi::OsString>)> =
1957 vars.iter().map(|v| (*v, env::var_os(v))).collect();
1958 for v in vars {
1959 env::remove_var(v);
1960 }
1961 let doc = r#"{ "version": 1, "storage": { "backend": "sqlite" } }"#;
1962 let err = parse_doc(doc, path).expect_err("no home in env must refuse");
1963 assert!(
1964 matches!(&err, DaemonConfigError::InvalidValue { message, .. }
1965 if message.contains("no absolute XDG_DATA_HOME")),
1966 "wrong refusal: {err:?}"
1967 );
1968
1969 let want = abs("/abs/home");
1973 let doc = format!(
1974 r#"{{ "version": 1, "storage": {{ "backend": "sqlite", "data_home": {} }} }}"#,
1975 serde_json::to_string(&want).expect("json path")
1976 );
1977 let cfg = parse_doc(&doc, path).expect("absolute data_home parses");
1978 assert!(matches!(
1979 cfg.storage,
1980 Some(StorageConfig::Sqlite { ref data_home }) if *data_home == want
1981 ));
1982
1983 for (k, v) in saved {
1984 match v {
1985 Some(val) => env::set_var(k, val),
1986 None => env::remove_var(k),
1987 }
1988 }
1989 }
1990
1991 #[test]
1992 fn restart_required_sections_are_the_rescan_cannot_apply_set() {
1993 assert_eq!(
1994 RestartRequiredSection::ALL.map(RestartRequiredSection::label),
1995 [
1996 "port",
1997 "storage",
1998 "admission_facts_carrier_module_id",
1999 "admission_facts_targets",
2000 "scope_authority_owners",
2001 "federated_scope_owner",
2002 "privileged_operator_prompt",
2003 ]
2004 );
2005 }
2006
2007 #[test]
2008 fn privileged_operator_prompt_defaults_to_log_and_accepts_both_modes() {
2009 let path = Path::new("/tmp/subc.jsonc");
2010 let config = parse_doc(r#"{"version":1}"#, path).unwrap();
2011 assert_eq!(
2012 config.privileged_operator_prompt,
2013 PrivilegedOperatorPrompt::Log
2014 );
2015 for (value, expected) in [
2016 ("log", PrivilegedOperatorPrompt::Log),
2017 ("enforce", PrivilegedOperatorPrompt::Enforce),
2018 ] {
2019 let config = parse_doc(
2020 &format!(r#"{{"version":1,"privileged_operator_prompt":"{value}"}}"#),
2021 path,
2022 )
2023 .unwrap();
2024 assert_eq!(config.privileged_operator_prompt, expected);
2025 }
2026 }
2027
2028 #[test]
2029 fn privileged_operator_prompt_refuses_unknown_values_and_wrong_types() {
2030 let path = Path::new("/tmp/subc.jsonc");
2031 for value in [r#""unknown""#, r#""Enforce""#, "null", "true", "1", "{}"] {
2032 let error = parse_doc(
2033 &format!(r#"{{"version":1,"privileged_operator_prompt":{value}}}"#),
2034 path,
2035 )
2036 .unwrap_err();
2037 assert!(matches!(error, DaemonConfigError::InvalidJson { .. }));
2038 }
2039 }
2040
2041 #[test]
2042 fn scope_authority_owners_defaults_to_the_session_runtime() {
2043 let config = parse_doc(r#"{ "version": 1 }"#, Path::new("/tmp/subc.jsonc")).unwrap();
2044 assert_eq!(
2045 config.scope_authority_owners,
2046 vec!["prefrontal-core", "prefrontal"]
2047 );
2048 }
2049
2050 #[test]
2051 fn federated_scope_owner_defaults_and_is_validated_and_restart_required() {
2052 let config = parse_doc(r#"{ "version": 1 }"#, Path::new("/fixture/subc.jsonc")).unwrap();
2053 assert_eq!(config.federated_scope_owner, "callosum");
2054 assert!(!config
2055 .scope_authority_owners
2056 .contains(&config.federated_scope_owner));
2057 let configured = parse_doc(
2058 r#"{ "version": 1, "federated_scope_owner": "peer-carrier" }"#,
2059 Path::new("/fixture/subc.jsonc"),
2060 )
2061 .unwrap();
2062 assert_eq!(configured.federated_scope_owner, "peer-carrier");
2063 assert!(RestartRequiredSection::ALL.contains(&RestartRequiredSection::FederatedScopeOwner));
2064 for invalid in ["", "..", "a/b", "a\\b"] {
2065 let body = serde_json::json!({"version": 1, "federated_scope_owner": invalid});
2066 assert!(
2067 parse_doc(&body.to_string(), Path::new("/fixture/subc.jsonc"))
2068 .unwrap_err()
2069 .to_string()
2070 .contains("federated_scope_owner")
2071 );
2072 }
2073 }
2074
2075 #[test]
2076 fn scope_authority_owners_is_read_when_set_and_refuses_an_empty_id() {
2077 let config = parse_doc(
2078 r#"{ "version": 1, "scope_authority_owners": ["a", "b"] }"#,
2079 Path::new("/tmp/subc.jsonc"),
2080 )
2081 .unwrap();
2082 assert_eq!(config.scope_authority_owners, vec!["a", "b"]);
2083 let config = parse_doc(
2086 r#"{ "version": 1, "scope_authority_owners": [] }"#,
2087 Path::new("/tmp/subc.jsonc"),
2088 )
2089 .unwrap();
2090 assert!(config.scope_authority_owners.is_empty());
2091 let error = parse_doc(
2092 r#"{ "version": 1, "scope_authority_owners": [""] }"#,
2093 Path::new("/tmp/subc.jsonc"),
2094 )
2095 .expect_err("an empty module id is refused");
2096 assert!(
2097 error.to_string().contains("scope_authority_owners"),
2098 "{error}"
2099 );
2100 }
2101
2102 #[test]
2103 fn no_storage_section_yields_none() {
2104 let config = parse_doc(
2105 r#"{ "version": 1, "modules": {} }"#,
2106 Path::new("/tmp/subc.jsonc"),
2107 )
2108 .expect("parse");
2109 assert_eq!(config.storage, None);
2110 }
2111
2112 #[test]
2113 fn sqlite_storage_parses_with_explicit_data_home() {
2114 let config = parse_doc(
2115 &format!(
2116 r#"{{ "version": 1, "storage": {{ "backend": "sqlite", "data_home": {} }} }}"#,
2117 serde_json::to_string(&abs("/data")).expect("json path")
2118 ),
2119 Path::new("/tmp/subc.jsonc"),
2120 )
2121 .expect("parse");
2122 assert_eq!(
2123 config.storage,
2124 Some(StorageConfig::Sqlite {
2125 data_home: abs("/data")
2126 })
2127 );
2128 }
2129
2130 #[test]
2131 fn sqlite_storage_defaults_data_home_when_omitted() {
2132 let _g = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
2138 std::env::set_var("XDG_DATA_HOME", abs("/forced/data/home"));
2139 let config = parse_doc(
2140 r#"{ "version": 1, "storage": { "backend": "sqlite" } }"#,
2141 Path::new("/tmp/subc.jsonc"),
2142 )
2143 .expect("parse");
2144 std::env::remove_var("XDG_DATA_HOME");
2145 assert_eq!(
2146 config.storage,
2147 Some(StorageConfig::Sqlite {
2148 data_home: abs("/forced/data/home")
2149 })
2150 );
2151 }
2152
2153 #[test]
2154 fn descriptor_for_matches_store_types_shape() {
2155 let cfg = StorageConfig::Sqlite {
2159 data_home: PathBuf::from("/data"),
2160 };
2161 let descriptor = cfg.descriptor_for("alfonso-routing");
2162 assert_eq!(
2163 descriptor,
2164 serde_json::json!({
2165 "module_id": "alfonso-routing",
2166 "storage_namespace": "default",
2167 "isolation": { "kind": "module" },
2168 "backend": {
2169 "backend": "sqlite",
2170 "path": "/data/cortexkit/alfonso-routing/store.db"
2171 }
2172 })
2173 );
2174 }
2175
2176 #[test]
2177 fn path_hazard_module_id_refuses_config_parse() {
2178 let path = Path::new("/tmp/subc.jsonc");
2179 let err = parse_doc(
2180 r#"{ "version": 1, "modules": { "../escape": { "program": "x" } } }"#,
2181 path,
2182 )
2183 .expect_err("separator-bearing module id must refuse");
2184 let text = format!("{err}");
2185 assert!(
2186 text.contains("not usable as a path component"),
2187 "refusal must name the hazard: {text}"
2188 );
2189 }
2190
2191 #[test]
2192 fn drain_timeout_resolves_module_over_daemon_over_absent() {
2193 let path = Path::new("/tmp/subc.jsonc");
2194 let config = parse_doc(
2195 r#"
2196 {
2197 "version": 1,
2198 "drain_timeout_ms": 45000,
2199 "modules": {
2200 "fast": { "program": "fast", "drain_timeout_ms": 0 },
2201 "slow": { "program": "slow", "drain_timeout_ms": 120000 },
2202 "inherits": { "program": "inherits" }
2203 }
2204 }
2205 "#,
2206 path,
2207 )
2208 .unwrap();
2209 let by_id = |id: &str| {
2210 config
2211 .modules
2212 .iter()
2213 .find(|m| m.module_id == id)
2214 .unwrap()
2215 .drain_timeout_ms
2216 };
2217 assert_eq!(by_id("fast"), Some(0));
2220 assert_eq!(by_id("slow"), Some(120_000));
2221 assert_eq!(by_id("inherits"), Some(45_000));
2223 assert_eq!(config.drain_timeout_ms, Some(45_000));
2224 }
2225
2226 #[test]
2227 fn drain_timeout_absent_everywhere_stays_none_for_builtin_default() {
2228 let path = Path::new("/tmp/subc.jsonc");
2229 let config = parse_doc(
2230 r#"{ "version": 1, "modules": { "m": { "program": "m" } } }"#,
2231 path,
2232 )
2233 .unwrap();
2234 assert_eq!(config.modules[0].drain_timeout_ms, None);
2238 assert_eq!(config.drain_timeout_ms, None);
2239 }
2240
2241 #[test]
2242 fn route_bind_relay_timeout_resolves_module_over_daemon_over_absent() {
2243 let path = Path::new("/tmp/subc.jsonc");
2249 let config = parse_doc(
2250 r#"
2251 {
2252 "version": 1,
2253 "route_bind_relay_timeout_ms": 30000,
2254 "modules": {
2255 "tight": { "program": "tight", "route_bind_relay_timeout_ms": 5000 },
2256 "loose": { "program": "loose", "route_bind_relay_timeout_ms": 60000 },
2257 "inherits": { "program": "inherits" }
2258 }
2259 }
2260 "#,
2261 path,
2262 )
2263 .unwrap();
2264 let by_id = |id: &str| {
2265 config
2266 .modules
2267 .iter()
2268 .find(|m| m.module_id == id)
2269 .unwrap()
2270 .route_bind_relay_timeout_ms
2271 };
2272 assert_eq!(by_id("tight"), Some(5_000));
2274 assert_eq!(by_id("loose"), Some(60_000));
2275 assert_eq!(by_id("inherits"), Some(30_000));
2277 assert_eq!(config.route_bind_relay_timeout_ms, Some(30_000));
2278 }
2279
2280 #[test]
2281 fn log_tag_keys_must_be_logger_names_and_the_error_names_the_key() {
2282 let path = Path::new("/tmp/subc.jsonc");
2283 for bad in ["Perf", "a b", "perf.", ".perf", "gc..walk", "a=b"] {
2284 let doc = format!(
2285 r#"{{ "version": 1, "modules": {{ "m": {{ "program": "m", "log": {{ "tags": {{ "{bad}": "debug" }} }} }} }} }}"#
2286 );
2287 let err = parse_doc(&doc, path).expect_err(bad);
2288 let text = format!("{err}");
2289 assert!(
2290 text.contains(&format!("{bad:?}")),
2291 "must name the key: {text}"
2292 );
2293 assert!(
2294 text.contains("logger name"),
2295 "must say what a key is: {text}"
2296 );
2297 }
2298 let ok = parse_doc(
2300 r#"{ "version": 1, "modules": { "m": { "program": "m", "log": { "tags": { "perf": "debug", "gc.walk": "trace", "m": "error", "a-b": "info" } } } } }"#,
2301 path,
2302 );
2303 assert!(ok.is_ok(), "{ok:?}");
2304 }
2305
2306 #[test]
2307 fn log_filter_spec_prefixes_bare_keys_with_the_module_and_passes_absolute_ones() {
2308 let path = Path::new("/tmp/subc.jsonc");
2309 let config = parse_doc(
2310 r#"{ "version": 1, "modules": { "synapse": { "program": "s", "log": { "level": "warn", "tags": { "perf": "debug", "gc.walk": "trace", "synapse": "error", "other.x": "info" } } } } }"#,
2311 path,
2312 )
2313 .unwrap();
2314 let log = config.modules[0].log.as_ref().unwrap();
2315 assert_eq!(
2317 log.filter_spec("synapse"),
2318 "warn,gc.walk=trace,other.x=info,synapse.perf=debug,synapse=error"
2319 );
2320 }
2321
2322 #[test]
2323 fn log_alarm_segment_mb_defaults_to_the_crate_default_and_refuses_zero() {
2324 let path = Path::new("/tmp/subc.jsonc");
2325 let config = parse_doc(
2326 r#"{ "version": 1, "modules": { "m": { "program": "m", "log": { "level": "info" } } } }"#,
2327 path,
2328 )
2329 .unwrap();
2330 assert_eq!(
2331 config.modules[0].log.as_ref().unwrap().alarm_segment_mb,
2332 cortexkit_log::SegmentRetention::default().alarm_segment_mb
2333 );
2334 let err = parse_doc(
2335 r#"{ "version": 1, "modules": { "m": { "program": "m", "log": { "alarm_segment_mb": 0 } } } }"#,
2336 path,
2337 )
2338 .expect_err("zero alarm must refuse");
2339 assert!(format!("{err}").contains("alarm_segment_mb"));
2340 }
2341
2342 #[test]
2343 fn route_bind_relay_timeout_zero_at_daemon_layer_is_refused() {
2344 let path = Path::new("/tmp/subc.jsonc");
2345 let err = parse_doc(
2346 r#"
2347 {
2348 "version": 1,
2349 "route_bind_relay_timeout_ms": 0,
2350 "modules": { "m": { "program": "m" } }
2351 }
2352 "#,
2353 path,
2354 )
2355 .expect_err("a daemon-wide zero budget must refuse parse");
2356 let text = format!("{err}");
2357 assert!(
2358 text.contains("route_bind_relay_timeout_ms"),
2359 "error must name the offending key: {text}"
2360 );
2361 assert!(
2362 text.contains("enabled: false"),
2363 "error must name the remedy (enable false): {text}"
2364 );
2365 }
2366
2367 #[test]
2368 fn route_bind_relay_timeout_zero_at_module_layer_is_refused() {
2369 let path = Path::new("/tmp/subc.jsonc");
2370 let err = parse_doc(
2371 r#"
2372 {
2373 "version": 1,
2374 "modules": {
2375 "good": { "program": "good" },
2376 "broken": { "program": "broken", "route_bind_relay_timeout_ms": 0 }
2377 }
2378 }
2379 "#,
2380 path,
2381 )
2382 .expect_err("a per-module zero budget must refuse parse");
2383 let text = format!("{err}");
2384 assert!(
2385 text.contains("route_bind_relay_timeout_ms"),
2386 "error must name the offending key: {text}"
2387 );
2388 assert!(
2389 text.contains("broken"),
2390 "error must name the offending module id: {text}"
2391 );
2392 assert!(
2393 text.contains("enabled: false"),
2394 "error must name the remedy (enable false): {text}"
2395 );
2396 }
2397
2398 #[test]
2399 fn drain_timeout_zero_still_parses_for_wedge_bounces() {
2400 let path = Path::new("/tmp/subc.jsonc");
2406 let config = parse_doc(
2407 r#"
2408 {
2409 "version": 1,
2410 "drain_timeout_ms": 0,
2411 "modules": {
2412 "wedge": { "program": "wedge", "drain_timeout_ms": 0 }
2413 }
2414 }
2415 "#,
2416 path,
2417 )
2418 .expect("drain_timeout_ms: 0 must still parse; wedge-bounce uses it");
2419 let wedge = config
2420 .modules
2421 .iter()
2422 .find(|m| m.module_id == "wedge")
2423 .unwrap();
2424 assert_eq!(wedge.drain_timeout_ms, Some(0));
2425 assert_eq!(config.drain_timeout_ms, Some(0));
2426 }
2427
2428 #[test]
2429 fn route_bind_relay_timeout_absent_everywhere_stays_none_for_builtin_default() {
2430 let path = Path::new("/tmp/subc.jsonc");
2435 let config = parse_doc(
2436 r#"{ "version": 1, "modules": { "m": { "program": "m" } } }"#,
2437 path,
2438 )
2439 .unwrap();
2440 assert_eq!(config.modules[0].route_bind_relay_timeout_ms, None);
2441 assert_eq!(config.route_bind_relay_timeout_ms, None);
2442 }
2443
2444 #[test]
2450 fn a_config_without_a_restart_block_keeps_the_supervisor_defaults() {
2451 let path = Path::new("/tmp/subc.jsonc");
2452 let config = parse_doc(
2453 r#"{ "version": 1, "modules": { "m": { "program": "m" } } }"#,
2454 path,
2455 )
2456 .unwrap();
2457 assert_eq!(config.modules[0].restart.max_restarts, 3);
2458 assert_eq!(config.modules[0].restart.window, Duration::from_secs(600));
2459 assert_eq!(
2460 config.modules[0].restart.backoff,
2461 Duration::from_millis(100)
2462 );
2463 assert_eq!(
2464 config.modules[0].restart.max_backoff,
2465 Duration::from_secs(30)
2466 );
2467 }
2468
2469 #[test]
2470 fn register_timeout_config_accepts_bounds_and_rejects_outside_them() {
2471 let path = Path::new("subc.jsonc");
2472 for seconds in [10, 3600] {
2473 let doc = format!(
2474 r#"{{"version":1,"modules":{{"m":{{"program":"m","register_timeout_s":{seconds}}}}}}}"#
2475 );
2476 let config = parse_doc(&doc, path).unwrap();
2477 assert_eq!(
2478 config.modules[0].register_timeout,
2479 Duration::from_secs(seconds)
2480 );
2481 }
2482 for value in ["9", "3601"] {
2483 let doc = format!(
2484 r#"{{"version":1,"modules":{{"m":{{"program":"m","register_timeout_s":{value}}}}}}}"#
2485 );
2486 let error = parse_doc(&doc, path).unwrap_err().to_string();
2487 assert!(error.contains("register_timeout_s"), "{value}: {error}");
2488 }
2489 let config = parse_doc(r#"{"version":1,"modules":{"m":{"program":"m"}}}"#, path).unwrap();
2490 assert_eq!(config.modules[0].register_timeout, Duration::from_secs(120));
2491 }
2492
2493 #[test]
2494 fn a_restart_block_resolves_each_key_independently() {
2495 let path = Path::new("/tmp/subc.jsonc");
2496 let config = parse_doc(
2497 r#"
2498 {
2499 "version": 1,
2500 "modules": {
2501 "all": {
2502 "program": "all",
2503 "restart": { "max_restarts": 5, "window_secs": 60, "backoff_ms": 250, "max_backoff_ms": 5000 }
2504 },
2505 "window-only": {
2506 "program": "window-only",
2507 "restart": { "window_secs": 7200 }
2508 },
2509 "never": {
2510 "program": "never",
2511 "restart": { "max_restarts": 0 }
2512 }
2513 }
2514 }
2515 "#,
2516 path,
2517 )
2518 .unwrap();
2519 let by_id = |id: &str| {
2520 config
2521 .modules
2522 .iter()
2523 .find(|m| m.module_id == id)
2524 .unwrap()
2525 .restart
2526 };
2527
2528 let all = by_id("all");
2529 assert_eq!(all.max_restarts, 5);
2530 assert_eq!(all.window, Duration::from_secs(60));
2531 assert_eq!(all.backoff, Duration::from_millis(250));
2532 assert_eq!(all.max_backoff, Duration::from_secs(5));
2533
2534 let window_only = by_id("window-only");
2537 assert_eq!(window_only.max_restarts, 3);
2538 assert_eq!(window_only.window, Duration::from_secs(7_200));
2539 assert_eq!(window_only.backoff, Duration::from_millis(100));
2540 assert_eq!(window_only.max_backoff, Duration::from_secs(30));
2541
2542 assert_eq!(by_id("never").max_restarts, 0);
2545 }
2546
2547 #[test]
2551 fn restart_window_zero_is_refused_by_name() {
2552 let path = Path::new("/tmp/subc.jsonc");
2553 let err = parse_doc(
2554 r#"
2555 {
2556 "version": 1,
2557 "modules": {
2558 "good": { "program": "good" },
2559 "broken": { "program": "broken", "restart": { "window_secs": 0 } }
2560 }
2561 }
2562 "#,
2563 path,
2564 )
2565 .expect_err("a zero crash window must refuse parse");
2566 assert!(
2567 matches!(err, DaemonConfigError::InvalidValue { .. }),
2568 "a zero window is an invalid value, not a parse failure: {err:?}"
2569 );
2570 let text = format!("{err}");
2571 assert!(
2572 text.contains("restart.window_secs"),
2573 "error must name the offending key: {text}"
2574 );
2575 assert!(
2576 text.contains("broken"),
2577 "error must name the offending module id: {text}"
2578 );
2579 assert!(
2580 text.contains("max_restarts: 0"),
2581 "error must name the setting that actually stops restarts: {text}"
2582 );
2583 }
2584
2585 #[test]
2586 fn restart_max_backoff_below_backoff_is_refused_by_name() {
2587 let path = Path::new("/tmp/subc.jsonc");
2588 let err = parse_doc(
2589 r#"
2590 {
2591 "version": 1,
2592 "modules": {
2593 "broken": {
2594 "program": "broken",
2595 "restart": { "backoff_ms": 1000, "max_backoff_ms": 999 }
2596 }
2597 }
2598 }
2599 "#,
2600 path,
2601 )
2602 .expect_err("a maximum below the base backoff must refuse parse");
2603 assert!(
2604 matches!(err, DaemonConfigError::InvalidValue { .. }),
2605 "an invalid restart bound must be an InvalidValue: {err:?}"
2606 );
2607 let text = format!("{err}");
2608 assert!(
2609 text.contains("restart.max_backoff_ms"),
2610 "error must name max_backoff_ms: {text}"
2611 );
2612 assert!(
2613 text.contains("restart.backoff_ms"),
2614 "error must name backoff_ms: {text}"
2615 );
2616 assert!(
2617 text.contains("broken"),
2618 "error must name the offending module id: {text}"
2619 );
2620 }
2621
2622 #[test]
2623 fn parse_jsonc_defaults_and_ignores_unknown_fields() {
2624 let path = Path::new("/tmp/subc.jsonc");
2625 let config = parse_doc(
2626 r#"
2627 {
2628 // forward-compatible root field
2629 "version": 1,
2630 "unknown": { "ignored": true },
2631 "modules": {
2632 "aft": {
2633 "program": "aft",
2634 "args": ["module",],
2635 "env": { "A": "B", },
2636 "future": 42,
2637 },
2638 "disabled": { "program": "disabled", "enabled": false }
2639 },
2640 }
2641 "#,
2642 path,
2643 )
2644 .unwrap();
2645
2646 assert_eq!(config.port, None);
2647 assert_eq!(config.modules.len(), 2);
2648 assert_eq!(config.modules[0].module_id, "aft");
2649 assert_eq!(config.modules[0].program, PathBuf::from("aft"));
2650 assert_eq!(config.modules[0].args, ["module"]);
2651 assert_eq!(config.modules[0].env, [("A".to_string(), "B".to_string())]);
2652 assert!(config.modules[0].enabled);
2653 assert!(config.modules[0].reserved_prefixes.is_empty());
2654 assert_eq!(config.modules[0].health, HealthConfig::default());
2655 assert!(!config.modules[1].enabled);
2656 }
2657
2658 #[test]
2659 fn reserved_capabilities_accept_unknown_bound_modules_and_refuse_bad_identifiers() {
2660 let path = Path::new("/tmp/subc.jsonc");
2661 let config = parse_doc(
2662 r#"{
2663 "version": 1,
2664 "reserved_capabilities": {
2665 "credentials-provider/v1": "future-vault"
2666 },
2667 "modules": {}
2668 }"#,
2669 path,
2670 )
2671 .expect("a binding may predate its provider installation");
2672 assert_eq!(
2673 config.reserved_capabilities,
2674 BTreeMap::from([(
2675 "credentials-provider/v1".to_string(),
2676 "future-vault".to_string()
2677 )])
2678 );
2679
2680 let error = parse_doc(
2681 r#"{
2682 "version": 1,
2683 "reserved_capabilities": { "Credentials/v1": "vault" },
2684 "modules": {}
2685 }"#,
2686 path,
2687 )
2688 .expect_err("reserved capabilities use the capability identifier grammar");
2689 assert!(error.to_string().contains("reserved_capabilities key"));
2690 }
2691
2692 #[test]
2693 fn retired_launch_nonce_env_is_ignored_for_any_value() {
2694 let parse = |field: &str| {
2695 parse_doc(
2696 &format!(r#"{{"version":1,"modules":{{"probe":{{"program":"probe"{field}}}}}}}"#),
2697 Path::new("subc.jsonc"),
2698 )
2699 .unwrap()
2700 .modules
2701 .remove(0)
2702 .module_spec()
2703 };
2704 for value in ["true", "false", "null", "0", "\"false\"", "[]", "{}"] {
2705 assert_eq!(
2706 parse(""),
2707 parse(&format!(",\"launch_nonce_env\":{value}")),
2708 "the retired key must not change the launch spec or require a restart"
2709 );
2710 }
2711 }
2712
2713 #[test]
2716 fn an_absent_protocol_key_and_an_explicit_subc_are_the_same_module() {
2717 let parse = |module_body: &str| {
2718 parse_doc(
2719 &format!(
2720 r#"{{
2721 "version": 1,
2722 "modules": {{ "aft": {{ "program": "aft"{module_body} }} }}
2723 }}"#
2724 ),
2725 Path::new("subc.jsonc"),
2726 )
2727 .expect("module parses")
2728 .modules
2729 .remove(0)
2730 };
2731
2732 let absent = parse("");
2733 let explicit = parse(r#", "protocol": "subc""#);
2734 let none = parse(r#", "protocol": "none""#);
2735
2736 assert_eq!(absent.protocol, ModuleProtocol::Subc);
2737 assert_eq!(explicit.protocol, ModuleProtocol::Subc);
2738 assert_eq!(
2739 absent, explicit,
2740 "an absent protocol key must produce exactly the module an explicit subc does"
2741 );
2742 assert_eq!(none.protocol, ModuleProtocol::None);
2743 assert_eq!(none.module_spec().protocol, ModuleProtocol::None);
2747 }
2748
2749 #[test]
2753 fn overlap_defaults_to_exclusive_and_only_safe_opts_in() {
2754 let parse = |module_body: &str| {
2755 parse_doc(
2756 &format!(
2757 r#"{{
2758 "version": 1,
2759 "modules": {{ "aft": {{ "program": "aft"{module_body} }} }}
2760 }}"#
2761 ),
2762 Path::new("subc.jsonc"),
2763 )
2764 };
2765
2766 let absent = parse("").unwrap().modules.remove(0);
2767 assert_eq!(absent.overlap, ModuleOverlap::Exclusive);
2768 assert_eq!(absent.module_spec().overlap, ModuleOverlap::Exclusive);
2769 let safe = parse(r#", "overlap": "safe""#).unwrap().modules.remove(0);
2770 assert_eq!(safe.module_spec().overlap, ModuleOverlap::Safe);
2771 let typo = parse(r#", "overlap": "sfae""#).expect_err("an unknown overlap is refused");
2772 assert!(typo.to_string().contains("sfae"), "{typo}");
2773 }
2774
2775 #[test]
2776 fn carry_containment_defaults_off_and_refuses_overlap() {
2777 let parse = |module_body: &str| {
2778 parse_doc(
2779 &format!(
2780 r#"{{
2781 "version": 1,
2782 "modules": {{ "worker": {{ "program": "worker"{module_body} }} }}
2783 }}"#
2784 ),
2785 Path::new("subc.jsonc"),
2786 )
2787 };
2788
2789 let absent = parse("").unwrap().modules.remove(0);
2790 let explicit_off = parse(r#", "carry_containment": false"#)
2791 .unwrap()
2792 .modules
2793 .remove(0);
2794 assert_eq!(absent, explicit_off);
2795 assert!(!absent.module_spec().carry_containment);
2796 let carried = parse(r#", "carry_containment": true"#)
2797 .unwrap()
2798 .modules
2799 .remove(0);
2800 assert!(carried.module_spec().carry_containment);
2801 let error = parse(r#", "carry_containment": true, "overlap": "safe""#)
2802 .expect_err("a carried container cannot have overlapping leaders");
2803 let message = error.to_string();
2804 assert!(message.contains("worker"), "{message}");
2805 assert!(message.contains("carry_containment"), "{message}");
2806 assert!(message.contains("overlap"), "{message}");
2807 }
2808
2809 #[test]
2813 fn the_spawn_role_is_refused_as_a_configured_env_key() {
2814 let error = parse_doc(
2815 r#"{
2816 "version": 1,
2817 "modules": { "aft": { "program": "aft", "env": { "SUBC_SPAWN_ROLE": "swap_candidate" } } }
2818 }"#,
2819 Path::new("subc.jsonc"),
2820 )
2821 .expect_err("SUBC_SPAWN_ROLE must not be configurable");
2822 assert!(
2823 matches!(error, DaemonConfigError::InvalidValue { .. }),
2824 "expected InvalidValue, got {error:?}"
2825 );
2826 assert!(error.to_string().contains("SUBC_SPAWN_ROLE"), "{error}");
2827 }
2828
2829 #[test]
2835 fn an_unsupported_protocol_value_is_refused_by_name() {
2836 let error = parse_doc(
2837 r#"{
2838 "version": 1,
2839 "modules": { "nats": { "program": "nats-server", "protocol": "grpc" } }
2840 }"#,
2841 Path::new("subc.jsonc"),
2842 )
2843 .expect_err("an unknown protocol must not fall back to a default");
2844
2845 assert!(
2846 matches!(error, DaemonConfigError::InvalidValue { .. }),
2847 "expected InvalidValue, got {error:?}"
2848 );
2849 let message = error.to_string();
2850 assert!(
2851 message.contains("grpc"),
2852 "the refusal must name the offending value: {message}"
2853 );
2854 assert!(
2855 message.contains("nats"),
2856 "the refusal must name the module so it can be found in the file: {message}"
2857 );
2858 }
2859
2860 #[test]
2864 fn reserved_true_with_protocol_none_is_refused_with_the_reason() {
2865 let error = parse_doc(
2866 r#"{
2867 "version": 1,
2868 "modules": {
2869 "nats": { "program": "nats-server", "protocol": "none", "reserved": true }
2870 }
2871 }"#,
2872 Path::new("subc.jsonc"),
2873 )
2874 .expect_err("a reservation that can never be checked must not parse");
2875
2876 assert!(
2877 matches!(error, DaemonConfigError::InvalidValue { .. }),
2878 "expected InvalidValue, got {error:?}"
2879 );
2880 let message = error.to_string();
2881 assert!(
2882 message.contains("nats") && message.contains("reserved"),
2883 "the refusal must name the module and the offending key: {message}"
2884 );
2885 assert!(
2886 message.contains("HELLO") || message.contains("never registers"),
2887 "the refusal must say WHY the pair cannot work: {message}"
2888 );
2889 }
2890
2891 #[test]
2892 fn reserved_prefixes_parse_for_reserved_modules() {
2893 let config = parse_doc(
2894 r#"
2895 {
2896 "version": 1,
2897 "modules": {
2898 "federation": {
2899 "program": "fed",
2900 "reserved": true,
2901 "reserved_prefixes": ["fed:"]
2902 }
2903 }
2904 }
2905 "#,
2906 Path::new("subc.jsonc"),
2907 )
2908 .unwrap();
2909
2910 assert_eq!(config.modules[0].reserved_prefixes, ["fed:".to_string()]);
2911 }
2912
2913 #[test]
2914 fn reserved_prefixes_reject_bad_boundaries_and_owners() {
2915 let missing_delimiter = parse_doc(
2916 r#"{
2917 "version": 1,
2918 "modules": {
2919 "federation": { "program": "fed", "reserved": true, "reserved_prefixes": ["fed"] }
2920 }
2921 }"#,
2922 Path::new("subc.jsonc"),
2923 )
2924 .unwrap_err();
2925 assert!(matches!(
2926 missing_delimiter,
2927 DaemonConfigError::InvalidValue { .. }
2928 ));
2929
2930 let non_reserved_owner = parse_doc(
2931 r#"{
2932 "version": 1,
2933 "modules": {
2934 "federation": { "program": "fed", "reserved_prefixes": ["fed:"] }
2935 }
2936 }"#,
2937 Path::new("subc.jsonc"),
2938 )
2939 .unwrap_err();
2940 assert!(matches!(
2941 non_reserved_owner,
2942 DaemonConfigError::InvalidValue { .. }
2943 ));
2944 }
2945
2946 #[test]
2947 fn reserved_prefixes_reject_cross_owner_overlap_and_exact_id_collisions() {
2948 let overlap = parse_doc(
2949 r#"{
2950 "version": 1,
2951 "modules": {
2952 "fed-owner": { "program": "fed", "reserved": true, "reserved_prefixes": ["fed:"] },
2953 "sub-owner": { "program": "fed-sub", "reserved": true, "reserved_prefixes": ["fed:sub:"] }
2954 }
2955 }"#,
2956 Path::new("subc.jsonc"),
2957 )
2958 .unwrap_err();
2959 assert!(matches!(overlap, DaemonConfigError::InvalidValue { .. }));
2960
2961 let exact_collision = parse_doc(
2962 r#"{
2963 "version": 1,
2964 "modules": {
2965 "federation": { "program": "fed", "reserved": true, "reserved_prefixes": ["fed:"] },
2966 "fed:special": { "program": "special" }
2967 }
2968 }"#,
2969 Path::new("subc.jsonc"),
2970 )
2971 .unwrap_err();
2972 assert!(matches!(
2973 exact_collision,
2974 DaemonConfigError::InvalidValue { .. }
2975 ));
2976 }
2977
2978 #[test]
2979 fn health_config_parses_and_ignores_unknown_fields() {
2980 let config = parse_doc(
2981 r#"
2982 {
2983 "version": 1,
2984 "modules": {
2985 "aft": {
2986 "program": "aft",
2987 "health": {
2988 "cadence_ms": 100,
2989 "deadline_ms": 20,
2990 "failure_threshold": 2,
2991 "on_degraded": "report",
2992 "on_failing": "restart",
2993 "critical": true,
2994 "future": "ignored"
2995 }
2996 }
2997 }
2998 }
2999 "#,
3000 Path::new("subc.jsonc"),
3001 )
3002 .unwrap();
3003
3004 let health = &config.modules[0].health;
3005 assert_eq!(health.cadence, std::time::Duration::from_millis(100));
3006 assert_eq!(health.deadline, std::time::Duration::from_millis(20));
3007 assert_eq!(health.failure_threshold, 2);
3008 assert_eq!(health.on_degraded, HealthAction::Report);
3009 assert_eq!(health.on_failing, HealthAction::Restart);
3010 assert!(health.critical);
3011 }
3012
3013 #[test]
3014 fn http_health_refuses_non_loopback_https_and_wire_modules() {
3015 for (protocol, url) in [
3016 ("none", "http://example.com/healthz"),
3017 ("none", "https://127.0.0.1/healthz"),
3018 ("subc", "http://127.0.0.1/healthz"),
3019 ] {
3020 let doc = serde_json::json!({"version": 1, "modules": {"bus": {
3021 "program": "nats-server", "protocol": protocol, "health": {"http": url}
3022 }}})
3023 .to_string();
3024 let error = parse_doc(&doc, Path::new("test.jsonc"))
3025 .unwrap_err()
3026 .to_string();
3027 assert!(
3028 error.contains("bus") && error.contains("health.http"),
3029 "{error}"
3030 );
3031 }
3032 }
3033
3034 #[test]
3035 fn health_config_rejects_bad_enum_and_non_positive_numbers() {
3036 let bad_enum = parse_doc(
3037 r#"{
3038 "version": 1,
3039 "modules": { "aft": { "program": "aft", "health": { "on_failing": "page" } } }
3040 }"#,
3041 Path::new("subc.jsonc"),
3042 )
3043 .unwrap_err();
3044 assert!(matches!(bad_enum, DaemonConfigError::InvalidJson { .. }));
3045
3046 let zero = parse_doc(
3047 r#"{
3048 "version": 1,
3049 "modules": { "aft": { "program": "aft", "health": { "cadence_ms": 0 } } }
3050 }"#,
3051 Path::new("subc.jsonc"),
3052 )
3053 .unwrap_err();
3054 assert!(matches!(zero, DaemonConfigError::InvalidValue { .. }));
3055 }
3056
3057 #[test]
3058 fn admission_facts_carrier_requires_non_empty_targets() {
3059 let missing_targets = parse_doc(
3060 r#"{
3061 "version": 1,
3062 "admission_facts_carrier_module_id": "fed",
3063 "modules": { "fed": { "program": "fed", "reserved": true } }
3064 }"#,
3065 Path::new("subc.jsonc"),
3066 )
3067 .unwrap_err();
3068 assert!(
3074 matches!(&missing_targets, DaemonConfigError::InvalidValue { message, .. }
3075 if message.contains("must be present")),
3076 "expected the presence rule, got: {missing_targets:?}"
3077 );
3078
3079 let empty_targets = parse_doc(
3080 r#"{
3081 "version": 1,
3082 "admission_facts_carrier_module_id": "fed",
3083 "admission_facts_targets": [""],
3084 "modules": { "fed": { "program": "fed", "reserved": true } }
3085 }"#,
3086 Path::new("subc.jsonc"),
3087 )
3088 .unwrap_err();
3089 assert!(
3090 matches!(&empty_targets, DaemonConfigError::InvalidValue { message, .. }
3091 if message.contains("must be non-empty")),
3092 "expected the non-empty rule, got: {empty_targets:?}"
3093 );
3094 }
3095
3096 #[test]
3097 fn admission_facts_carrier_must_be_enabled_reserved_and_configured() {
3098 for module in [
3099 r#"{ "program": "fed", "enabled": false, "reserved": true }"#,
3100 r#"{ "program": "fed", "enabled": true, "reserved": false }"#,
3101 ] {
3102 let doc = format!(
3103 r#"{{
3104 "version": 1,
3105 "admission_facts_carrier_module_id": "fed",
3106 "admission_facts_targets": ["target"],
3107 "modules": {{ "fed": {module}, "target": {{ "program": "target" }} }}
3108 }}"#
3109 );
3110 let err = parse_doc(&doc, Path::new("subc.jsonc")).unwrap_err();
3111 assert!(
3115 matches!(&err, DaemonConfigError::InvalidValue { message, .. }
3116 if message.contains("enabled reserved module")),
3117 "expected the enabled-and-reserved rule, got: {err:?}"
3118 );
3119 }
3120
3121 let absent = parse_doc(
3122 r#"{
3123 "version": 1,
3124 "admission_facts_carrier_module_id": "missing",
3125 "admission_facts_targets": ["target"],
3126 "modules": { "target": { "program": "target" } }
3127 }"#,
3128 Path::new("subc.jsonc"),
3129 )
3130 .unwrap_err();
3131 assert!(
3132 matches!(&absent, DaemonConfigError::InvalidValue { message, .. }
3133 if message.contains("must name a configured module")),
3134 "expected the configured-module rule, got: {absent:?}"
3135 );
3136 }
3137
3138 #[test]
3139 fn reject_unsupported_version() {
3140 let err = parse_doc(
3141 r#"{ "version": 2, "modules": {} }"#,
3142 Path::new("subc.jsonc"),
3143 )
3144 .unwrap_err();
3145 assert!(matches!(
3146 err,
3147 DaemonConfigError::UnsupportedVersion { version: 2, .. }
3148 ));
3149 }
3150
3151 #[test]
3152 fn reject_unterminated_block_comment() {
3153 let err = parse_doc(r#"{ "version": 1, /*"#, Path::new("subc.jsonc")).unwrap_err();
3154 assert!(matches!(err, DaemonConfigError::InvalidJsonc { .. }));
3155 }
3156}
3157
3158#[cfg(test)]
3159mod activity_config_tests {
3160 use super::*;
3161
3162 #[test]
3163 fn activity_config_defaults_partial_overrides_and_positive_bounds() {
3164 let path = Path::new("subc.jsonc");
3165 let default = parse_doc_with_activity(r#"{"version":1,"modules":{}}"#, path).unwrap();
3166 assert_eq!(
3167 default.1,
3168 ActivityConfig {
3169 max_age_days: 30,
3170 max_total_mb: 64
3171 }
3172 );
3173 let changed = parse_doc_with_activity(
3174 r#"{"version":1,"activity":{"max_age_days":7,"max_total_mb":8}}"#,
3175 path,
3176 )
3177 .unwrap();
3178 assert_eq!(
3179 changed.1,
3180 ActivityConfig {
3181 max_age_days: 7,
3182 max_total_mb: 8
3183 }
3184 );
3185 let partial =
3186 parse_doc_with_activity(r#"{"version":1,"activity":{"max_age_days":7}}"#, path)
3187 .unwrap();
3188 assert_eq!(
3189 partial.1,
3190 ActivityConfig {
3191 max_age_days: 7,
3192 max_total_mb: 64
3193 }
3194 );
3195 for doc in [
3196 r#"{"version":1,"activity":{"max_age_days":0}}"#,
3197 r#"{"version":1,"activity":{"max_total_mb":0}}"#,
3198 ] {
3199 assert!(parse_doc(doc, path).is_err());
3200 }
3201 assert!(!RestartRequiredSection::ALL
3202 .iter()
3203 .any(|section| section.label() == "activity"));
3204 }
3205}
3206
3207#[cfg(test)]
3208mod registration_declaration_tests {
3209 use super::*;
3210 #[test]
3211 fn registration_declaration_config_bool_is_optional_and_typed() {
3212 let parse = |field: &str| {
3213 parse_doc(
3214 &format!(r#"{{"version":1,"modules":{{"worker":{{"program":"worker"{field}}}}}}}"#),
3215 Path::new("subc.jsonc"),
3216 )
3217 };
3218 assert!(!parse("").unwrap().modules[0].registration_channel);
3219 assert!(
3220 !parse(r#", "registration_channel":false"#).unwrap().modules[0].registration_channel
3221 );
3222 assert!(parse(r#", "registration_channel":true"#).unwrap().modules[0].registration_channel);
3223 assert!(parse(r#", "registration_channel":"true""#).is_err());
3224 }
3225}