Skip to main content

bern_protocol/
compose.rs

1//! One catalog from an application's shell protocol and its modules.
2//!
3//! Each module keeps its own namespace, so its command ids stay
4//! `module.command` and its state fields join the application state as
5//! `module.field`. Every field diffuses independently instead of packing an
6//! entire module into a single record. Type names are unique across the
7//! application: two different definitions with one name are an error.
8//!
9//! The build tool composes the descriptors it reads from source and the
10//! running engine composes the ones the protocol macros generated, with
11//! this same function, so both sides arrive at the same fingerprint.
12
13use crate::{
14    CommandPolicy, CommandSpec, DescriptorError, ExternalNames, MODULES_NAMESPACE, OperationKind,
15    ParamSpec, ProtocolDescriptor, Retry, Scope, StateField, Type, valid_name,
16};
17
18/// One module of an application: its catalog, and whether it can be
19/// switched off at run time.
20#[derive(Clone, Copy, Debug)]
21pub struct ModulePart<'a> {
22    pub descriptor: &'a ProtocolDescriptor,
23    pub optional: bool,
24}
25
26/// Record type of the `modules` state field: one `bool` per optional
27/// module, true while the module runs.
28pub const MODULES_STATE_TYPE: &str = "Modules";
29
30/// Name of the command switching an optional module: `modules.set_enabled`.
31pub const SET_ENABLED: &str = "set_enabled";
32
33/// Name of the record holding a module's state: `downloads` gives
34/// `DownloadsState`, `network_sources` gives `NetworkSourcesState`.
35pub fn module_state_type(namespace: &str) -> String {
36    let mut name = String::new();
37    for word in namespace.split('_') {
38        let mut chars = word.chars();
39        if let Some(first) = chars.next() {
40            name.extend(first.to_uppercase());
41            name.push_str(chars.as_str());
42        }
43    }
44    name.push_str("State");
45    name
46}
47
48/// The application catalog: the shell's state and commands first, then
49/// each module in order. Module query reads name the module's own fields;
50/// in the application they read the module's state field as a whole.
51///
52/// With optional modules the catalog ends with the `modules` state field,
53/// whose record holds a `bool` per optional module, and the command
54/// `modules.set_enabled(id, enabled)`, which returns the ids of the modules
55/// it switched, dependencies included.
56pub fn compose(
57    shell: &ProtocolDescriptor,
58    parts: &[ModulePart<'_>],
59) -> Result<ProtocolDescriptor, DescriptorError> {
60    let modules: Vec<&ProtocolDescriptor> = parts.iter().map(|part| part.descriptor).collect();
61    let mut composed = shell.clone();
62    // In the application every event is named `namespace.event`.
63    let qualify = |namespace: &str, events: &[crate::EventSpec]| {
64        events
65            .iter()
66            .map(|event| crate::EventSpec {
67                name: format!("{namespace}.{}", event.name),
68                ..event.clone()
69            })
70            .collect::<Vec<_>>()
71    };
72    composed.events = qualify(&shell.namespace, &shell.events);
73    for module in &modules {
74        let namespace = &module.namespace;
75        if !valid_name(namespace) {
76            return Err(DescriptorError(format!(
77                "invalid module namespace `{namespace}`; use lower snake case"
78            )));
79        }
80        if namespace == &shell.namespace
81            || modules
82                .iter()
83                .filter(|other| &other.namespace == namespace)
84                .count()
85                > 1
86        {
87            return Err(DescriptorError(format!(
88                "namespace `{namespace}` is used by more than one protocol"
89            )));
90        }
91        if composed.state_index(namespace).is_some() {
92            return Err(DescriptorError(format!(
93                "state field `{namespace}` of `{}` has the name of a module",
94                shell.namespace
95            )));
96        }
97        composed
98            .types
99            .merge(&module.types)
100            .map_err(|error| DescriptorError(format!("module `{namespace}`: {}", error.message)))?;
101        if !module.modules.is_empty() {
102            return Err(DescriptorError(format!(
103                "module `{namespace}` is itself composed; modules do not nest"
104            )));
105        }
106        for field in &module.state {
107            composed.state.push(StateField {
108                name: format!("{namespace}.{}", field.name),
109                ty: field.ty.clone(),
110                doc: field.doc.clone(),
111                content: field.content,
112                stream: field.stream,
113                keyed: field.keyed.clone(),
114            });
115        }
116        composed.modules.push(namespace.clone());
117        composed.events.extend(qualify(namespace, &module.events));
118        for command in &module.commands {
119            let mut command = command.clone();
120            if !command.reads.is_empty() {
121                command.reads = command
122                    .reads
123                    .iter()
124                    .map(|field| format!("{namespace}.{field}"))
125                    .collect();
126            }
127            composed.commands.push(command);
128        }
129    }
130    // A command answering an event takes exactly the event's parameters.
131    for command in &composed.commands {
132        let Some(on) = &command.on else {
133            continue;
134        };
135        let Some(event) = composed.events.iter().find(|event| &event.name == on) else {
136            return Err(DescriptorError(format!(
137                "command `{}` answers `{on}`, which no protocol of the application emits",
138                command.id
139            )));
140        };
141        let wanted: Vec<_> = event.params.iter().map(|p| (&p.name, &p.ty)).collect();
142        let given: Vec<_> = command.params.iter().map(|p| (&p.name, &p.ty)).collect();
143        if wanted != given {
144            return Err(DescriptorError(format!(
145                "command `{}` answers `{on}`, so it takes the event's parameters ({})",
146                command.id,
147                event
148                    .params
149                    .iter()
150                    .map(|param| format!("{}: {}", param.name, param.ty.display()))
151                    .collect::<Vec<_>>()
152                    .join(", ")
153            )));
154        }
155    }
156    let optional: Vec<&str> = parts
157        .iter()
158        .filter(|part| part.optional)
159        .map(|part| part.descriptor.namespace.as_str())
160        .collect();
161    if !optional.is_empty() {
162        if composed.state_index(MODULES_NAMESPACE).is_some()
163            || composed.types.record_def(MODULES_STATE_TYPE).is_some()
164            || composed.types.enum_def(MODULES_STATE_TYPE).is_some()
165        {
166            return Err(DescriptorError(format!(
167                "the application declares `{MODULES_NAMESPACE}` or `{MODULES_STATE_TYPE}`, which optional modules use"
168            )));
169        }
170        for namespace in &optional {
171            composed.state.push(StateField {
172                name: format!("{MODULES_NAMESPACE}.{namespace}"),
173                ty: Type::Bool,
174                doc: format!("Whether the `{namespace}` module runs."),
175                content: false,
176                stream: false,
177                keyed: None,
178            });
179        }
180        composed.commands.push(CommandSpec {
181            id: format!("{MODULES_NAMESPACE}.{SET_ENABLED}"),
182            name: SET_ENABLED.into(),
183            doc: "Switch an optional module on or off. Switching one on switches on the modules it depends on; switching one off switches off the modules depending on it. Returns the ids of every module switched.".into(),
184            kind: OperationKind::Command,
185            scope: Scope::Engine,
186            params: vec![
187                ParamSpec {
188                    name: "id".into(),
189                    ty: Type::Text,
190                    doc: "Module id".into(),
191                },
192                ParamSpec {
193                    name: "enabled".into(),
194                    ty: Type::Bool,
195                    doc: "Whether the module runs".into(),
196                },
197            ],
198            result: Type::list(Type::Text),
199            errors: vec!["unknown_module".into(), "not_optional".into()],
200            policy: CommandPolicy {
201                retry: Retry::Idempotent,
202                ..CommandPolicy::default()
203            },
204            external: ExternalNames::derive(MODULES_NAMESPACE, SET_ENABLED),
205            reads: vec![],
206            on: None,
207        });
208    }
209    composed
210        .validate()
211        .map_err(|error| DescriptorError(format!("the application catalog is invalid: {error}")))?;
212    Ok(composed)
213}
214
215/// Where each part's commands start in the composed catalog: the shell at
216/// 0, then every module in order. `modules.set_enabled`, if any, follows.
217pub fn command_offsets(shell: &ProtocolDescriptor, parts: &[ModulePart<'_>]) -> Vec<usize> {
218    let mut offsets = vec![0];
219    let mut next = shell.commands.len();
220    for part in parts {
221        offsets.push(next);
222        next += part.descriptor.commands.len();
223    }
224    offsets
225}
226
227/// Where each part's state fields start in the composed catalog: the shell
228/// at 0, then every module in order. Optional module switches follow.
229pub fn state_offsets(shell: &ProtocolDescriptor, parts: &[ModulePart<'_>]) -> Vec<usize> {
230    let mut offsets = vec![0];
231    let mut next = shell.state.len();
232    for part in parts {
233        offsets.push(next);
234        next += part.descriptor.state.len();
235    }
236    offsets
237}
238
239#[cfg(test)]
240mod tests {
241    use super::*;
242    use crate::{
243        CommandPolicy, CommandSpec, DESCRIPTOR_VERSION, ExternalNames, FieldDef, OperationKind,
244        RecordDef, Scope, TypeTable,
245    };
246
247    fn command(namespace: &str, name: &str) -> CommandSpec {
248        CommandSpec {
249            id: format!("{namespace}.{name}"),
250            name: name.into(),
251            doc: String::new(),
252            kind: OperationKind::Command,
253            scope: Scope::Engine,
254            params: vec![],
255            result: Type::Unit,
256            errors: vec![],
257            policy: CommandPolicy::default(),
258            external: ExternalNames::derive(namespace, name),
259            reads: vec![],
260            on: None,
261        }
262    }
263
264    fn part(descriptor: &ProtocolDescriptor) -> ModulePart<'_> {
265        ModulePart {
266            descriptor,
267            optional: false,
268        }
269    }
270
271    fn protocol(namespace: &str, fields: &[&str], commands: &[&str]) -> ProtocolDescriptor {
272        ProtocolDescriptor {
273            descriptor_version: DESCRIPTOR_VERSION,
274            namespace: namespace.into(),
275            version: 1,
276            types: TypeTable::default(),
277            state: fields
278                .iter()
279                .map(|name| StateField {
280                    name: (*name).into(),
281                    ty: Type::Int,
282                    doc: String::new(),
283                    content: false,
284                    stream: false,
285                    keyed: None,
286                })
287                .collect(),
288            commands: commands
289                .iter()
290                .map(|name| command(namespace, name))
291                .collect(),
292            modules: Vec::new(),
293            events: Vec::new(),
294        }
295    }
296
297    #[test]
298    fn modules_flatten_their_state_fields_and_keep_their_command_ids() {
299        let shell = protocol("app", &["count"], &["reset"]);
300        let downloads = protocol("downloads", &["active", "done"], &["add", "remove"]);
301        let library = protocol("network_library", &["items"], &["add"]);
302        let composed = compose(&shell, &[part(&downloads), part(&library)]).unwrap();
303        let names: Vec<_> = composed.state.iter().map(|f| f.name.as_str()).collect();
304        assert_eq!(
305            names,
306            [
307                "count",
308                "downloads.active",
309                "downloads.done",
310                "network_library.items"
311            ]
312        );
313        assert_eq!(composed.state[1].ty, Type::Int);
314        let ids: Vec<_> = composed.commands.iter().map(|c| c.id.as_str()).collect();
315        assert_eq!(
316            ids,
317            [
318                "app.reset",
319                "downloads.add",
320                "downloads.remove",
321                "network_library.add"
322            ]
323        );
324        assert_eq!(
325            command_offsets(&shell, &[part(&downloads), part(&library)]),
326            [0, 1, 3]
327        );
328        assert_eq!(
329            state_offsets(&shell, &[part(&downloads), part(&library)]),
330            [0, 1, 3]
331        );
332    }
333
334    #[test]
335    fn query_reads_name_the_exact_module_field() {
336        let shell = protocol("app", &[], &[]);
337        let mut downloads = protocol("downloads", &["active", "done"], &[]);
338        let mut search = command("downloads", "search");
339        search.kind = OperationKind::Query;
340        search.reads = vec!["active".into()];
341        downloads.commands.push(search);
342        let composed = compose(&shell, &[part(&downloads)]).unwrap();
343        assert_eq!(composed.commands[0].reads, ["downloads.active"]);
344    }
345
346    #[test]
347    fn clashing_namespaces_fields_and_types_fail() {
348        let shell = protocol("app", &["downloads"], &[]);
349        let downloads = protocol("downloads", &[], &[]);
350        assert!(compose(&shell, &[part(&downloads)]).is_err());
351        let shell = protocol("app", &[], &[]);
352        assert!(compose(&shell, &[part(&downloads), part(&downloads)]).is_err());
353        assert!(compose(&shell, &[part(&protocol("app", &[], &[]))]).is_err());
354
355        let mut a = protocol("a", &[], &[]);
356        a.types.records.push(RecordDef {
357            name: "Item".into(),
358            fields: vec![],
359        });
360        let mut b = protocol("b", &[], &[]);
361        b.types.records.push(RecordDef {
362            name: "Item".into(),
363            fields: vec![FieldDef {
364                name: "id".into(),
365                ty: Type::Int,
366                doc: String::new(),
367                content: false,
368            }],
369        });
370        assert!(compose(&shell, &[part(&a), part(&b)]).is_err());
371    }
372
373    #[test]
374    fn optional_modules_add_their_switch() {
375        let shell = protocol("app", &[], &["reset"]);
376        let notes = protocol("notes", &["count"], &["add"]);
377        let tags = protocol("tags", &[], &[]);
378        let composed = compose(
379            &shell,
380            &[
381                part(&notes),
382                ModulePart {
383                    descriptor: &tags,
384                    optional: true,
385                },
386            ],
387        )
388        .unwrap();
389        let fields: Vec<_> = composed.state.iter().map(|f| f.name.as_str()).collect();
390        assert_eq!(fields, ["notes.count", "modules.tags"]);
391        assert_eq!(composed.state[1].ty, Type::Bool);
392        let last = composed.commands.last().unwrap();
393        assert_eq!(last.id, "modules.set_enabled");
394        assert_eq!(last.external.cli, ["modules", "set-enabled"]);
395        // Without optional modules nothing is added.
396        let plain = compose(&shell, &[part(&notes)]).unwrap();
397        assert!(plain.state.iter().all(|f| !f.name.starts_with("modules.")));
398    }
399
400    #[test]
401    fn answers_take_the_event_parameters() {
402        let shell = protocol("app", &[], &[]);
403        let mut notes = protocol("notes", &[], &["add"]);
404        let param = |name: &str| crate::ParamSpec {
405            name: name.into(),
406            ty: Type::Int,
407            doc: String::new(),
408        };
409        notes.events.push(crate::EventSpec {
410            name: "added".into(),
411            doc: String::new(),
412            params: vec![param("id")],
413        });
414        let mut tags = protocol("tags", &[], &["label"]);
415        tags.commands[0].on = Some("notes.added".into());
416        tags.commands[0].params = vec![param("id")];
417        let composed = compose(&shell, &[part(&notes), part(&tags)]).unwrap();
418        assert_eq!(composed.events[0].name, "notes.added");
419        // Other parameters, or an event nobody emits, are refused.
420        tags.commands[0].params = vec![param("note")];
421        assert!(compose(&shell, &[part(&notes), part(&tags)]).is_err());
422        tags.commands[0].params = vec![param("id")];
423        tags.commands[0].on = Some("notes.removed".into());
424        assert!(compose(&shell, &[part(&notes), part(&tags)]).is_err());
425    }
426
427    #[test]
428    fn state_type_names_are_upper_camel() {
429        assert_eq!(module_state_type("downloads"), "DownloadsState");
430        assert_eq!(module_state_type("network_sources"), "NetworkSourcesState");
431    }
432}