Skip to main content

ai6_diptel/
station.rs

1//! What a Station sends to Universal Exports, each body declared once.
2//!
3//! The Station writes these and the gateway reads the same type, so a field added on one side
4//! cannot be missed on the other. Each derives guatiao's value and schema, and serde's
5//! `Serialize` and `Deserialize`, which fix the JSON spelling both sides have always used: a
6//! reader keeps ignoring keys it does not know, and an absent key reads as its default.
7//!
8//! [`CheckIn`] is the part of a Station's check-in that holds plain data. The Registry keeps the
9//! common keys alongside AI6-specific records such as Theaters and the Mission queue.
10
11use std::collections::BTreeMap;
12
13use guatiao::{FromValue, Schema, ToValue};
14use serde::{Deserialize, Serialize};
15
16/// The check-in key under which a Station publishes [`PublishedSources`].
17pub const SOURCE_FACTS_KEY: &str = "source_facts";
18
19/// What a Station publishes at check-in of one Source instance, so a gateway that loads no
20/// Source provider can name its page and intake labels. It carries no credential: no variable
21/// name and no value.
22#[non_exhaustive]
23#[derive(
24    Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, ToValue, FromValue, Schema,
25)]
26pub struct PublishedSource {
27    /// The Source provider's ID: `github`, `gitlab`, `jira`.
28    pub provider: String,
29    /// The `https` page of the repository or project, or a Jira site's root.
30    #[serde(default)]
31    pub web: Option<String>,
32    /// The project's key at the tracker, when it has one.
33    #[serde(default)]
34    pub project: Option<String>,
35    /// The labels an item needs to be taken in.
36    #[serde(default)]
37    #[map(default)]
38    pub intake_labels: Vec<String>,
39}
40
41impl PublishedSource {
42    /// A published instance of `provider` with nothing else said of it.
43    pub fn new(provider: impl Into<String>) -> Self {
44        Self {
45            provider: provider.into(),
46            ..Self::default()
47        }
48    }
49
50    /// With its page.
51    #[must_use]
52    pub fn web(mut self, web: Option<String>) -> Self {
53        self.web = web;
54        self
55    }
56
57    /// With its project's key.
58    #[must_use]
59    pub fn project(mut self, project: Option<String>) -> Self {
60        self.project = project;
61        self
62    }
63
64    /// With the labels an item needs to be taken in.
65    #[must_use]
66    pub fn intake_labels(mut self, labels: Vec<String>) -> Self {
67        self.intake_labels = labels;
68        self
69    }
70}
71
72/// An Operation's published Source instances by Operation ID, then instance name.
73pub type PublishedSources = BTreeMap<String, BTreeMap<String, PublishedSource>>;
74
75/// The plain-data keys of a Station's check-in. A key a Station leaves out reads as its
76/// default, and a key that does not read claims nothing, so an older or newer peer is
77/// understood as far as it goes.
78#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToValue, FromValue, Schema)]
79pub struct CheckIn {
80    /// The Station's host name.
81    #[serde(
82        default,
83        skip_serializing_if = "Option::is_none",
84        deserialize_with = "read_key"
85    )]
86    pub host: Option<String>,
87    /// The operating system it runs on.
88    #[serde(
89        default,
90        skip_serializing_if = "Option::is_none",
91        deserialize_with = "read_key"
92    )]
93    pub platform: Option<String>,
94    /// Its process ID.
95    #[serde(
96        default,
97        skip_serializing_if = "Option::is_none",
98        deserialize_with = "read_key"
99    )]
100    pub process_id: Option<u32>,
101    /// Its roles.
102    #[serde(default, deserialize_with = "read_key")]
103    #[map(default)]
104    pub roles: Vec<String>,
105    /// How many Missions it runs at once; 0 for a Station that runs none.
106    #[serde(default, deserialize_with = "read_key")]
107    #[map(default)]
108    pub capacity: usize,
109    /// How many Runs it has running.
110    #[serde(default, deserialize_with = "read_key")]
111    #[map(default)]
112    pub running: usize,
113    /// Its labels.
114    #[serde(default, deserialize_with = "read_key")]
115    #[map(default)]
116    pub labels: BTreeMap<String, String>,
117    /// The Operations whose checkout it has.
118    #[serde(default, deserialize_with = "read_key")]
119    #[map(default)]
120    pub operations: Vec<String>,
121    /// The AgentHandler providers it can run; absent when it did not report them.
122    #[serde(
123        default,
124        skip_serializing_if = "Option::is_none",
125        deserialize_with = "read_key"
126    )]
127    pub handlers: Option<Vec<String>>,
128    /// Every Operation it may place a Mission of, which is wider than `operations`.
129    #[serde(default, deserialize_with = "read_key")]
130    #[map(default)]
131    pub runnable_operations: Vec<String>,
132    /// Every roster Operation's ancestors, nearest first; absent when they did not fit the
133    /// check-in's budget.
134    #[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    /// The names Operations are called by.
141    #[serde(default, deserialize_with = "read_key")]
142    #[map(default)]
143    pub operation_names: BTreeMap<String, String>,
144    /// What the Source providers say of each instance; absent when it did not fit the
145    /// check-in's budget.
146    #[serde(
147        default,
148        skip_serializing_if = "Option::is_none",
149        deserialize_with = "read_key"
150    )]
151    pub source_facts: Option<PublishedSources>,
152    /// Each Operation's issue settings looser than the default, one line each.
153    #[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    /// Peer-pairing settings looser than the strict defaults, one line each.
161    #[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    /// Bootstrap settings looser than the strict defaults, one line each.
169    #[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    /// The Station's TLS policy where it is looser than the default, one line each.
177    #[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    /// Handler settings looser than the default, one line each.
185    #[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    /// What the plugin scan accepted that the strict profile refuses, one line each.
193    #[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    /// Moneypenny's settings looser than the default, one line each.
201    #[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    /// Cable relay settings looser than the default, one line each.
209    #[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    /// Sealing trust looser than the default, one line each.
217    #[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    /// The plain-data field names shared with a Registry check-in.
237    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/// The gateway's answer to a Run's registration.
264#[non_exhaustive]
265#[derive(
266    Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, ToValue, FromValue, Schema,
267)]
268pub struct RunRegistered {
269    /// The sequence number of the next event of the Run the gateway takes.
270    pub next_sequence: u64,
271    /// The most terminal output the gateway takes in one event of this Run.
272    #[serde(default)]
273    pub terminal_bytes: Option<u64>,
274}
275
276impl RunRegistered {
277    /// An answer with the next sequence and the terminal-output limit.
278    pub fn new(next_sequence: u64, terminal_bytes: Option<u64>) -> Self {
279        Self {
280            next_sequence,
281            terminal_bytes,
282        }
283    }
284}
285
286/// The state a Station reports for a Run's Mission.
287#[non_exhaustive]
288#[derive(
289    Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, ToValue, FromValue, Schema,
290)]
291pub struct LifecycleReport {
292    /// The Operation that owns the Mission.
293    pub operation_id: String,
294    /// The Mission.
295    pub mission_id: String,
296    /// The Mission's state, in the spelling of [`RunState::as_str`](crate::RunState::as_str).
297    pub state: String,
298    /// Why AI6 holds it in that state, when it says.
299    #[serde(default, skip_serializing_if = "Option::is_none")]
300    pub reason: Option<String>,
301}
302
303impl LifecycleReport {
304    /// A report of `state` for a Mission of an Operation.
305    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/// What a Station did with an operator control, reported back to the gateway.
321#[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    /// The reporting Station.
328    pub station: String,
329    /// `applied` or `rejected`.
330    pub outcome: String,
331    /// The Mission's state afterwards, when the Station has the Mission.
332    #[serde(default)]
333    pub state: Option<String>,
334    /// Why a control was rejected; AI6's own wording, never provider or Agent text.
335    #[serde(default)]
336    pub reason: Option<String>,
337}
338
339impl ControlReport {
340    /// A report from `station` of `outcome`.
341    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}