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