Skip to main content

aimdb_core/remote/
protocol.rs

1//! AimX Protocol Message Types
2//!
3//! Defines the method-level payloads for the remote access protocol: the
4//! hello/welcome handshake bodies and the request/response/event shapes.
5//! These ride the **AimX** NDJSON envelope; the wire framing itself lives
6//! in [`crate::session::aimx`] (feature `connector-session`). See
7//! `docs/design/remote-access-via-connectors.md` for the architecture.
8
9use alloc::string::String;
10use alloc::vec::Vec;
11use serde::{Deserialize, Serialize};
12use serde_json::Value as JsonValue;
13
14/// Version of the AimX wire protocol spoken by this crate.
15pub const PROTOCOL_VERSION: &str = "4.0";
16
17/// Query-parameter name a WebSocket client uses to declare its
18/// [`PROTOCOL_VERSION`] at the HTTP upgrade. The socket transports gate the
19/// version inside the `hello` handshake, but a browser cannot set custom
20/// headers on the WebSocket handshake **and** the WS server runs
21/// `reads_hello:false`, so the WS upgrade carries the version in the URL
22/// instead (`…/ws?v=4.0`) and the server refuses an incompatible/absent one
23/// before the socket opens. See [`ws_url_with_version`].
24pub const VERSION_PARAM: &str = "v";
25
26/// Append this crate's [`PROTOCOL_VERSION`] as the [`VERSION_PARAM`] query
27/// parameter to a WebSocket upgrade `url`, joining with `&` if `url` already
28/// carries a query string and `?` otherwise. Every first-party WS client
29/// dialer routes its URL through this so the server's upgrade-time gate sees a
30/// version; keeping the `NAME=VALUE` contract here means the reader
31/// (the server) and the writers (the dialers) never drift.
32pub fn ws_url_with_version(url: &str) -> String {
33    let sep = if url.contains('?') { '&' } else { '?' };
34    alloc::format!("{url}{sep}{VERSION_PARAM}={PROTOCOL_VERSION}")
35}
36
37/// Major-version component of a `"MAJOR.MINOR"` protocol string, or `None` if it
38/// is empty or not in that shape.
39fn protocol_major(version: &str) -> Option<&str> {
40    match version.split('.').next() {
41        Some(major) if !major.is_empty() => Some(major),
42        _ => None,
43    }
44}
45
46/// Whether a peer advertising `their_version` is wire-compatible with this
47/// crate's [`PROTOCOL_VERSION`].
48///
49/// Compatibility is by **major** version — a breaking wire change bumps the
50/// major (2.x → 3.0), a compatible additive change bumps only the minor. A
51/// missing or malformed version string is treated as **incompatible** (fail
52/// closed): a peer that cannot state a version it speaks is exactly the legacy
53/// client this gate exists to turn away.
54pub fn version_compatible(their_version: &str) -> bool {
55    match (
56        protocol_major(their_version),
57        protocol_major(PROTOCOL_VERSION),
58    ) {
59        (Some(theirs), Some(ours)) => theirs == ours,
60        _ => false,
61    }
62}
63
64/// Client hello message
65#[derive(Debug, Clone, Serialize, Deserialize)]
66pub struct HelloMessage {
67    /// Protocol version
68    pub version: String,
69
70    /// Client identification string
71    pub client: String,
72
73    /// Desired capabilities (optional)
74    #[serde(skip_serializing_if = "Option::is_none")]
75    pub capabilities: Option<Vec<String>>,
76
77    /// Authentication token (optional)
78    #[serde(skip_serializing_if = "Option::is_none")]
79    pub auth_token: Option<String>,
80}
81
82/// Server welcome message
83#[derive(Debug, Clone, Serialize, Deserialize)]
84pub struct WelcomeMessage {
85    /// Protocol version
86    pub version: String,
87
88    /// Server identification string
89    pub server: String,
90
91    /// Granted permissions
92    pub permissions: Vec<String>,
93
94    /// Records that allow writes (empty for read-only)
95    pub writable_records: Vec<String>,
96
97    /// Maximum subscriptions per connection (optional)
98    #[serde(skip_serializing_if = "Option::is_none")]
99    pub max_subscriptions: Option<usize>,
100
101    /// Whether client is authenticated
102    #[serde(skip_serializing_if = "Option::is_none")]
103    pub authenticated: Option<bool>,
104
105    /// The instance's name, when one was given at startup (3.1)
106    #[serde(default, skip_serializing_if = "Option::is_none")]
107    pub instance_name: Option<String>,
108}
109
110/// Most bytes of post-link data one `instance.post_link` reply carries; the
111/// reply's `data` is twice as many hex digits.
112pub const POST_LINK_CHUNK_MAX: u32 = 1024;
113
114/// Upper bound on an `instance.info` reply, in bytes of JSON: a 4 KiB payload,
115/// a 128-byte name (JSON escaping at most 6× it), a 32-byte UID as hex and
116/// the fixed fields. Every reply fits the smallest AimX frame (serial, 8 KiB).
117pub const INSTANCE_INFO_REPLY_MAX: usize = 6 * 1024;
118
119/// Reply of `instance.info` (3.1): which build and which instance this is.
120#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
121pub struct InstanceInfoReply {
122    /// Version of `aimdb-core` the instance runs.
123    pub aimdb_version: String,
124    /// Name and UID given at startup.
125    pub instance: InstanceIdentityReply,
126    /// The build-info section; `None` (`null`) when none is embedded.
127    pub build: Option<BuildReply>,
128}
129
130/// The `instance` part of [`InstanceInfoReply`].
131#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
132pub struct InstanceIdentityReply {
133    /// Instance name.
134    pub name: Option<String>,
135    /// Instance UID as lowercase hex.
136    pub uid: Option<String>,
137}
138
139/// The `build` part of [`InstanceInfoReply`].
140#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
141pub struct BuildReply {
142    /// Section layout version.
143    pub format: u16,
144    /// The payload as embedded (schema 1 or later); readers ignore fields
145    /// they do not know.
146    pub info: JsonValue,
147    /// The post-link region's state; `None` (`null`) when the section has no
148    /// region. Its bytes are read with `instance.post_link`.
149    pub post_link: Option<PostLinkReply>,
150}
151
152/// State of the post-link region.
153#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
154#[serde(tag = "state", rename_all = "snake_case")]
155pub enum PostLinkReply {
156    /// Not written yet.
157    Erased,
158    /// Written: `len` bytes.
159    Written {
160        /// Number of written bytes.
161        len: u32,
162    },
163    /// Neither erased nor a valid length prefix.
164    Malformed,
165}
166
167/// Reply of `instance.post_link` (3.1): one chunk of the written post-link
168/// bytes. Clients read from offset 0 until they hold `total` bytes.
169#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
170pub struct PostLinkChunk {
171    /// Offset of `data` in the written bytes, as requested.
172    pub offset: u32,
173    /// Number of written bytes.
174    pub total: u32,
175    /// Lowercase hex of at most [`POST_LINK_CHUNK_MAX`] bytes; empty at or
176    /// past the end.
177    pub data: String,
178}
179
180/// Request message from client
181#[derive(Debug, Clone, Serialize, Deserialize)]
182pub struct Request {
183    /// Unique request identifier
184    pub id: u64,
185
186    /// Method name
187    pub method: String,
188
189    /// Method parameters (optional)
190    #[serde(skip_serializing_if = "Option::is_none")]
191    pub params: Option<JsonValue>,
192}
193
194/// Response message from server
195#[derive(Debug, Clone, Serialize, Deserialize)]
196#[serde(untagged)]
197pub enum Response {
198    /// Success response
199    Success {
200        /// Request ID
201        id: u64,
202        /// Result value
203        result: JsonValue,
204    },
205    /// Error response
206    Error {
207        /// Request ID
208        id: u64,
209        /// Error details
210        error: ErrorObject,
211    },
212}
213
214impl Response {
215    /// Creates a success response
216    pub fn success(id: u64, result: JsonValue) -> Self {
217        Self::Success { id, result }
218    }
219
220    /// Creates an error response
221    pub fn error(id: u64, code: impl Into<String>, message: impl Into<String>) -> Self {
222        Self::Error {
223            id,
224            error: ErrorObject {
225                code: code.into(),
226                message: message.into(),
227                details: None,
228            },
229        }
230    }
231
232    /// Creates an error response with details
233    pub fn error_with_details(
234        id: u64,
235        code: impl Into<String>,
236        message: impl Into<String>,
237        details: JsonValue,
238    ) -> Self {
239        Self::Error {
240            id,
241            error: ErrorObject {
242                code: code.into(),
243                message: message.into(),
244                details: Some(details),
245            },
246        }
247    }
248}
249
250/// Error object in response
251#[derive(Debug, Clone, Serialize, Deserialize)]
252pub struct ErrorObject {
253    /// Error code
254    pub code: String,
255
256    /// Human-readable error message
257    pub message: String,
258
259    /// Additional error details (optional)
260    #[serde(skip_serializing_if = "Option::is_none")]
261    pub details: Option<JsonValue>,
262}
263
264/// Event message from server (subscription push)
265#[derive(Debug, Clone, Serialize, Deserialize)]
266pub struct Event {
267    /// Subscription identifier
268    pub subscription_id: String,
269
270    /// Monotonic sequence number
271    pub sequence: u64,
272
273    /// Event data (record value)
274    pub data: JsonValue,
275
276    /// Unix timestamp in "secs.nanosecs" format (e.g., "1730379296.123456789")
277    pub timestamp: String,
278
279    /// Number of dropped events since last delivery (optional)
280    #[serde(skip_serializing_if = "Option::is_none")]
281    pub dropped: Option<u64>,
282}
283
284#[cfg(test)]
285mod tests {
286    use super::*;
287    use alloc::string::ToString;
288    use alloc::vec;
289
290    #[test]
291    fn test_hello_serialization() {
292        let hello = HelloMessage {
293            version: PROTOCOL_VERSION.to_string(),
294            client: "test-client".to_string(),
295            capabilities: Some(vec!["read".to_string()]),
296            auth_token: None,
297        };
298
299        let json = serde_json::to_string(&hello).unwrap();
300        assert!(json.contains("\"version\":\"4.0\""));
301        assert!(json.contains("\"client\":\"test-client\""));
302    }
303
304    fn welcome(instance_name: Option<&str>) -> WelcomeMessage {
305        WelcomeMessage {
306            version: PROTOCOL_VERSION.to_string(),
307            server: "aimdb".to_string(),
308            permissions: vec!["read".to_string()],
309            writable_records: vec![],
310            max_subscriptions: Some(8),
311            authenticated: Some(false),
312            instance_name: instance_name.map(String::from),
313        }
314    }
315
316    #[test]
317    fn instance_name_is_omitted_when_unset() {
318        let json = serde_json::to_string(&welcome(None)).unwrap();
319        assert!(!json.contains("instance_name"), "{json}");
320        let json = serde_json::to_string(&welcome(Some("gateway-3"))).unwrap();
321        assert!(json.contains(r#""instance_name":"gateway-3""#), "{json}");
322    }
323
324    /// 3.1 is additive: a 3.0 client parses a 3.1 welcome, and a 3.1 client
325    /// parses a 3.0 welcome.
326    #[test]
327    fn welcome_is_compatible_both_ways() {
328        /// `WelcomeMessage` as of protocol 3.0, frozen.
329        #[derive(Deserialize, Serialize)]
330        struct WelcomeV30 {
331            version: String,
332            server: String,
333            permissions: Vec<String>,
334            writable_records: Vec<String>,
335            #[serde(skip_serializing_if = "Option::is_none")]
336            max_subscriptions: Option<usize>,
337            #[serde(skip_serializing_if = "Option::is_none")]
338            authenticated: Option<bool>,
339        }
340
341        let v31 = serde_json::to_string(&welcome(Some("gateway-3"))).unwrap();
342        let old: WelcomeV30 = serde_json::from_str(&v31).unwrap();
343        assert_eq!(old.server, "aimdb");
344
345        let v30 = serde_json::to_string(&WelcomeV30 {
346            version: "3.0".to_string(),
347            ..old
348        })
349        .unwrap();
350        let new: WelcomeMessage = serde_json::from_str(&v30).unwrap();
351        assert_eq!(new.instance_name, None);
352    }
353
354    #[test]
355    fn post_link_reply_shapes() {
356        let cases = [
357            (PostLinkReply::Erased, r#"{"state":"erased"}"#),
358            (
359                PostLinkReply::Written { len: 1472 },
360                r#"{"state":"written","len":1472}"#,
361            ),
362            (PostLinkReply::Malformed, r#"{"state":"malformed"}"#),
363        ];
364        for (reply, json) in cases {
365            assert_eq!(serde_json::to_string(&reply).unwrap(), json);
366            assert_eq!(serde_json::from_str::<PostLinkReply>(json).unwrap(), reply);
367        }
368    }
369
370    #[test]
371    fn version_compatible_matches_on_major() {
372        // Same major (current + a hypothetical future minor) → compatible.
373        assert!(version_compatible(PROTOCOL_VERSION));
374        assert!(version_compatible("4.0"));
375        assert!(version_compatible("4.7"));
376        assert!(version_compatible("4")); // bare major
377
378        // Older majors → refused: 3.x has no write stamps (`ts`), 2.x is the
379        // legacy WS-era wire.
380        assert!(!version_compatible("3.1"));
381        assert!(!version_compatible("3.0"));
382        assert!(!version_compatible("2.0"));
383        assert!(!version_compatible("1.0"));
384
385        // Missing / malformed → fail closed.
386        assert!(!version_compatible(""));
387        assert!(!version_compatible(".0"));
388        assert!(!version_compatible("garbage"));
389    }
390
391    #[test]
392    fn test_request_serialization() {
393        let request = Request {
394            id: 1,
395            method: "record.list".to_string(),
396            params: Some(serde_json::json!({})),
397        };
398
399        let json = serde_json::to_string(&request).unwrap();
400        assert!(json.contains("\"id\":1"));
401        assert!(json.contains("\"method\":\"record.list\""));
402    }
403
404    #[test]
405    fn test_response_success() {
406        let response = Response::success(1, serde_json::json!({"status": "ok"}));
407
408        let json = serde_json::to_string(&response).unwrap();
409        assert!(json.contains("\"id\":1"));
410        assert!(json.contains("\"result\""));
411        assert!(json.contains("\"status\":\"ok\""));
412    }
413
414    #[test]
415    fn test_response_error() {
416        let response = Response::error(2, "NOT_FOUND", "Record not found");
417
418        let json = serde_json::to_string(&response).unwrap();
419        assert!(json.contains("\"id\":2"));
420        assert!(json.contains("\"error\""));
421        assert!(json.contains("\"code\":\"NOT_FOUND\""));
422        assert!(json.contains("\"message\":\"Record not found\""));
423    }
424
425    #[test]
426    fn test_event_serialization() {
427        let event = Event {
428            subscription_id: "sub-123".to_string(),
429            sequence: 42,
430            data: serde_json::json!({"temp": 23.5}),
431            timestamp: "1730379296.123456789".to_string(),
432            dropped: None,
433        };
434
435        let json = serde_json::to_string(&event).unwrap();
436        assert!(json.contains("\"subscription_id\":\"sub-123\""));
437        assert!(json.contains("\"sequence\":42"));
438        assert!(json.contains("\"temp\":23.5"));
439    }
440
441    #[test]
442    fn test_event_with_dropped() {
443        let event = Event {
444            subscription_id: "sub-456".to_string(),
445            sequence: 100,
446            data: serde_json::json!({"value": 1}),
447            timestamp: "1730379300.987654321".to_string(),
448            dropped: Some(5),
449        };
450
451        let json = serde_json::to_string(&event).unwrap();
452        assert!(json.contains("\"dropped\":5"));
453    }
454}