kitchen_tools/plugin/protocol.rs
1//! Requests and events between an app and a plugin: one JSON object per line (from lumen's model
2//! plugins). The app writes a request (an object with a `"request"` tag) to the program's stdin;
3//! the program answers on its stdout with [`Event`]s: `progress` any number of times, then
4//! exactly one `done` or `error`. Large data (images, masks, signals) travels as files named in
5//! the request, never through JSON.
6//!
7//! Every plugin answers the core requests ([`CoreRequest`]); an app adds its own (lumen's
8//! `segment`, `instances`) as any serializable type with a `"request"` tag.
9
10use serde::{Deserialize, Serialize};
11
12/// The protocol version this crate speaks. A plugin states the one it speaks in its manifest
13/// ([`crate::plugin::PluginInfo::protocol`]); the app refuses one that differs (the handshake).
14pub const PROTOCOL: u32 = 1;
15
16/// The requests every plugin answers.
17#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
18#[serde(tag = "request", rename_all = "snake_case")]
19pub enum CoreRequest {
20 /// The plugin's manifest (as `<program> info`).
21 Info,
22 /// Downloads and verifies something it needs (a model's weights, its runtime) by id.
23 Install {
24 /// What to install.
25 id: String,
26 },
27 /// Removes what it downloaded for `id`.
28 Remove {
29 /// What to remove.
30 id: String,
31 },
32 /// Ends a server.
33 Quit,
34}
35
36/// What a plugin answers.
37#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
38#[serde(tag = "event", rename_all = "snake_case")]
39pub enum Event {
40 /// How far it is.
41 Progress {
42 /// What it is doing ("encoding").
43 stage: String,
44 /// 0–1 when known.
45 #[serde(default)]
46 fraction: Option<f32>,
47 },
48 /// The request's answer (its JSON depends on the request).
49 Done {
50 /// The answer.
51 result: serde_json::Value,
52 },
53 /// Why the request failed.
54 Error {
55 /// The reason.
56 message: String,
57 },
58}
59
60impl Event {
61 /// The event as one line of the protocol.
62 pub fn line(&self) -> String {
63 serde_json::to_string(self).unwrap_or_else(|e| format!("{{\"event\":\"error\",\"message\":\"{e}\"}}"))
64 }
65}
66
67#[cfg(test)]
68mod tests {
69 use super::*;
70
71 #[test]
72 fn requests_and_events_are_one_json_line() {
73 let r = CoreRequest::Install { id: "sam2-tiny".into() };
74 let line = serde_json::to_string(&r).unwrap();
75 assert_eq!(line, r#"{"request":"install","id":"sam2-tiny"}"#);
76 assert_eq!(serde_json::from_str::<CoreRequest>(&line).unwrap(), r);
77 let e = Event::Progress { stage: "encoding".into(), fraction: Some(0.5) };
78 assert!(!e.line().contains('\n'));
79 assert_eq!(serde_json::from_str::<Event>(&e.line()).unwrap(), e);
80 assert_eq!(
81 serde_json::from_str::<Event>(r#"{"event":"done","result":{"n":3}}"#).unwrap(),
82 Event::Done { result: serde_json::json!({"n": 3}) }
83 );
84 }
85}