ai6_theater_container/
settings.rs1use ai6::guatiao::{FromValue, Schema, ToValue};
2
3#[derive(Debug, Clone, ToValue, FromValue, Schema)]
5#[map(crate = ::ai6::guatiao, deny_unknown_fields)]
6pub struct Settings {
7 pub image: String,
9 pub engine: Option<String>,
11 pub user: Option<String>,
13 pub command: Option<Vec<String>>,
15 #[map(default)]
17 pub run_args: Vec<String>,
18 pub engine_timeout_ms: Option<u64>,
21 pub engine_output_bytes: Option<u64>,
23}
24
25impl Settings {
26 pub fn checked(self) -> Result<Self, String> {
32 let settings = self;
33 for (name, value) in [
35 ("image", Some(&settings.image)),
36 ("engine", settings.engine.as_ref()),
37 ("user", settings.user.as_ref()),
38 ] {
39 if let Some(value) = value
40 && (value.is_empty() || value.starts_with('-') || value.contains('\0'))
41 {
42 return Err(format!(
43 "{name} must be a non-empty word not starting with '-'"
44 ));
45 }
46 }
47 if settings
48 .command
49 .as_ref()
50 .is_some_and(|command| command.is_empty())
51 || settings
52 .command
53 .iter()
54 .flatten()
55 .chain(&settings.run_args)
56 .any(|word| word.contains('\0'))
57 {
58 return Err("command must name a program, and no argument may hold a NUL".to_owned());
59 }
60 Ok(settings)
61 }
62
63 pub(crate) fn engine_timeout_ms(&self) -> u64 {
64 self.engine_timeout_ms.unwrap_or(600_000)
65 }
66
67 pub(crate) fn engine_output_bytes(&self) -> u64 {
68 self.engine_output_bytes.unwrap_or(1024 * 1024)
69 }
70
71 pub(crate) fn engine(&self) -> String {
72 self.engine.clone().unwrap_or_else(|| "docker".to_owned())
73 }
74
75 pub(crate) fn command(&self) -> Vec<String> {
76 self.command
77 .clone()
78 .unwrap_or_else(|| vec!["sleep".to_owned(), "infinity".to_owned()])
79 }
80}
81
82#[cfg(test)]
83impl Settings {
84 pub(crate) fn parse(text: &str) -> Result<Self, String> {
85 ai6::provider_settings::settings_from_text::<Self>(
86 ai6::bootstrap::format::Format::Toml,
87 text,
88 )?
89 .checked()
90 }
91}
92
93#[cfg(test)]
94mod tests {
95 use super::*;
96
97 #[test]
98 fn defaults_and_validation() {
99 let settings = Settings::parse("image = \"fedora:44\"\n").unwrap();
100 assert_eq!(settings.engine(), "docker");
101 assert_eq!(settings.command(), ["sleep", "infinity"]);
102 for bad in [
103 "",
104 "image = \"\"\n",
105 "image = \"-v\"\n",
106 "image = \"i\"\ncommand = []\n",
107 "image = \"i\"\nengine = \"-x\"\n",
108 "image = \"i\"\nunknown = 1\n",
109 ] {
110 assert!(Settings::parse(bad).is_err(), "{bad}");
111 }
112 }
113
114 #[test]
115 fn the_engine_bounds_are_settings_with_defaults() {
116 let settings = Settings::parse("image = \"i\"\n").unwrap();
117 assert_eq!(settings.engine_timeout_ms(), 600_000);
118 assert_eq!(settings.engine_output_bytes(), 1024 * 1024);
119 let settings =
120 Settings::parse("image = \"i\"\nengine_timeout_ms = 5\nengine_output_bytes = 7\n")
121 .unwrap();
122 assert_eq!(settings.engine_timeout_ms(), 5);
123 assert_eq!(settings.engine_output_bytes(), 7);
124 }
125}