1use crate::{DESCRIPTOR_VERSION, SchemaError, Type, TypeTable, fingerprint_bytes};
2use serde::{Deserialize, Serialize};
3use std::collections::BTreeMap;
4use std::fmt;
5
6#[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#[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 Serial,
28 Overlapping,
32}
33
34#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
35#[serde(rename_all = "snake_case")]
36pub enum Retry {
37 Never,
39 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#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
62pub struct ExternalNames {
63 pub cli: Vec<String>,
65}
66
67impl ExternalNames {
68 pub fn derive(namespace: &str, name: &str) -> Self {
69 Self {
70 cli: vec![namespace.replace('_', "-"), name.replace('_', "-")],
71 }
72 }
73}
74
75#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
76pub struct ParamSpec {
77 pub name: String,
78 #[serde(rename = "type")]
79 pub ty: Type,
80 #[serde(default, skip_serializing_if = "String::is_empty")]
81 pub doc: String,
82}
83
84#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
85pub struct CommandSpec {
86 pub id: String,
88 pub name: String,
89 #[serde(default, skip_serializing_if = "String::is_empty")]
90 pub doc: String,
91 #[serde(default)]
92 pub kind: OperationKind,
93 pub scope: Scope,
94 pub params: Vec<ParamSpec>,
95 pub result: Type,
96 #[serde(default, skip_serializing_if = "Vec::is_empty")]
98 pub errors: Vec<String>,
99 pub policy: CommandPolicy,
100 pub external: ExternalNames,
101 #[serde(default, skip_serializing_if = "Vec::is_empty")]
104 pub reads: Vec<String>,
105 #[serde(default, skip_serializing_if = "Option::is_none")]
108 pub on: Option<String>,
109}
110
111#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
114pub struct EventSpec {
115 pub name: String,
116 #[serde(default, skip_serializing_if = "String::is_empty")]
117 pub doc: String,
118 pub params: Vec<ParamSpec>,
119}
120
121impl CommandSpec {
122 pub fn is_query(&self) -> bool {
123 self.kind == OperationKind::Query
124 }
125}
126
127#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
128pub struct StateField {
129 pub name: String,
130 #[serde(rename = "type")]
131 pub ty: Type,
132 #[serde(default, skip_serializing_if = "String::is_empty")]
133 pub doc: String,
134 #[serde(default, skip_serializing_if = "is_false")]
137 pub content: bool,
138 #[serde(default, skip_serializing_if = "is_false")]
141 pub stream: bool,
142 #[serde(default, skip_serializing_if = "Option::is_none")]
144 pub keyed: Option<String>,
145}
146
147fn is_false(value: &bool) -> bool {
148 !*value
149}
150
151#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
154pub struct ProtocolDescriptor {
155 pub descriptor_version: u32,
156 pub namespace: String,
157 pub version: u32,
159 pub types: TypeTable,
160 pub state: Vec<StateField>,
161 pub commands: Vec<CommandSpec>,
162 #[serde(default, skip_serializing_if = "Vec::is_empty")]
164 pub events: Vec<EventSpec>,
165 #[serde(default, skip_serializing_if = "Vec::is_empty")]
169 pub modules: Vec<String>,
170}
171
172#[derive(Clone, Debug, PartialEq, Eq)]
173pub struct DescriptorError(pub String);
174
175impl fmt::Display for DescriptorError {
176 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
177 f.write_str(&self.0)
178 }
179}
180
181impl std::error::Error for DescriptorError {}
182
183impl From<SchemaError> for DescriptorError {
184 fn from(error: SchemaError) -> Self {
185 DescriptorError(error.message)
186 }
187}
188
189pub const RESERVED_NAMESPACES: &[&str] = &["bern", "ui", "window", "session", "media", "modules"];
191
192pub const MODULES_NAMESPACE: &str = "modules";
194
195pub fn valid_name(name: &str) -> bool {
196 name.starts_with(|c: char| c.is_ascii_lowercase())
197 && name
198 .chars()
199 .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
200 && !name.ends_with('_')
201 && !name.contains("__")
202}
203
204impl ProtocolDescriptor {
205 pub fn command(&self, id: &str) -> Option<(usize, &CommandSpec)> {
206 self.commands
207 .iter()
208 .enumerate()
209 .find(|(_, spec)| spec.id == id)
210 }
211
212 pub fn command_symbol(&self, command: &CommandSpec) -> String {
217 match command.id.strip_suffix(&format!(".{}", command.name)) {
218 Some(namespace) if namespace != self.namespace => {
219 format!("{namespace}_{}", command.name)
220 }
221 _ => command.name.clone(),
222 }
223 }
224
225 pub fn state_index(&self, name: &str) -> Option<usize> {
226 self.state.iter().position(|field| field.name == name)
227 }
228
229 pub fn fingerprint(&self) -> u64 {
232 fingerprint_bytes(
233 serde_json::to_string(self)
234 .expect("descriptor serializes")
235 .as_bytes(),
236 )
237 }
238
239 pub fn validate(&self) -> Result<(), DescriptorError> {
240 if self.descriptor_version != DESCRIPTOR_VERSION {
241 return Err(DescriptorError(format!(
242 "descriptor version {} is not supported (expected {DESCRIPTOR_VERSION})",
243 self.descriptor_version
244 )));
245 }
246 if !valid_name(&self.namespace) {
247 return Err(DescriptorError(format!(
248 "invalid protocol namespace `{}`; use lower snake case",
249 self.namespace
250 )));
251 }
252 for namespace in std::iter::once(&self.namespace).chain(&self.modules) {
253 if !valid_name(namespace) {
254 return Err(DescriptorError(format!(
255 "invalid module namespace `{namespace}`; use lower snake case"
256 )));
257 }
258 if RESERVED_NAMESPACES.contains(&namespace.as_str()) {
259 return Err(DescriptorError(format!(
260 "protocol namespace `{namespace}` is reserved for framework commands"
261 )));
262 }
263 }
264 self.types.validate()?;
265 let mut state_names = BTreeMap::new();
266 for field in &self.state {
267 if state_names.insert(&field.name, ()).is_some() {
268 return Err(DescriptorError(format!(
269 "state field `{}` is declared twice",
270 field.name
271 )));
272 }
273 self.types.check_type(&field.ty, &mut Vec::new())?;
274 if let Some(key_name) = &field.keyed {
275 let Type::List { inner } = &field.ty else {
276 return Err(DescriptorError(format!(
277 "state field `{}` sets `#[keyed({key_name})]`, which applies only to a list of records",
278 field.name
279 )));
280 };
281 let Type::Record { name: rec_name } = inner.as_ref() else {
282 return Err(DescriptorError(format!(
283 "state field `{}` sets `#[keyed({key_name})]`, which applies only to a list of records",
284 field.name
285 )));
286 };
287 let Some(def) = self.types.record_def(rec_name) else {
288 return Err(DescriptorError(format!(
289 "state field `{}` references unknown record `{rec_name}`",
290 field.name
291 )));
292 };
293 let Some(key_field) = def.fields.iter().find(|f| &f.name == key_name) else {
294 return Err(DescriptorError(format!(
295 "state field `{}` sets `#[keyed({key_name})]`, which `{rec_name}` does not have",
296 field.name
297 )));
298 };
299 if !matches!(key_field.ty, Type::Int | Type::Text) {
300 return Err(DescriptorError(format!(
301 "key field `{key_name}` of `{rec_name}` must be `i64` or `String`, found {}",
302 key_field.ty.display()
303 )));
304 }
305 }
306 }
307 let mut symbols = BTreeMap::new();
308 for command in &self.commands {
309 if !valid_name(&command.name) {
310 return Err(DescriptorError(format!(
311 "invalid command name `{}`; use lower snake case",
312 command.name
313 )));
314 }
315 let owner = command
316 .id
317 .strip_suffix(&format!(".{}", command.name))
318 .unwrap_or_default();
319 let switch = owner == MODULES_NAMESPACE && !self.modules.is_empty();
320 if owner != self.namespace
321 && !self.modules.iter().any(|module| module == owner)
322 && !switch
323 {
324 return Err(DescriptorError(format!(
325 "command `{}` must use the id `{}.{}`",
326 command.name, self.namespace, command.name
327 )));
328 }
329 if let Some(other) = symbols.insert(self.command_symbol(command), &command.id) {
330 if other == &command.id {
331 return Err(DescriptorError(format!(
332 "command `{}` is registered twice",
333 command.id
334 )));
335 }
336 return Err(DescriptorError(format!(
337 "commands `{other}` and `{}` generate the same binding `{}`",
338 command.id,
339 self.command_symbol(command)
340 )));
341 }
342 let mut params = BTreeMap::new();
343 for param in &command.params {
344 if params.insert(¶m.name, ()).is_some() {
345 return Err(DescriptorError(format!(
346 "command `{}` repeats parameter `{}`",
347 command.id, param.name
348 )));
349 }
350 self.types.check_type(¶m.ty, &mut Vec::new())?;
351 }
352 self.types.check_type(&command.result, &mut Vec::new())?;
353 if !command.reads.is_empty() && !command.is_query() {
354 return Err(DescriptorError(format!(
355 "command `{}` declares state reads; only queries do",
356 command.id
357 )));
358 }
359 for field in &command.reads {
360 if self.state_index(field).is_none() {
361 return Err(DescriptorError(format!(
362 "query `{}` reads `{field}`, which is not a state field",
363 command.id
364 )));
365 }
366 }
367 }
368 check_external_names(self.commands.iter())?;
369 Ok(())
370 }
371}
372
373pub fn check_external_names<'a>(
375 commands: impl IntoIterator<Item = &'a CommandSpec>,
376) -> Result<(), DescriptorError> {
377 let mut cli = BTreeMap::new();
378 for command in commands {
379 if let Some(other) = cli.insert(command.external.cli.join(" "), &command.id) {
380 return Err(DescriptorError(format!(
381 "commands `{other}` and `{}` map to the same CLI command `{}`",
382 command.id,
383 command.external.cli.join(" ")
384 )));
385 }
386 }
387 Ok(())
388}
389
390#[cfg(test)]
391mod tests {
392 use super::*;
393
394 fn command(namespace: &str, name: &str) -> CommandSpec {
395 CommandSpec {
396 id: format!("{namespace}.{name}"),
397 name: name.into(),
398 doc: String::new(),
399 kind: OperationKind::Command,
400 scope: Scope::Engine,
401 params: vec![],
402 result: Type::Unit,
403 errors: vec![],
404 policy: CommandPolicy::default(),
405 external: ExternalNames::derive(namespace, name),
406 reads: vec![],
407 on: None,
408 }
409 }
410
411 fn descriptor(commands: Vec<CommandSpec>) -> ProtocolDescriptor {
412 ProtocolDescriptor {
413 modules: Vec::new(),
414 events: Vec::new(),
415 descriptor_version: DESCRIPTOR_VERSION,
416 namespace: "player".into(),
417 version: 1,
418 types: TypeTable::default(),
419 state: vec![],
420 commands,
421 }
422 }
423
424 #[test]
425 fn external_names_follow_the_documented_mapping() {
426 let names = ExternalNames::derive("player", "seek_to");
427 assert_eq!(names.cli, vec!["player", "seek-to"]);
428 assert_eq!(
429 serde_json::to_value(&names).unwrap(),
430 serde_json::json!({"cli": ["player", "seek-to"]})
431 );
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.cli = vec!["player".into(), "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 binding_collisions_depend_on_the_generated_method_not_the_cli_path() {
455 let mut catalog = descriptor(vec![
456 command("player", "queue_add"),
457 command("player_queue", "add"),
458 ]);
459 catalog.modules.push("player_queue".into());
460 catalog.validate().unwrap();
462
463 catalog.namespace = "shell".into();
465 catalog.modules.push("player".into());
466 assert_eq!(
467 catalog.validate().unwrap_err().0,
468 "commands `player.queue_add` and `player_queue.add` generate the same binding `player_queue_add`"
469 );
470 }
471
472 #[test]
473 fn only_queries_read_declared_state_fields() {
474 let mut query = command("player", "search");
475 query.kind = OperationKind::Query;
476 query.reads = vec!["position_ms".into()];
477 let mut with_state = descriptor(vec![query.clone()]);
478 with_state.state.push(StateField {
479 name: "position_ms".into(),
480 ty: Type::Int,
481 doc: String::new(),
482 content: false,
483 stream: false,
484 keyed: None,
485 });
486 with_state.validate().unwrap();
487 assert!(descriptor(vec![query.clone()]).validate().is_err());
489 let mut command_reads = with_state.clone();
491 command_reads.commands[0].kind = OperationKind::Command;
492 assert!(command_reads.validate().is_err());
493 }
494
495 #[test]
496 fn fingerprint_changes_with_catalog() {
497 let a = descriptor(vec![command("player", "seek")]);
498 let b = descriptor(vec![command("player", "pause")]);
499 assert_ne!(a.fingerprint(), b.fingerprint());
500 assert_eq!(a.fingerprint(), a.clone().fingerprint());
501 }
502}