1use std::collections::BTreeMap;
12
13use guatiao::{FromValue, Schema, ToValue};
14use serde::{Deserialize, Serialize};
15
16pub const SOURCE_FACTS_KEY: &str = "source_facts";
18
19#[non_exhaustive]
23#[derive(
24 Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, ToValue, FromValue, Schema,
25)]
26pub struct PublishedSource {
27 pub provider: String,
29 #[serde(default)]
31 pub web: Option<String>,
32 #[serde(default)]
34 pub project: Option<String>,
35 #[serde(default)]
37 #[map(default)]
38 pub intake_labels: Vec<String>,
39}
40
41impl PublishedSource {
42 pub fn new(provider: impl Into<String>) -> Self {
44 Self {
45 provider: provider.into(),
46 ..Self::default()
47 }
48 }
49
50 #[must_use]
52 pub fn web(mut self, web: Option<String>) -> Self {
53 self.web = web;
54 self
55 }
56
57 #[must_use]
59 pub fn project(mut self, project: Option<String>) -> Self {
60 self.project = project;
61 self
62 }
63
64 #[must_use]
66 pub fn intake_labels(mut self, labels: Vec<String>) -> Self {
67 self.intake_labels = labels;
68 self
69 }
70}
71
72pub type PublishedSources = BTreeMap<String, BTreeMap<String, PublishedSource>>;
74
75#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToValue, FromValue, Schema)]
79pub struct CheckIn {
80 #[serde(
82 default,
83 skip_serializing_if = "Option::is_none",
84 deserialize_with = "read_key"
85 )]
86 pub host: Option<String>,
87 #[serde(
89 default,
90 skip_serializing_if = "Option::is_none",
91 deserialize_with = "read_key"
92 )]
93 pub platform: Option<String>,
94 #[serde(
96 default,
97 skip_serializing_if = "Option::is_none",
98 deserialize_with = "read_key"
99 )]
100 pub process_id: Option<u32>,
101 #[serde(default, deserialize_with = "read_key")]
103 #[map(default)]
104 pub roles: Vec<String>,
105 #[serde(default, deserialize_with = "read_key")]
107 #[map(default)]
108 pub capacity: usize,
109 #[serde(default, deserialize_with = "read_key")]
111 #[map(default)]
112 pub running: usize,
113 #[serde(default, deserialize_with = "read_key")]
115 #[map(default)]
116 pub labels: BTreeMap<String, String>,
117 #[serde(default, deserialize_with = "read_key")]
119 #[map(default)]
120 pub operations: Vec<String>,
121 #[serde(
123 default,
124 skip_serializing_if = "Option::is_none",
125 deserialize_with = "read_key"
126 )]
127 pub handlers: Option<Vec<String>>,
128 #[serde(default, deserialize_with = "read_key")]
130 #[map(default)]
131 pub runnable_operations: Vec<String>,
132 #[serde(
135 default,
136 skip_serializing_if = "Option::is_none",
137 deserialize_with = "read_key"
138 )]
139 pub operation_lineage: Option<BTreeMap<String, Vec<String>>>,
140 #[serde(default, deserialize_with = "read_key")]
142 #[map(default)]
143 pub operation_names: BTreeMap<String, String>,
144 #[serde(
147 default,
148 skip_serializing_if = "Option::is_none",
149 deserialize_with = "read_key"
150 )]
151 pub source_facts: Option<PublishedSources>,
152 #[serde(
154 default,
155 skip_serializing_if = "Vec::is_empty",
156 deserialize_with = "read_key"
157 )]
158 #[map(default, skip_serializing_if = Vec::is_empty)]
159 pub issues_weakened: Vec<String>,
160 #[serde(
162 default,
163 skip_serializing_if = "Vec::is_empty",
164 deserialize_with = "read_key"
165 )]
166 #[map(default, skip_serializing_if = Vec::is_empty)]
167 pub peers_weakened: Vec<String>,
168 #[serde(
170 default,
171 skip_serializing_if = "Vec::is_empty",
172 deserialize_with = "read_key"
173 )]
174 #[map(default, skip_serializing_if = Vec::is_empty)]
175 pub bootstrap_weakened: Vec<String>,
176 #[serde(
178 default,
179 skip_serializing_if = "Vec::is_empty",
180 deserialize_with = "read_key"
181 )]
182 #[map(default, skip_serializing_if = Vec::is_empty)]
183 pub tls_weakened: Vec<String>,
184 #[serde(
186 default,
187 skip_serializing_if = "Vec::is_empty",
188 deserialize_with = "read_key"
189 )]
190 #[map(default, skip_serializing_if = Vec::is_empty)]
191 pub agents_weakened: Vec<String>,
192 #[serde(
194 default,
195 skip_serializing_if = "Vec::is_empty",
196 deserialize_with = "read_key"
197 )]
198 #[map(default, skip_serializing_if = Vec::is_empty)]
199 pub plugins_weakened: Vec<String>,
200 #[serde(
202 default,
203 skip_serializing_if = "Vec::is_empty",
204 deserialize_with = "read_key"
205 )]
206 #[map(default, skip_serializing_if = Vec::is_empty)]
207 pub assistant_weakened: Vec<String>,
208 #[serde(
210 default,
211 skip_serializing_if = "Vec::is_empty",
212 deserialize_with = "read_key"
213 )]
214 #[map(default, skip_serializing_if = Vec::is_empty)]
215 pub cables_weakened: Vec<String>,
216 #[serde(
218 default,
219 skip_serializing_if = "Vec::is_empty",
220 deserialize_with = "read_key"
221 )]
222 #[map(default, skip_serializing_if = Vec::is_empty)]
223 pub secrets_weakened: Vec<String>,
224}
225
226fn read_key<'de, D, T>(deserializer: D) -> Result<T, D::Error>
227where
228 D: serde::Deserializer<'de>,
229 T: serde::de::DeserializeOwned + Default,
230{
231 let value = serde_json::Value::deserialize(deserializer)?;
232 Ok(T::deserialize(value).unwrap_or_default())
233}
234
235impl CheckIn {
236 pub const KEYS: &'static [&'static str] = &[
238 "host",
239 "platform",
240 "process_id",
241 "roles",
242 "capacity",
243 "running",
244 "labels",
245 "operations",
246 "handlers",
247 "runnable_operations",
248 "operation_lineage",
249 "operation_names",
250 "source_facts",
251 "issues_weakened",
252 "peers_weakened",
253 "bootstrap_weakened",
254 "tls_weakened",
255 "agents_weakened",
256 "plugins_weakened",
257 "assistant_weakened",
258 "cables_weakened",
259 "secrets_weakened",
260 ];
261}
262
263#[non_exhaustive]
265#[derive(
266 Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, ToValue, FromValue, Schema,
267)]
268pub struct RunRegistered {
269 pub next_sequence: u64,
271 #[serde(default)]
273 pub terminal_bytes: Option<u64>,
274}
275
276impl RunRegistered {
277 pub fn new(next_sequence: u64, terminal_bytes: Option<u64>) -> Self {
279 Self {
280 next_sequence,
281 terminal_bytes,
282 }
283 }
284}
285
286#[non_exhaustive]
288#[derive(
289 Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, ToValue, FromValue, Schema,
290)]
291pub struct LifecycleReport {
292 pub operation_id: String,
294 pub mission_id: String,
296 pub state: String,
298 #[serde(default, skip_serializing_if = "Option::is_none")]
300 pub reason: Option<String>,
301}
302
303impl LifecycleReport {
304 pub fn new(
306 operation_id: impl Into<String>,
307 mission_id: impl Into<String>,
308 state: impl Into<String>,
309 reason: Option<String>,
310 ) -> Self {
311 Self {
312 operation_id: operation_id.into(),
313 mission_id: mission_id.into(),
314 state: state.into(),
315 reason,
316 }
317 }
318}
319
320#[non_exhaustive]
322#[derive(
323 Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, ToValue, FromValue, Schema,
324)]
325#[serde(deny_unknown_fields)]
326pub struct ControlReport {
327 pub station: String,
329 pub outcome: String,
331 #[serde(default)]
333 pub state: Option<String>,
334 #[serde(default)]
336 pub reason: Option<String>,
337}
338
339impl ControlReport {
340 pub fn new(
342 station: impl Into<String>,
343 outcome: impl Into<String>,
344 state: Option<String>,
345 reason: Option<String>,
346 ) -> Self {
347 Self {
348 station: station.into(),
349 outcome: outcome.into(),
350 state,
351 reason,
352 }
353 }
354}
355
356#[cfg(test)]
357mod tests {
358 use super::*;
359
360 fn json<T: Serialize>(value: &T) -> String {
361 serde_json::to_string(value).unwrap()
362 }
363
364 #[test]
365 fn a_check_in_keeps_the_wire_older_peers_read() {
366 let check_in = CheckIn {
367 host: Some("h".to_owned()),
368 platform: Some("linux".to_owned()),
369 process_id: Some(7),
370 roles: vec!["execution".to_owned()],
371 capacity: 2,
372 running: 1,
373 labels: BTreeMap::from([("site".to_owned(), "a".to_owned())]),
374 operations: vec!["G".to_owned()],
375 handlers: None,
376 runnable_operations: vec!["G".to_owned()],
377 operation_lineage: Some(BTreeMap::from([("G".to_owned(), Vec::new())])),
378 operation_names: BTreeMap::from([("G".to_owned(), "guatiao".to_owned())]),
379 source_facts: None,
380 peers_weakened: vec!["line".to_owned()],
381 ..CheckIn::default()
382 };
383 assert_eq!(
384 json(&check_in),
385 concat!(
386 r#"{"host":"h","platform":"linux","process_id":7,"roles":["execution"],"#,
387 r#""capacity":2,"running":1,"labels":{"site":"a"},"operations":["G"],"#,
388 r#""runnable_operations":["G"],"#,
389 r#""operation_lineage":{"G":[]},"operation_names":{"G":"guatiao"},"#,
390 r#""peers_weakened":["line"]}"#
391 )
392 );
393 }
394
395 #[test]
396 fn a_check_in_reads_what_it_wrote_and_a_key_that_does_not_read_claims_nothing() {
397 let mut info = serde_json::to_value(CheckIn {
398 roles: vec!["head".to_owned()],
399 capacity: 3,
400 ..CheckIn::default()
401 })
402 .unwrap();
403 info["running"] = serde_json::json!("many");
404 info["labels"] = serde_json::json!(["not", "a", "map"]);
405 info["theaters"] = serde_json::json!([{"id": "local"}]);
406 let read: CheckIn = serde_json::from_value(info).unwrap();
407 assert_eq!(read.roles, ["head"]);
408 assert_eq!(read.capacity, 3);
409 assert_eq!(read.running, 0);
410 assert!(read.labels.is_empty());
411 }
412
413 #[test]
414 fn a_check_in_is_one_value_and_one_schema() {
415 let value = CheckIn {
416 capacity: 4,
417 ..CheckIn::default()
418 };
419 let tree = guatiao::ToValue::to_value_in(&value, guatiao::Alloc::rust()).unwrap();
420 assert_eq!(<CheckIn as FromValue>::from_value(&tree).unwrap(), value);
421 let schema = CheckIn::schema().unwrap();
422 let schema = <&guatiao::Map>::try_from(&schema).unwrap();
423 let properties = <&guatiao::Map>::try_from(schema.get("properties").unwrap()).unwrap();
424 assert!(properties.get("runnable_operations").is_some());
425 assert!(properties.get("source_facts").is_some());
426 }
427
428 #[test]
429 fn a_published_source_keeps_its_wire() {
430 let source = PublishedSource::new("github")
431 .web(Some("https://github.example/o/r".to_owned()))
432 .intake_labels(vec!["ai6:go".to_owned()]);
433 assert_eq!(
434 json(&source),
435 r#"{"provider":"github","web":"https://github.example/o/r","project":null,"intake_labels":["ai6:go"]}"#
436 );
437 let older: PublishedSource = serde_json::from_str(r#"{"provider":"jira"}"#).unwrap();
438 assert_eq!(older, PublishedSource::new("jira"));
439 }
440
441 #[test]
442 fn the_reports_keep_the_wire_older_peers_read() {
443 assert_eq!(
444 json(&LifecycleReport::new("op", "m", "working", None)),
445 r#"{"operation_id":"op","mission_id":"m","state":"working"}"#
446 );
447 assert_eq!(
448 json(&LifecycleReport::new(
449 "op",
450 "m",
451 "parked",
452 Some("budget".into())
453 )),
454 r#"{"operation_id":"op","mission_id":"m","state":"parked","reason":"budget"}"#
455 );
456 assert_eq!(
457 json(&ControlReport::new(
458 "s",
459 "rejected",
460 None,
461 Some("no".into())
462 )),
463 r#"{"station":"s","outcome":"rejected","state":null,"reason":"no"}"#
464 );
465 assert_eq!(
466 json(&RunRegistered::new(3, Some(65_536))),
467 r#"{"next_sequence":3,"terminal_bytes":65536}"#
468 );
469 let older: RunRegistered = serde_json::from_str(r#"{"next_sequence":1}"#).unwrap();
470 assert_eq!(older.terminal_bytes, None);
471 assert!(
472 serde_json::from_str::<ControlReport>(r#"{"station":"s","outcome":"applied","x":1}"#)
473 .is_err()
474 );
475 }
476}