Skip to main content

geri_proto/
lib.rs

1//! Wire contract for [Géri], a self-declaring telemetry, command, and
2//! tamper-evident event log protocol.
3//!
4
5// All codes written by my hand. But all docs written by Claude. There is not much fun at writing
6// Documentation. Boring stuff goes for Claude.
7// I've checked documentation. So far looks correct.
8
9//! This crate defines **what travels on the wire** and nothing else: no I/O, no
10//! storage, no transport. It is `#![no_std]` (it needs only `alloc`), so the same
11//! types compile for a microcontroller, a Linux daemon, a browser, or a hub.
12//! The normative description of the protocol is [`SPEC.md`].
13//!
14//! # Concepts
15//!
16//! - A **source** is the origin of data: a device, an app, a service, or an adapter
17//!   in front of one. It declares its **entities**, the addressable parts it exposes.
18//! - An entity may declare a [`Control`], which tells a hub how it can be changed
19//!   and how risky that is. Hubs validate every command against it.
20//! - [`Value`] is the shared data model for state, events, command arguments, and
21//!   results. Géri carries values without interpreting them.
22//!
23//! # Two protocol versions
24//!
25//! - **v4** ([`v4`], [`VERSION`]) is the current, batch-oriented HTTP contract:
26//!   sources submit [`v4::Batch`]es of [`v4::Record`]s and get a [`v4::Receipt`]
27//!   only after durable commit. Operators issue commands that sources claim.
28//! - **v3** ([`Up`], [`Down`], [`LEGACY_VERSION`]) is the streaming form for
29//!   long-lived connections:
30//!
31//! ```text
32//! Source                            Hub
33//!   |--- Hello --------------------->|  Who I am, what I offer
34//!   |--- State --------------------->|  My current values
35//!   |--- Event --------------------->|  Something happened
36//!   |<-- Pace -----------------------|  Report state at this interval
37//!   |<-- Invoke ---------------------|  Do this action with these args
38//!   |--- Ack ----------------------->|  Final outcome of a command
39//!   |--- Bye ----------------------->|  I am leaving
40//! ```
41//!
42//! The first v3 message must be `Hello`. A receiver checks `v` and does not process
43//! messages of a version it does not support. Unknown messages decode to
44//! [`Up::Unknown`] / [`Down::Unknown`] and may be ignored; unknown payload content is
45//! carried through unchanged.
46//!
47//! # Encodings
48//!
49//! Every type serializes with [serde] to two equivalent encodings:
50//!
51//! - **JSON**, for humans, webhooks, and browsers. In v3, [`Value`] is *tagged* so
52//!   that integers, floats, and bytes survive the round trip.
53//! - **CBOR**, for constrained devices and high-throughput links. [`Value`] uses
54//!   native CBOR types.
55//!
56//! The message envelope is the same in both, e.g. `{"t": "state", ...}`. On a
57//! WebSocket, text frames carry JSON and binary frames carry CBOR.
58//!
59//! # Example
60//!
61//! Build a v4 batch with one state record and encode it as JSON:
62//!
63//! ```
64//! use geri_proto::v4::{Batch, Record, RecordKind, VERSION};
65//!
66//! let batch = Batch {
67//!     v: VERSION,
68//!     records: vec![Record {
69//!         source_id: "router".into(),
70//!         entity_id: "cpu".into(),
71//!         record_id: "router-1".into(),
72//!         sequence: 1,
73//!         kind: RecordKind::State,
74//!         event_time_ms: None,
75//!         content_type: "application/json".into(),
76//!         data: Some(serde_json::json!({ "pct": 12.5 })),
77//!         indexed: None,
78//!         blob: None,
79//!     }],
80//! };
81//! let json = serde_json::to_string(&batch).unwrap();
82//! assert!(json.starts_with(r#"{"v":4,"records":[{"source_id":"router""#));
83//! ```
84//!
85//! Declare a v3 node with a dimmable light and a reboot button:
86//!
87//! ```
88//! use geri_proto::{Danger, Entity, LEGACY_VERSION, Shape, Up, Visibility};
89//!
90//! let hello = Up::Hello {
91//!     v: LEGACY_VERSION,
92//!     label: "Living room".into(),
93//!     pace_ms: None,
94//!     entities: vec![
95//!         Entity::new("light").label("Light").control(Shape::range(0.0, 100.0), Danger::Safe),
96//!         Entity::new("reboot").control(Shape::Trigger, Danger::Destructive),
97//!     ],
98//!     visibility: Visibility::Public,
99//! };
100//! let json = serde_json::to_value(&hello).unwrap();
101//! assert_eq!(json["t"], "hello");
102//! assert_eq!(json["entities"][1]["control"]["shape"]["type"], "trigger");
103//! ```
104//!
105//! # Limits
106//!
107//! Message size, entity counts, data depth, and traffic limits are chosen by the
108//! receiver, not by this crate; see `geri-core` and [`v4::Limits`]. The only limit
109//! enforced here is [`MAX_DEPTH`] for nested values.
110//!
111//! [Géri]: https://github.com/caneroglu/geri
112//! [`SPEC.md`]: https://github.com/caneroglu/geri/blob/main/SPEC.md
113//! [serde]: https://serde.rs
114
115#![no_std]
116#![warn(missing_docs)]
117
118extern crate alloc;
119
120use alloc::{collections::BTreeMap, string::String, vec::Vec};
121use core::num::NonZeroU32;
122use serde::{Deserialize, Serialize};
123
124mod control;
125pub mod v4;
126mod value;
127mod wire;
128pub use control::{Control, Danger, Invalid, PRESS, SET, Shape};
129pub use value::{MAX_DEPTH, Plain, Value};
130pub use wire::ValueDeserializer;
131
132/// The current protocol version (4). See [`v4`].
133pub const VERSION: u16 = v4::VERSION;
134/// The streaming protocol version (3) used by [`Up`] and [`Down`].
135pub const LEGACY_VERSION: u16 = 3;
136
137/// Identity of a v3 node, established by the transport. See [`valid_id`].
138pub type NodeId = String;
139
140/// Name of an entity, event stream, or action. See [`valid_id`].
141pub type Name = String;
142/// Milliseconds since the Unix epoch (UTC).
143pub type Timestamp = u64;
144/// Hub-chosen identifier that pairs an [`Down::Invoke`] with its [`Up::Ack`].
145pub type CommandId = String;
146/// A reporting interval in milliseconds. Zero is not a valid interval.
147pub type IntervalMs = NonZeroU32;
148/// Current values of a node, keyed by entity name.
149pub type Values = BTreeMap<Name, Value>;
150
151/// Returns whether `id` is a valid v3 identifier: 1 to 32 bytes of `a-z`, `0-9`,
152/// and `-`.
153///
154/// Used for node IDs, entity names, and groups. v4 identifiers are looser; see
155/// [`v4::valid_id`].
156///
157/// ```
158/// assert!(geri_proto::valid_id("living-room-2"));
159/// assert!(!geri_proto::valid_id("Living_Room"));
160/// assert!(!geri_proto::valid_id(""));
161/// ```
162pub fn valid_id(id: &str) -> bool {
163    (1..=32).contains(&id.len())
164        && id
165            .bytes()
166            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
167}
168
169/// An addressable part of a v3 node, as declared in [`Up::Hello`].
170///
171/// An entity carries state, events, or both, and may expose one [`Control`].
172/// Build one with [`Entity::new`] and the chained setters.
173#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
174pub struct Entity {
175    /// Entity name, unique within the node. A v3 identifier.
176    pub name: Name,
177    /// Human-readable label. Defaults to the name in UIs.
178    #[serde(default, skip_serializing_if = "Option::is_none")]
179    pub label: Option<String>,
180    /// Free-form hint for renderers, such as `"gauge"` or `"feed"`.
181    #[serde(default, skip_serializing_if = "Option::is_none")]
182    pub kind: Option<String>,
183    /// Optional group name for laying out related entities together.
184    #[serde(default, skip_serializing_if = "Option::is_none")]
185    pub group: Option<Name>,
186    /// How the entity can be changed, if at all.
187    #[serde(default, skip_serializing_if = "Option::is_none")]
188    pub control: Option<Control>,
189
190    /// Who may see this entity's values.
191    #[serde(default)]
192    pub scope: Scope,
193}
194
195impl Entity {
196    /// Creates a public entity with no label, kind, group, or control.
197    pub fn new(name: &str) -> Self {
198        Self {
199            name: name.into(),
200            ..Self::default()
201        }
202    }
203
204    /// Sets the human-readable label.
205    pub fn label(mut self, label: impl Into<String>) -> Self {
206        self.label = Some(label.into());
207        self
208    }
209
210    /// Sets the renderer hint.
211    pub fn kind(mut self, kind: impl Into<String>) -> Self {
212        self.kind = Some(kind.into());
213        self
214    }
215
216    /// Sets the layout group.
217    pub fn group(mut self, group: impl Into<Name>) -> Self {
218        self.group = Some(group.into());
219        self
220    }
221
222    /// Makes the entity controllable with the given shape and risk level.
223    pub fn control(mut self, shape: Shape, danger: Danger) -> Self {
224        self.control = Some(Control::new(shape, danger));
225        self
226    }
227
228    /// Hides the entity's values from non-admin viewers.
229    pub fn private(mut self) -> Self {
230        self.scope = Scope::Private;
231        self
232    }
233}
234
235/// Visibility of a single v3 entity.
236#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
237#[serde(rename_all = "snake_case")]
238pub enum Scope {
239    /// Visible to every viewer of the node.
240    #[default]
241    Public,
242    /// Visible only to admins.
243    Private,
244}
245
246/// Visibility of a whole v3 node, declared in [`Up::Hello`].
247///
248/// Unknown values decode as [`Visibility::Private`], so a newer, stricter value
249/// never leaks data to an older hub.
250#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
251#[serde(rename_all = "snake_case")]
252pub enum Visibility {
253    /// Listed and readable by everyone.
254    #[default]
255    Public,
256    /// Listed, but values are hidden from non-admins.
257    Masked,
258    /// Visible only to admins.
259    #[serde(other)]
260    Private,
261}
262
263impl Visibility {
264    /// Returns whether this is [`Visibility::Public`].
265    pub fn is_public(&self) -> bool {
266        *self == Self::Public
267    }
268}
269
270/// One occurrence in a v3 event stream, sent with [`Up::Event`].
271#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
272pub struct Item {
273    /// Source-chosen identifier, unique within the event stream.
274    pub id: String,
275    /// When the event happened, if the source has a clock.
276    #[serde(default, skip_serializing_if = "Option::is_none")]
277    pub at: Option<Timestamp>,
278    /// Event payload.
279    pub data: Value,
280}
281
282/// Final result of a command, sent with [`Up::Ack`].
283///
284/// There is no "accepted" or "pending" outcome: an ack is always final.
285#[derive(Clone, Debug, PartialEq, Serialize)]
286#[serde(tag = "status", rename_all = "snake_case")]
287pub enum Outcome {
288    /// The command succeeded.
289    Ok {
290        /// Result value; [`Value::Null`] when there is nothing to report.
291        value: Value,
292    },
293    /// The command failed.
294    Error {
295        /// Machine-readable error code.
296        code: String,
297        /// Human-readable explanation.
298        message: String,
299        /// Optional structured details.
300        #[serde(default, skip_serializing_if = "Option::is_none")]
301        details: Option<Value>,
302    },
303}
304
305/// A v3 message from a source to the hub.
306///
307/// Tagged by `t` on the wire, e.g. `{"t": "state", "values": {...}}`.
308#[derive(Clone, Debug, PartialEq, Serialize)]
309#[serde(tag = "t", rename_all = "snake_case")]
310pub enum Up {
311    /// Declares the node. Must be the first message on a connection.
312    Hello {
313        /// Protocol version; must be [`LEGACY_VERSION`].
314        v: u16,
315        /// Human-readable node label.
316        label: String,
317        /// Preferred state reporting interval. `None` for event-driven sources.
318        #[serde(default, skip_serializing_if = "Option::is_none")]
319        pace_ms: Option<IntervalMs>,
320        /// Every entity the node offers.
321        entities: Vec<Entity>,
322        /// Who may see the node.
323        #[serde(default, skip_serializing_if = "Visibility::is_public")]
324        visibility: Visibility,
325    },
326    /// Reports current values. Entities not listed keep their previous value.
327    State {
328        /// New values keyed by entity name.
329        values: Values,
330    },
331    /// Reports one occurrence in an event stream.
332    Event {
333        /// Entity name of the event stream.
334        name: Name,
335        /// The occurrence.
336        item: Item,
337    },
338    /// Reports the final outcome of a [`Down::Invoke`].
339    Ack {
340        /// The command being answered.
341        cmd: CommandId,
342        /// Its outcome.
343        outcome: Outcome,
344    },
345    /// Announces that the node is leaving on purpose.
346    Bye {
347        /// Why it is leaving.
348        reason: Bye,
349    },
350    /// A message type this version does not know. Receivers may ignore it.
351    #[serde(other)]
352    Unknown,
353}
354
355/// Why a node sent [`Up::Bye`]. Lets a hub tell a planned absence from a failure.
356#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
357#[serde(rename_all = "snake_case")]
358pub enum Bye {
359    /// Going to sleep; expect it back.
360    Sleep,
361    /// Shutting down.
362    Shutdown,
363    /// Any other reason, including ones unknown to this version.
364    #[serde(other)]
365    Other,
366}
367
368/// A v3 message from the hub to a source.
369#[derive(Clone, Debug, PartialEq, Serialize)]
370#[serde(tag = "t", rename_all = "snake_case")]
371pub enum Down {
372    /// Asks the source to report state at this interval.
373    Pace {
374        /// Interval in milliseconds.
375        ms: IntervalMs,
376    },
377    /// Asks the source to perform an action. Must be answered by exactly one
378    /// [`Up::Ack`].
379    Invoke {
380        /// Identifier to echo in the ack.
381        cmd: CommandId,
382        /// Target entity name.
383        name: Name,
384        /// Action to perform: [`SET`] or [`PRESS`] for declared controls.
385        action: Name,
386        /// Arguments, already validated against the entity's [`Control`].
387        #[serde(default)]
388        args: Value,
389    },
390    /// A message type this version does not know. Receivers may ignore it.
391    #[serde(other)]
392    Unknown,
393}
394
395/// MQTT topic scheme for v3 nodes on a broker.
396///
397/// ```text
398/// geri/{node}/{name}        state of entity {name}
399/// geri/{node}/{name}/set    command to entity {name}
400/// ```
401pub mod mqtt {
402    use alloc::{format, string::String};
403
404    /// First segment of every Géri topic.
405    pub const ROOT: &str = "geri";
406
407    /// Topic on which `node` publishes the state of entity `name`.
408    pub fn state_topic(node: &str, name: &str) -> String {
409        format!("{ROOT}/{node}/{name}")
410    }
411
412    /// Topic on which commands to entity `name` of `node` are published.
413    pub fn set_topic(node: &str, name: &str) -> String {
414        format!("{ROOT}/{node}/{name}/set")
415    }
416
417    /// Parses a Géri topic into `(node, name, is_set)`.
418    ///
419    /// Returns `None` for any other topic shape or for invalid identifiers.
420    ///
421    /// ```
422    /// use geri_proto::mqtt;
423    /// assert_eq!(mqtt::parse("geri/router/wifi/set"), Some(("router", "wifi", true)));
424    /// assert_eq!(mqtt::parse("geri/router/wifi"), Some(("router", "wifi", false)));
425    /// assert_eq!(mqtt::parse("geri/router/wifi/other"), None);
426    /// ```
427    pub fn parse(topic: &str) -> Option<(&str, &str, bool)> {
428        let mut it = topic.strip_prefix(ROOT)?.strip_prefix('/')?.split('/');
429        let (node, name) = (it.next()?, it.next()?);
430        let set = match it.next() {
431            None => false,
432            Some("set") => true,
433            Some(_) => return None,
434        };
435        (it.next().is_none() && super::valid_id(node) && super::valid_id(name))
436            .then_some((node, name, set))
437    }
438}
439
440#[cfg(test)]
441mod tests;