1use std::{collections::BTreeMap, fs, io, path::Path};
2
3use serde::{Deserialize, Deserializer, Serialize, de};
4
5use crate::{
6 Error, Result,
7 types::{JobClass, JobProfile},
8};
9
10#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
16#[serde(default, deny_unknown_fields)]
17pub struct Config {
18 pub daemon: DaemonConfig,
20 pub admission: AdmissionConfig,
22 pub benchmark: BenchmarkConfig,
24 pub leases: LeaseConfig,
26 pub retention: RetentionConfig,
28 pub hook: HookConfig,
30 pub classes: ClassProfiles,
32 pub presets: Presets,
34 pub classifier: ClassifierConfig,
36 pub linux: LinuxConfig,
38}
39
40impl Config {
41 pub fn from_toml(text: &str) -> Result<Self> {
48 let config: Self = toml::from_str(text)?;
49 config.validate()?;
50 Ok(config)
51 }
52
53 pub fn load(path: &Path) -> Result<Self> {
60 let loaded = match fs::read_to_string(path) {
61 Ok(text) => Self::from_toml(&text),
62 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Self::default()),
63 Err(error) => Err(error.into()),
64 };
65 loaded.map_err(|reason| Error::ConfigFile {
66 path: path.to_owned(),
67 reason: Box::new(reason),
68 })
69 }
70
71 pub fn validate(&self) -> Result<()> {
77 ensure(self.daemon.port != 0, "daemon.port must not be 0")?;
78 ensure(
79 (0.0..100.0).contains(&self.admission.headroom_pct),
80 "admission.headroom_pct must be at least 0 and below 100",
81 )?;
82 ensure(
83 is_pct(self.benchmark.quiet_cpu_pct),
84 "benchmark.quiet_cpu_pct must be 0 to 100",
85 )?;
86 ensure(
87 is_pct(self.benchmark.quiet_gpu_pct),
88 "benchmark.quiet_gpu_pct must be 0 to 100",
89 )?;
90 ensure(
91 self.benchmark.quiet_secs > 0,
92 "benchmark.quiet_secs must be positive",
93 )?;
94 ensure(
95 self.benchmark.max_quiet_wait_secs >= self.benchmark.quiet_secs,
96 "benchmark.max_quiet_wait_secs must be at least quiet_secs",
97 )?;
98 ensure(
99 self.leases.heartbeat_ttl_secs > 0,
100 "leases.heartbeat_ttl_secs must be positive",
101 )?;
102 let retention = &self.retention;
103 ensure(
104 retention.lease_days > 0,
105 "retention.lease_days must be positive",
106 )?;
107 ensure(
108 retention.history_days > 0,
109 "retention.history_days must be positive",
110 )?;
111 ensure(
112 retention.keep_runs_per_job > 0,
113 "retention.keep_runs_per_job must be positive",
114 )?;
115 ensure(
116 retention.max_job_runs >= retention.keep_runs_per_job,
117 "retention.max_job_runs must be at least keep_runs_per_job",
118 )?;
119 for class in JobClass::ALL {
120 if let Some(reason) = self.classes.get(class).invalid_reason() {
121 return Err(Error::Config(format!(
122 "classes.{}: {reason}",
123 class.as_str()
124 )));
125 }
126 }
127 for (name, profile) in &self.presets.0 {
128 let well_formed = !name.is_empty()
129 && name
130 .bytes()
131 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_');
132 ensure(
133 well_formed,
134 format!("presets.{name}: names use only a-z, 0-9 and _"),
135 )?;
136 ensure(
137 JobClass::ALL.iter().all(|class| class.as_str() != name),
138 format!("presets.{name}: a class already has this name"),
139 )?;
140 if let Some(reason) = profile.invalid_reason() {
141 return Err(Error::Config(format!("presets.{name}: {reason}")));
142 }
143 }
144 for (index, rule) in self.classifier.rules.iter().enumerate() {
145 let has_blank =
146 rule.program.trim().is_empty() || rule.args.iter().any(|arg| arg.trim().is_empty());
147 ensure(
148 !has_blank,
149 format!("classifier.rules[{index}] has a blank program or arg"),
150 )?;
151 }
152 let flags = &self.classifier.light_flags;
153 ensure(
154 flags.iter().all(|flag| !flag.trim().is_empty()),
155 "classifier.light_flags must not contain blank entries",
156 )?;
157 Ok(())
158 }
159}
160
161fn ensure(condition: bool, message: impl Into<String>) -> Result<()> {
162 if condition {
163 Ok(())
164 } else {
165 Err(Error::Config(message.into()))
166 }
167}
168
169fn is_pct(value: f32) -> bool {
170 (0.0..=100.0).contains(&value)
171}
172
173#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
175#[serde(default, deny_unknown_fields)]
176pub struct DaemonConfig {
177 pub port: u16,
179}
180
181impl Default for DaemonConfig {
182 fn default() -> Self {
183 Self { port: 47_823 }
184 }
185}
186
187#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
189#[serde(default, deny_unknown_fields)]
190pub struct AdmissionConfig {
191 pub headroom_pct: f32,
194}
195
196impl Default for AdmissionConfig {
197 fn default() -> Self {
198 Self { headroom_pct: 15.0 }
199 }
200}
201
202#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
204#[serde(default, deny_unknown_fields)]
205pub struct BenchmarkConfig {
206 pub quiet_cpu_pct: f32,
208 pub quiet_gpu_pct: f32,
210 pub quiet_secs: u64,
213 pub max_quiet_wait_secs: u64,
216}
217
218impl Default for BenchmarkConfig {
219 fn default() -> Self {
220 Self {
221 quiet_cpu_pct: 10.0,
222 quiet_gpu_pct: 10.0,
223 quiet_secs: 10,
224 max_quiet_wait_secs: 60,
225 }
226 }
227}
228
229#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
231#[serde(default, deny_unknown_fields)]
232pub struct LeaseConfig {
233 pub heartbeat_ttl_secs: u64,
235 pub idle_release_secs: u64,
238}
239
240impl Default for LeaseConfig {
241 fn default() -> Self {
242 Self {
243 heartbeat_ttl_secs: 60,
244 idle_release_secs: 180,
245 }
246 }
247}
248
249#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
251#[serde(default, deny_unknown_fields)]
252pub struct RetentionConfig {
253 pub lease_days: u64,
256 pub history_days: u64,
259 pub keep_runs_per_job: u64,
262 pub max_job_runs: u64,
264}
265
266impl Default for RetentionConfig {
267 fn default() -> Self {
268 Self {
269 lease_days: 30,
270 history_days: 90,
271 keep_runs_per_job: 20,
272 max_job_runs: 5_000,
273 }
274 }
275}
276
277#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
279#[serde(default, deny_unknown_fields)]
280pub struct HookConfig {
281 pub fail_open: bool,
284}
285
286impl Default for HookConfig {
287 fn default() -> Self {
288 Self { fail_open: true }
289 }
290}
291
292#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
298#[serde(default, deny_unknown_fields)]
299pub struct LinuxConfig {
300 pub scopes: bool,
303 pub enforce_cpu: bool,
305 pub enforce_memory: bool,
307}
308
309impl Default for LinuxConfig {
310 fn default() -> Self {
311 Self {
312 scopes: true,
313 enforce_cpu: false,
314 enforce_memory: false,
315 }
316 }
317}
318
319#[derive(Debug, Clone, PartialEq, Serialize)]
324pub struct ClassProfiles {
325 pub light: JobProfile,
327 pub cpu_heavy: JobProfile,
329 pub gpu_heavy: JobProfile,
331 pub mixed: JobProfile,
333}
334
335impl ClassProfiles {
336 pub fn get(&self, class: JobClass) -> &JobProfile {
338 match class {
339 JobClass::Light => &self.light,
340 JobClass::CpuHeavy => &self.cpu_heavy,
341 JobClass::GpuHeavy => &self.gpu_heavy,
342 JobClass::Mixed => &self.mixed,
343 }
344 }
345}
346
347impl Default for ClassProfiles {
348 fn default() -> Self {
349 Self {
350 light: JobProfile {
351 cores: 1.0,
352 ram_mb: 512,
353 gpu_pct: 0.0,
354 vram_mb: 0,
355 est_secs: 30,
356 },
357 cpu_heavy: JobProfile {
358 cores: 8.0,
359 ram_mb: 4096,
360 gpu_pct: 0.0,
361 vram_mb: 0,
362 est_secs: 300,
363 },
364 gpu_heavy: JobProfile {
365 cores: 2.0,
366 ram_mb: 4096,
367 gpu_pct: 80.0,
368 vram_mb: 4096,
369 est_secs: 600,
370 },
371 mixed: JobProfile {
372 cores: 6.0,
373 ram_mb: 8192,
374 gpu_pct: 50.0,
375 vram_mb: 2048,
376 est_secs: 600,
377 },
378 }
379 }
380}
381
382impl<'de> Deserialize<'de> for ClassProfiles {
383 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
384 where
385 D: Deserializer<'de>,
386 {
387 let overrides = ClassOverrides::deserialize(deserializer)?;
388 let defaults = Self::default();
389 Ok(Self {
390 light: overrides.light.apply(defaults.light),
391 cpu_heavy: overrides.cpu_heavy.apply(defaults.cpu_heavy),
392 gpu_heavy: overrides.gpu_heavy.apply(defaults.gpu_heavy),
393 mixed: overrides.mixed.apply(defaults.mixed),
394 })
395 }
396}
397
398#[derive(Default, Deserialize)]
399#[serde(default, deny_unknown_fields)]
400struct ClassOverrides {
401 light: ProfileOverride,
402 cpu_heavy: ProfileOverride,
403 gpu_heavy: ProfileOverride,
404 mixed: ProfileOverride,
405}
406
407#[derive(Default, Deserialize)]
408#[serde(deny_unknown_fields)]
409struct ProfileOverride {
410 cores: Option<f32>,
411 ram_mb: Option<u64>,
412 gpu_pct: Option<f32>,
413 vram_mb: Option<u64>,
414 est_secs: Option<u64>,
415}
416
417impl ProfileOverride {
418 fn apply(self, base: JobProfile) -> JobProfile {
419 JobProfile {
420 cores: self.cores.unwrap_or(base.cores),
421 ram_mb: self.ram_mb.unwrap_or(base.ram_mb),
422 gpu_pct: self.gpu_pct.unwrap_or(base.gpu_pct),
423 vram_mb: self.vram_mb.unwrap_or(base.vram_mb),
424 est_secs: self.est_secs.unwrap_or(base.est_secs),
425 }
426 }
427}
428
429#[derive(Debug, Clone, PartialEq, Serialize)]
435#[serde(transparent)]
436pub struct Presets(pub BTreeMap<String, JobProfile>);
437
438const PRESET_EST_SECS: u64 = 300;
440
441impl Presets {
442 pub fn get(&self, name: &str) -> Option<&JobProfile> {
444 self.0.get(name)
445 }
446
447 pub fn names(&self) -> impl Iterator<Item = &str> {
449 self.0.keys().map(String::as_str)
450 }
451}
452
453impl Default for Presets {
454 fn default() -> Self {
455 let preset = |cores, ram_mb, gpu_pct, vram_mb, est_secs| JobProfile {
456 cores,
457 ram_mb,
458 gpu_pct,
459 vram_mb,
460 est_secs,
461 };
462 Self(BTreeMap::from([
463 ("cpu_small".to_owned(), preset(2.0, 1024, 0.0, 0, 60)),
464 ("cpu_medium".to_owned(), preset(4.0, 2048, 0.0, 0, 180)),
465 ("gpu_small".to_owned(), preset(1.0, 2048, 30.0, 2048, 300)),
466 ("quick".to_owned(), preset(4.0, 2048, 0.0, 0, 10)),
467 ("low_impact".to_owned(), preset(0.25, 256, 0.0, 0, 60)),
468 ]))
469 }
470}
471
472impl<'de> Deserialize<'de> for Presets {
473 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
474 where
475 D: Deserializer<'de>,
476 {
477 let overrides = BTreeMap::<String, ProfileOverride>::deserialize(deserializer)?;
478 let mut presets = Self::default();
479 for (name, value) in overrides {
480 let profile = match presets.0.get(&name) {
481 Some(&base) => value.apply(base),
482 None => {
483 let (Some(cores), Some(ram_mb)) = (value.cores, value.ram_mb) else {
484 return Err(de::Error::custom(format!(
485 "new preset `{name}` needs both cores and ram_mb"
486 )));
487 };
488 value.apply(JobProfile {
489 cores,
490 ram_mb,
491 gpu_pct: 0.0,
492 vram_mb: 0,
493 est_secs: PRESET_EST_SECS,
494 })
495 }
496 };
497 presets.0.insert(name, profile);
498 }
499 Ok(presets)
500 }
501}
502
503#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
505#[serde(default, deny_unknown_fields)]
506pub struct ClassifierConfig {
507 pub rules: Vec<HeavyRule>,
509 pub light_flags: Vec<String>,
512}
513
514impl Default for ClassifierConfig {
515 fn default() -> Self {
516 Self {
517 rules: vec![
518 HeavyRule::new(
519 "cargo",
520 &["build", "test", "run", "bench"],
521 JobClass::CpuHeavy,
522 ),
523 HeavyRule::new("pnpm", &["build", "test"], JobClass::CpuHeavy),
524 HeavyRule::new("msbuild", &[], JobClass::CpuHeavy),
525 HeavyRule::new("cmake", &["--build"], JobClass::CpuHeavy),
526 HeavyRule::new("python*", &["train*.py"], JobClass::GpuHeavy),
527 HeavyRule::new("py", &["train*.py"], JobClass::GpuHeavy),
528 ],
529 light_flags: ["--help", "-h", "--version", "-V", "/?"]
530 .map(String::from)
531 .to_vec(),
532 }
533 }
534}
535
536#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
540#[serde(deny_unknown_fields)]
541pub struct HeavyRule {
542 pub program: String,
544 #[serde(default)]
548 pub args: Vec<String>,
549 pub class: JobClass,
551}
552
553impl HeavyRule {
554 fn new(program: &str, args: &[&str], class: JobClass) -> Self {
555 Self {
556 program: program.into(),
557 args: args.iter().map(|&arg| arg.into()).collect(),
558 class,
559 }
560 }
561}
562
563#[cfg(test)]
564mod tests {
565 use std::env;
566
567 use super::*;
568 use crate::mutate::mutations;
569
570 fn config_error(text: &str) -> String {
571 match Config::from_toml(text) {
572 Err(Error::Config(message)) => message,
573 other => panic!("expected Error::Config, got {other:?}"),
574 }
575 }
576
577 #[test]
578 fn test_config_empty_document_yields_defaults() {
579 assert_eq!(Config::from_toml("").unwrap(), Config::default());
580 }
581
582 #[test]
583 fn test_config_default_passes_validation() {
584 Config::default().validate().unwrap();
585 }
586
587 #[test]
588 fn test_config_default_toml_round_trip_preserves_every_value() {
589 let text = toml::to_string(&Config::default()).unwrap();
590 assert_eq!(Config::from_toml(&text).unwrap(), Config::default());
591 }
592
593 #[test]
594 fn test_config_presets_merge_over_defaults_and_add_new_ones() {
595 let config = Config::from_toml(
596 "[presets.cpu_small]\ncores = 3.0\n\n[presets.render_preview]\ncores = 2.0\n\
597 ram_mb = 3000\ngpu_pct = 40.0\n",
598 )
599 .unwrap();
600 let defaults = Presets::default();
601 let small = config.presets.get("cpu_small").unwrap();
602 assert_eq!(small.cores, 3.0);
603 assert_eq!(small.est_secs, defaults.get("cpu_small").unwrap().est_secs);
604 let preview = config.presets.get("render_preview").unwrap();
605 assert_eq!((preview.gpu_pct, preview.vram_mb), (40.0, 0));
606 assert_eq!(preview.est_secs, PRESET_EST_SECS);
607 assert_eq!(config.presets.get("quick"), defaults.get("quick"));
608 }
609
610 #[test]
611 fn test_config_presets_reject_bad_names_and_incomplete_new_ones() {
612 assert!(config_error("[presets.cpu_heavy]\ncores = 1.0\nram_mb = 1\n").contains("class"));
613 assert!(config_error("[presets.Big]\ncores = 1.0\nram_mb = 1\n").contains("a-z"));
614 assert!(config_error("[presets.quick]\ngpu_pct = 140.0\n").contains("presets.quick"));
615 let incomplete = Config::from_toml("[presets.huge]\ncores = 12.0\n").unwrap_err();
616 assert!(incomplete.to_string().contains("ram_mb"), "{incomplete}");
617 }
618
619 #[test]
620 fn test_default_presets_are_quick_and_low_impact_where_named() {
621 let presets = Presets::default();
622 assert!(presets.get("quick").unwrap().is_quick());
623 assert!(presets.get("low_impact").unwrap().is_low_impact());
624 assert!(!presets.get("cpu_small").unwrap().is_quick());
625 assert!(!presets.get("cpu_small").unwrap().is_low_impact());
626 }
627
628 #[test]
629 fn test_config_partial_table_merges_over_defaults() {
630 let config = Config::from_toml(
631 "[leases]\nheartbeat_ttl_secs = 90\n\n[classes.gpu_heavy]\nvram_mb = 8192\n",
632 )
633 .unwrap();
634 let defaults = Config::default();
635 assert_eq!(config.leases.heartbeat_ttl_secs, 90);
636 assert_eq!(
637 config.leases.idle_release_secs,
638 defaults.leases.idle_release_secs
639 );
640 assert_eq!(config.classes.gpu_heavy.vram_mb, 8192);
641 assert_eq!(
642 config.classes.gpu_heavy.cores,
643 defaults.classes.gpu_heavy.cores
644 );
645 assert_eq!(config.classes.cpu_heavy, defaults.classes.cpu_heavy);
646 assert_eq!(config.daemon, defaults.daemon);
647 assert_eq!(config.classifier, defaults.classifier);
648 }
649
650 #[test]
651 fn test_config_linux_table_defaults_to_scopes_without_caps_and_merges() {
652 let defaults = LinuxConfig::default();
653 assert!(defaults.scopes);
654 assert!(!defaults.enforce_cpu);
655 assert!(!defaults.enforce_memory);
656
657 let config = Config::from_toml("[linux]\nenforce_memory = true\n").unwrap();
658 assert_eq!(
659 config.linux,
660 LinuxConfig {
661 enforce_memory: true,
662 ..defaults
663 }
664 );
665 let result = Config::from_toml("[linux]\nenforce_io = true\n");
666 assert!(matches!(result, Err(Error::ConfigParse(_))));
667 }
668
669 #[test]
670 fn test_config_integer_percentage_parses_as_float() {
671 let config = Config::from_toml("[admission]\nheadroom_pct = 20\n").unwrap();
672 assert_eq!(config.admission.headroom_pct, 20.0);
673 }
674
675 #[test]
676 fn test_config_user_rules_replace_default_rules() {
677 let config = Config::from_toml(
678 "[[classifier.rules]]\nprogram = \"python\"\nargs = [\"train.py\"]\nclass = \"gpu_heavy\"\n",
679 )
680 .unwrap();
681 assert_eq!(
682 config.classifier.rules,
683 vec![HeavyRule::new("python", &["train.py"], JobClass::GpuHeavy)]
684 );
685 }
686
687 #[test]
688 fn test_config_rule_without_args_matches_any_arguments() {
689 let config =
690 Config::from_toml("[[classifier.rules]]\nprogram = \"ninja\"\nclass = \"cpu_heavy\"\n")
691 .unwrap();
692 assert!(config.classifier.rules[0].args.is_empty());
693 }
694
695 #[test]
696 fn test_config_user_rules_keep_default_light_flags() {
697 let config =
698 Config::from_toml("[[classifier.rules]]\nprogram = \"ninja\"\nclass = \"cpu_heavy\"\n")
699 .unwrap();
700 let defaults = ClassifierConfig::default();
701 assert_eq!(config.classifier.light_flags, defaults.light_flags);
702 assert!(defaults.light_flags.contains(&"--help".to_owned()));
703 }
704
705 #[test]
706 fn test_config_blank_light_flag_is_rejected() {
707 let message = config_error("[classifier]\nlight_flags = [\"--help\", \"\"]\n");
708 assert!(message.contains("classifier.light_flags"));
709 }
710
711 #[test]
712 fn test_config_unknown_key_is_rejected() {
713 let result = Config::from_toml("[leases]\nheartbeat_tll_secs = 90\n");
714 assert!(matches!(result, Err(Error::ConfigParse(_))));
715 let result = Config::from_toml("[classes.mixed]\nvram = 1024\n");
716 assert!(matches!(result, Err(Error::ConfigParse(_))));
717 let result = Config::from_toml("[classes.huge]\ncores = 32\n");
718 assert!(matches!(result, Err(Error::ConfigParse(_))));
719 }
720
721 #[test]
722 fn test_config_wrong_type_is_rejected() {
723 let result = Config::from_toml("[daemon]\nport = \"eighty\"\n");
724 assert!(matches!(result, Err(Error::ConfigParse(_))));
725 }
726
727 #[test]
728 fn test_config_out_of_range_values_name_the_key() {
729 assert!(config_error("[daemon]\nport = 0\n").contains("daemon.port"));
730 assert!(config_error("[admission]\nheadroom_pct = 100\n").contains("headroom_pct"));
731 assert!(config_error("[benchmark]\nquiet_cpu_pct = 120\n").contains("quiet_cpu_pct"));
732 assert!(config_error("[benchmark]\nquiet_secs = 0\n").contains("quiet_secs"));
733 let short_wait = "[benchmark]\nquiet_secs = 30\nmax_quiet_wait_secs = 20\n";
734 assert!(config_error(short_wait).contains("max_quiet_wait_secs"));
735 assert!(config_error("[leases]\nheartbeat_ttl_secs = 0\n").contains("heartbeat_ttl"));
736 assert!(config_error("[classes.mixed]\ngpu_pct = 150\n").contains("classes.mixed"));
737 assert!(config_error("[retention]\nlease_days = 0\n").contains("retention.lease_days"));
738 assert!(config_error("[retention]\nhistory_days = 0\n").contains("history_days"));
739 assert!(config_error("[retention]\nkeep_runs_per_job = 0\n").contains("keep_runs"));
740 let small_cap = "[retention]\nkeep_runs_per_job = 50\nmax_job_runs = 10\n";
741 assert!(config_error(small_cap).contains("retention.max_job_runs"));
742 }
743
744 #[test]
745 fn test_config_load_invalid_file_names_the_file_and_the_key() {
746 let path =
747 env::temp_dir().join(format!("allot-shared-test-bad-{}.toml", std::process::id()));
748 fs::write(&path, "[leases]\nheartbeat_ttl_secs = 0\n").unwrap();
749 let loaded = Config::load(&path);
750 fs::remove_file(&path).unwrap();
751 let message = loaded.unwrap_err().to_string();
752 assert!(
753 message.starts_with(&path.display().to_string()),
754 "{message}"
755 );
756 assert!(message.contains("leases.heartbeat_ttl_secs"), "{message}");
757 }
758
759 #[test]
760 fn test_config_malformed_documents_fail_without_panicking() {
761 let text = toml::to_string(&Config::default()).unwrap();
762 for variant in mutations(&text, 0x5eed, 2_000) {
763 match Config::from_toml(&variant) {
764 Ok(config) => config.validate().unwrap(),
765 Err(error) => assert!(!error.to_string().is_empty()),
766 }
767 }
768 }
769
770 #[test]
771 fn test_config_wrongly_typed_value_names_its_key() {
772 let text = toml::to_string(&Config::default()).unwrap();
773 let mut checked = 0;
774 for (index, line) in text.lines().enumerate() {
775 let Some((key, _)) = line.split_once(" = ") else {
776 continue;
777 };
778 for wrong in ["\"text\"", "[1, 2]", "{ x = 1 }", "-1", "true", "1.5", "0"] {
779 let mut lines: Vec<&str> = text.lines().collect();
780 let replaced = format!("{key} = {wrong}");
781 lines[index] = &replaced;
782 if let Err(error) = Config::from_toml(&lines.join("\n")) {
784 let message = error.to_string();
785 assert!(message.contains(key.trim()), "{key} = {wrong}: {message}");
786 checked += 1;
787 }
788 }
789 }
790 assert!(checked > 50, "only {checked} rejections were checked");
791 }
792
793 #[test]
794 fn test_config_blank_rule_program_is_rejected() {
795 let message =
796 config_error("[[classifier.rules]]\nprogram = \" \"\nclass = \"cpu_heavy\"\n");
797 assert!(message.contains("classifier.rules[0]"));
798 }
799
800 #[test]
801 fn test_config_load_missing_file_yields_defaults() {
802 let path = env::temp_dir()
803 .join("allot-shared-test-missing")
804 .join("config.toml");
805 assert_eq!(Config::load(&path).unwrap(), Config::default());
806 }
807
808 #[test]
809 fn test_config_load_existing_file_parses_it() {
810 let path = env::temp_dir().join(format!("allot-shared-test-{}.toml", std::process::id()));
811 fs::write(&path, "[hook]\nfail_open = false\n").unwrap();
812 let loaded = Config::load(&path);
813 fs::remove_file(&path).unwrap();
814 assert!(!loaded.unwrap().hook.fail_open);
815 }
816}