Skip to main content

bern_protocol/
descriptor.rs

1use crate::{DESCRIPTOR_VERSION, SchemaError, Type, TypeTable, fingerprint_bytes};
2use serde::{Deserialize, Serialize};
3use std::collections::BTreeMap;
4use std::fmt;
5
6/// Whether a command changes engine state or acts on one UI session.
7#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
8#[serde(rename_all = "snake_case")]
9pub enum Scope {
10    Engine,
11    Session,
12}
13
14/// Commands perform actions; queries only read and never change state.
15#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
16#[serde(rename_all = "snake_case")]
17pub enum OperationKind {
18    #[default]
19    Command,
20    Query,
21}
22
23#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
24#[serde(rename_all = "snake_case")]
25pub enum Concurrency {
26    /// Requests run one after another in arrival order.
27    Serial,
28    /// Requests start in arrival order, after the commands queued before
29    /// them, but answer independently and possibly out of order. Queries
30    /// whose providers answer asynchronously use it.
31    Overlapping,
32}
33
34#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
35#[serde(rename_all = "snake_case")]
36pub enum Retry {
37    /// Resending after an unknown outcome may repeat side effects.
38    Never,
39    /// Repeating the same request leaves the same final state.
40    Idempotent,
41}
42
43#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
44pub struct CommandPolicy {
45    pub concurrency: Concurrency,
46    pub retry: Retry,
47    pub cancellable: bool,
48}
49
50impl Default for CommandPolicy {
51    fn default() -> Self {
52        Self {
53            concurrency: Concurrency::Serial,
54            retry: Retry::Never,
55            cancellable: false,
56        }
57    }
58}
59
60/// Explicit, collision-checked names for entries other than the UI.
61#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
62pub struct ExternalNames {
63    /// Sub-command words, for example `["player", "seek"]`.
64    pub cli: Vec<String>,
65    /// MCP tool name, for example `player_seek`.
66    pub mcp: String,
67}
68
69impl ExternalNames {
70    pub fn derive(namespace: &str, name: &str) -> Self {
71        Self {
72            cli: vec![namespace.replace('_', "-"), name.replace('_', "-")],
73            mcp: format!("{namespace}_{name}"),
74        }
75    }
76}
77
78#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
79pub struct ParamSpec {
80    pub name: String,
81    #[serde(rename = "type")]
82    pub ty: Type,
83    #[serde(default, skip_serializing_if = "String::is_empty")]
84    pub doc: String,
85}
86
87#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
88pub struct CommandSpec {
89    /// Stable identifier, `namespace.name`.
90    pub id: String,
91    pub name: String,
92    #[serde(default, skip_serializing_if = "String::is_empty")]
93    pub doc: String,
94    #[serde(default)]
95    pub kind: OperationKind,
96    pub scope: Scope,
97    pub params: Vec<ParamSpec>,
98    pub result: Type,
99    /// Error codes the handler may return besides the generic ones.
100    #[serde(default, skip_serializing_if = "Vec::is_empty")]
101    pub errors: Vec<String>,
102    pub policy: CommandPolicy,
103    pub external: ExternalNames,
104    /// State fields a query reads. A query's answer is stale once one of
105    /// them changes, so live subscriptions request it again.
106    #[serde(default, skip_serializing_if = "Vec::is_empty")]
107    pub reads: Vec<String>,
108    /// For a command answering another module's event: the event, as
109    /// `module.event`. It runs after each command emitting that event.
110    #[serde(default, skip_serializing_if = "Option::is_none")]
111    pub on: Option<String>,
112}
113
114/// Something a module reports so the modules depending on it can react,
115/// such as `playback.opened`.
116#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
117pub struct EventSpec {
118    pub name: String,
119    #[serde(default, skip_serializing_if = "String::is_empty")]
120    pub doc: String,
121    pub params: Vec<ParamSpec>,
122}
123
124impl CommandSpec {
125    pub fn is_query(&self) -> bool {
126        self.kind == OperationKind::Query
127    }
128}
129
130#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
131pub struct StateField {
132    pub name: String,
133    #[serde(rename = "type")]
134    pub ty: Type,
135    #[serde(default, skip_serializing_if = "String::is_empty")]
136    pub doc: String,
137    /// `#[content]`: text that is data, shown as it is (see
138    /// [`crate::FieldDef::content`]).
139    #[serde(default, skip_serializing_if = "is_false")]
140    pub content: bool,
141    /// `#[stream]`: a high-frequency field read even when `Engine::quiet()`
142    /// holds on a wake, so the rest of a large state need not be snapshotted.
143    #[serde(default, skip_serializing_if = "is_false")]
144    pub stream: bool,
145    /// `#[keyed(field)]`: record key field for incremental list updates.
146    #[serde(default, skip_serializing_if = "Option::is_none")]
147    pub keyed: Option<String>,
148}
149
150fn is_false(value: &bool) -> bool {
151    !*value
152}
153
154/// The complete, versioned description of one application protocol:
155/// its types, read-only state snapshot and command catalog.
156#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
157pub struct ProtocolDescriptor {
158    pub descriptor_version: u32,
159    pub namespace: String,
160    /// Catalog version chosen by the application.
161    pub version: u32,
162    pub types: TypeTable,
163    pub state: Vec<StateField>,
164    pub commands: Vec<CommandSpec>,
165    /// Events this protocol emits, in declaration order.
166    #[serde(default, skip_serializing_if = "Vec::is_empty")]
167    pub events: Vec<EventSpec>,
168    /// Namespaces of the modules composed into this catalog, in order.
169    /// Their commands keep their own namespace in their ids, and each
170    /// module's state is the state field of the same name.
171    #[serde(default, skip_serializing_if = "Vec::is_empty")]
172    pub modules: Vec<String>,
173}
174
175#[derive(Clone, Debug, PartialEq, Eq)]
176pub struct DescriptorError(pub String);
177
178impl fmt::Display for DescriptorError {
179    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
180        f.write_str(&self.0)
181    }
182}
183
184impl std::error::Error for DescriptorError {}
185
186impl From<SchemaError> for DescriptorError {
187    fn from(error: SchemaError) -> Self {
188        DescriptorError(error.message)
189    }
190}
191
192/// Namespaces used by framework-provided session, window and media commands.
193pub const RESERVED_NAMESPACES: &[&str] = &["bern", "ui", "window", "session", "media", "modules"];
194
195/// Namespace of the commands switching optional modules on and off.
196pub const MODULES_NAMESPACE: &str = "modules";
197
198pub fn valid_name(name: &str) -> bool {
199    name.starts_with(|c: char| c.is_ascii_lowercase())
200        && name
201            .chars()
202            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
203        && !name.ends_with('_')
204        && !name.contains("__")
205}
206
207impl ProtocolDescriptor {
208    pub fn command(&self, id: &str) -> Option<(usize, &CommandSpec)> {
209        self.commands
210            .iter()
211            .enumerate()
212            .find(|(_, spec)| spec.id == id)
213    }
214
215    /// A name for `command` that is unique in this catalog, for generated
216    /// code: the command's own name in the application's namespace, the
217    /// namespace and name joined by `_` in a module's, such as
218    /// `downloads_add`.
219    pub fn command_symbol(&self, command: &CommandSpec) -> String {
220        match command.id.strip_suffix(&format!(".{}", command.name)) {
221            Some(namespace) if namespace != self.namespace => {
222                format!("{namespace}_{}", command.name)
223            }
224            _ => command.name.clone(),
225        }
226    }
227
228    pub fn state_index(&self, name: &str) -> Option<usize> {
229        self.state.iter().position(|field| field.name == name)
230    }
231
232    /// Stable fingerprint of the full descriptor. Peers compare it during
233    /// the handshake so a stale client cannot silently use another catalog.
234    pub fn fingerprint(&self) -> u64 {
235        fingerprint_bytes(
236            serde_json::to_string(self)
237                .expect("descriptor serializes")
238                .as_bytes(),
239        )
240    }
241
242    pub fn validate(&self) -> Result<(), DescriptorError> {
243        if self.descriptor_version != DESCRIPTOR_VERSION {
244            return Err(DescriptorError(format!(
245                "descriptor version {} is not supported (expected {DESCRIPTOR_VERSION})",
246                self.descriptor_version
247            )));
248        }
249        if !valid_name(&self.namespace) {
250            return Err(DescriptorError(format!(
251                "invalid protocol namespace `{}`; use lower snake case",
252                self.namespace
253            )));
254        }
255        for namespace in std::iter::once(&self.namespace).chain(&self.modules) {
256            if !valid_name(namespace) {
257                return Err(DescriptorError(format!(
258                    "invalid module namespace `{namespace}`; use lower snake case"
259                )));
260            }
261            if RESERVED_NAMESPACES.contains(&namespace.as_str()) {
262                return Err(DescriptorError(format!(
263                    "protocol namespace `{namespace}` is reserved for framework commands"
264                )));
265            }
266        }
267        self.types.validate()?;
268        let mut state_names = BTreeMap::new();
269        for field in &self.state {
270            if state_names.insert(&field.name, ()).is_some() {
271                return Err(DescriptorError(format!(
272                    "state field `{}` is declared twice",
273                    field.name
274                )));
275            }
276            self.types.check_type(&field.ty, &mut Vec::new())?;
277            if let Some(key_name) = &field.keyed {
278                let Type::List { inner } = &field.ty else {
279                    return Err(DescriptorError(format!(
280                        "state field `{}` sets `#[keyed({key_name})]`, which applies only to a list of records",
281                        field.name
282                    )));
283                };
284                let Type::Record { name: rec_name } = inner.as_ref() else {
285                    return Err(DescriptorError(format!(
286                        "state field `{}` sets `#[keyed({key_name})]`, which applies only to a list of records",
287                        field.name
288                    )));
289                };
290                let Some(def) = self.types.record_def(rec_name) else {
291                    return Err(DescriptorError(format!(
292                        "state field `{}` references unknown record `{rec_name}`",
293                        field.name
294                    )));
295                };
296                let Some(key_field) = def.fields.iter().find(|f| &f.name == key_name) else {
297                    return Err(DescriptorError(format!(
298                        "state field `{}` sets `#[keyed({key_name})]`, which `{rec_name}` does not have",
299                        field.name
300                    )));
301                };
302                if !matches!(key_field.ty, Type::Int | Type::Text) {
303                    return Err(DescriptorError(format!(
304                        "key field `{key_name}` of `{rec_name}` must be `i64` or `String`, found {}",
305                        key_field.ty.display()
306                    )));
307                }
308            }
309        }
310        let mut ids = BTreeMap::new();
311        for command in &self.commands {
312            if !valid_name(&command.name) {
313                return Err(DescriptorError(format!(
314                    "invalid command name `{}`; use lower snake case",
315                    command.name
316                )));
317            }
318            let owner = command
319                .id
320                .strip_suffix(&format!(".{}", command.name))
321                .unwrap_or_default();
322            let switch = owner == MODULES_NAMESPACE && !self.modules.is_empty();
323            if owner != self.namespace
324                && !self.modules.iter().any(|module| module == owner)
325                && !switch
326            {
327                return Err(DescriptorError(format!(
328                    "command `{}` must use the id `{}.{}`",
329                    command.name, self.namespace, command.name
330                )));
331            }
332            if ids.insert(command.id.clone(), ()).is_some() {
333                return Err(DescriptorError(format!(
334                    "command `{}` is registered twice",
335                    command.id
336                )));
337            }
338            let mut params = BTreeMap::new();
339            for param in &command.params {
340                if params.insert(&param.name, ()).is_some() {
341                    return Err(DescriptorError(format!(
342                        "command `{}` repeats parameter `{}`",
343                        command.id, param.name
344                    )));
345                }
346                self.types.check_type(&param.ty, &mut Vec::new())?;
347            }
348            self.types.check_type(&command.result, &mut Vec::new())?;
349            if !command.reads.is_empty() && !command.is_query() {
350                return Err(DescriptorError(format!(
351                    "command `{}` declares state reads; only queries do",
352                    command.id
353                )));
354            }
355            for field in &command.reads {
356                if self.state_index(field).is_none() {
357                    return Err(DescriptorError(format!(
358                        "query `{}` reads `{field}`, which is not a state field",
359                        command.id
360                    )));
361                }
362            }
363        }
364        check_external_names(self.commands.iter())?;
365        Ok(())
366    }
367}
368
369/// Reject catalogs where two commands would share a CLI path or MCP tool.
370pub fn check_external_names<'a>(
371    commands: impl IntoIterator<Item = &'a CommandSpec>,
372) -> Result<(), DescriptorError> {
373    let mut cli = BTreeMap::new();
374    let mut mcp = BTreeMap::new();
375    for command in commands {
376        if let Some(other) = cli.insert(command.external.cli.join(" "), &command.id) {
377            return Err(DescriptorError(format!(
378                "commands `{other}` and `{}` map to the same CLI command `{}`",
379                command.id,
380                command.external.cli.join(" ")
381            )));
382        }
383        if let Some(other) = mcp.insert(command.external.mcp.clone(), &command.id) {
384            return Err(DescriptorError(format!(
385                "commands `{other}` and `{}` map to the same MCP tool `{}`",
386                command.id, command.external.mcp
387            )));
388        }
389    }
390    Ok(())
391}
392
393#[cfg(test)]
394mod tests {
395    use super::*;
396
397    fn command(namespace: &str, name: &str) -> CommandSpec {
398        CommandSpec {
399            id: format!("{namespace}.{name}"),
400            name: name.into(),
401            doc: String::new(),
402            kind: OperationKind::Command,
403            scope: Scope::Engine,
404            params: vec![],
405            result: Type::Unit,
406            errors: vec![],
407            policy: CommandPolicy::default(),
408            external: ExternalNames::derive(namespace, name),
409            reads: vec![],
410            on: None,
411        }
412    }
413
414    fn descriptor(commands: Vec<CommandSpec>) -> ProtocolDescriptor {
415        ProtocolDescriptor {
416            modules: Vec::new(),
417            events: Vec::new(),
418            descriptor_version: DESCRIPTOR_VERSION,
419            namespace: "player".into(),
420            version: 1,
421            types: TypeTable::default(),
422            state: vec![],
423            commands,
424        }
425    }
426
427    #[test]
428    fn external_names_follow_the_documented_mapping() {
429        let names = ExternalNames::derive("player", "seek_to");
430        assert_eq!(names.cli, vec!["player", "seek-to"]);
431        assert_eq!(names.mcp, "player_seek_to");
432    }
433
434    #[test]
435    fn duplicate_commands_and_name_collisions_fail() {
436        assert!(
437            descriptor(vec![command("player", "seek"), command("player", "seek")])
438                .validate()
439                .is_err()
440        );
441        let mut clash = command("player", "pause");
442        clash.external.mcp = "player_seek".into();
443        assert!(
444            descriptor(vec![command("player", "seek"), clash])
445                .validate()
446                .is_err()
447        );
448        descriptor(vec![command("player", "seek"), command("player", "pause")])
449            .validate()
450            .unwrap();
451    }
452
453    #[test]
454    fn only_queries_read_declared_state_fields() {
455        let mut query = command("player", "search");
456        query.kind = OperationKind::Query;
457        query.reads = vec!["position_ms".into()];
458        let mut with_state = descriptor(vec![query.clone()]);
459        with_state.state.push(StateField {
460            name: "position_ms".into(),
461            ty: Type::Int,
462            doc: String::new(),
463            content: false,
464            stream: false,
465            keyed: None,
466        });
467        with_state.validate().unwrap();
468        // Unknown field.
469        assert!(descriptor(vec![query.clone()]).validate().is_err());
470        // A command cannot declare reads.
471        let mut command_reads = with_state.clone();
472        command_reads.commands[0].kind = OperationKind::Command;
473        assert!(command_reads.validate().is_err());
474    }
475
476    #[test]
477    fn fingerprint_changes_with_catalog() {
478        let a = descriptor(vec![command("player", "seek")]);
479        let b = descriptor(vec![command("player", "pause")]);
480        assert_ne!(a.fingerprint(), b.fingerprint());
481        assert_eq!(a.fingerprint(), a.clone().fingerprint());
482    }
483}