aimdb-core 3.0.0

Type-safe async data pipelines — one Rust codebase from MCU to cloud
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
//! AimX Protocol Message Types
//!
//! Defines the method-level payloads for the remote access protocol: the
//! hello/welcome handshake bodies and the request/response/event shapes.
//! These ride the **AimX** NDJSON envelope; the wire framing itself lives
//! in [`crate::session::aimx`] (feature `connector-session`). See
//! `docs/design/remote-access-via-connectors.md` for the architecture.

use alloc::string::String;
use alloc::vec::Vec;
use serde::{Deserialize, Serialize};
use serde_json::Value as JsonValue;

/// Version of the AimX wire protocol spoken by this crate.
pub const PROTOCOL_VERSION: &str = "4.0";

/// Query-parameter name a WebSocket client uses to declare its
/// [`PROTOCOL_VERSION`] at the HTTP upgrade. The socket transports gate the
/// version inside the `hello` handshake, but a browser cannot set custom
/// headers on the WebSocket handshake **and** the WS server runs
/// `reads_hello:false`, so the WS upgrade carries the version in the URL
/// instead (`…/ws?v=4.0`) and the server refuses an incompatible/absent one
/// before the socket opens. See [`ws_url_with_version`].
pub const VERSION_PARAM: &str = "v";

/// Append this crate's [`PROTOCOL_VERSION`] as the [`VERSION_PARAM`] query
/// parameter to a WebSocket upgrade `url`, joining with `&` if `url` already
/// carries a query string and `?` otherwise. Every first-party WS client
/// dialer routes its URL through this so the server's upgrade-time gate sees a
/// version; keeping the `NAME=VALUE` contract here means the reader
/// (the server) and the writers (the dialers) never drift.
pub fn ws_url_with_version(url: &str) -> String {
    let sep = if url.contains('?') { '&' } else { '?' };
    alloc::format!("{url}{sep}{VERSION_PARAM}={PROTOCOL_VERSION}")
}

/// Major-version component of a `"MAJOR.MINOR"` protocol string, or `None` if it
/// is empty or not in that shape.
fn protocol_major(version: &str) -> Option<&str> {
    match version.split('.').next() {
        Some(major) if !major.is_empty() => Some(major),
        _ => None,
    }
}

/// Whether a peer advertising `their_version` is wire-compatible with this
/// crate's [`PROTOCOL_VERSION`].
///
/// Compatibility is by **major** version — a breaking wire change bumps the
/// major (2.x → 3.0), a compatible additive change bumps only the minor. A
/// missing or malformed version string is treated as **incompatible** (fail
/// closed): a peer that cannot state a version it speaks is exactly the legacy
/// client this gate exists to turn away.
pub fn version_compatible(their_version: &str) -> bool {
    match (
        protocol_major(their_version),
        protocol_major(PROTOCOL_VERSION),
    ) {
        (Some(theirs), Some(ours)) => theirs == ours,
        _ => false,
    }
}

/// Client hello message
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HelloMessage {
    /// Protocol version
    pub version: String,

    /// Client identification string
    pub client: String,

    /// Desired capabilities (optional)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub capabilities: Option<Vec<String>>,

    /// Authentication token (optional)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub auth_token: Option<String>,
}

/// Server welcome message
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WelcomeMessage {
    /// Protocol version
    pub version: String,

    /// Server identification string
    pub server: String,

    /// Granted permissions
    pub permissions: Vec<String>,

    /// Records that allow writes (empty for read-only)
    pub writable_records: Vec<String>,

    /// Maximum subscriptions per connection (optional)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_subscriptions: Option<usize>,

    /// Whether client is authenticated
    #[serde(skip_serializing_if = "Option::is_none")]
    pub authenticated: Option<bool>,

    /// The instance's name, when one was given at startup (3.1)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub instance_name: Option<String>,
}

/// Most bytes of post-link data one `instance.post_link` reply carries; the
/// reply's `data` is twice as many hex digits.
pub const POST_LINK_CHUNK_MAX: u32 = 1024;

/// Upper bound on an `instance.info` reply, in bytes of JSON: a 4 KiB payload,
/// a 128-byte name (JSON escaping at most 6× it), a 32-byte UID as hex and
/// the fixed fields. Every reply fits the smallest AimX frame (serial, 8 KiB).
pub const INSTANCE_INFO_REPLY_MAX: usize = 6 * 1024;

/// Reply of `instance.info` (3.1): which build and which instance this is.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct InstanceInfoReply {
    /// Version of `aimdb-core` the instance runs.
    pub aimdb_version: String,
    /// Name and UID given at startup.
    pub instance: InstanceIdentityReply,
    /// The build-info section; `None` (`null`) when none is embedded.
    pub build: Option<BuildReply>,
}

/// The `instance` part of [`InstanceInfoReply`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct InstanceIdentityReply {
    /// Instance name.
    pub name: Option<String>,
    /// Instance UID as lowercase hex.
    pub uid: Option<String>,
}

/// The `build` part of [`InstanceInfoReply`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BuildReply {
    /// Section layout version.
    pub format: u16,
    /// The payload as embedded (schema 1 or later); readers ignore fields
    /// they do not know.
    pub info: JsonValue,
    /// The post-link region's state; `None` (`null`) when the section has no
    /// region. Its bytes are read with `instance.post_link`.
    pub post_link: Option<PostLinkReply>,
}

/// State of the post-link region.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "state", rename_all = "snake_case")]
pub enum PostLinkReply {
    /// Not written yet.
    Erased,
    /// Written: `len` bytes.
    Written {
        /// Number of written bytes.
        len: u32,
    },
    /// Neither erased nor a valid length prefix.
    Malformed,
}

/// Reply of `instance.post_link` (3.1): one chunk of the written post-link
/// bytes. Clients read from offset 0 until they hold `total` bytes.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PostLinkChunk {
    /// Offset of `data` in the written bytes, as requested.
    pub offset: u32,
    /// Number of written bytes.
    pub total: u32,
    /// Lowercase hex of at most [`POST_LINK_CHUNK_MAX`] bytes; empty at or
    /// past the end.
    pub data: String,
}

/// Request message from client
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Request {
    /// Unique request identifier
    pub id: u64,

    /// Method name
    pub method: String,

    /// Method parameters (optional)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub params: Option<JsonValue>,
}

/// Response message from server
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Response {
    /// Success response
    Success {
        /// Request ID
        id: u64,
        /// Result value
        result: JsonValue,
    },
    /// Error response
    Error {
        /// Request ID
        id: u64,
        /// Error details
        error: ErrorObject,
    },
}

impl Response {
    /// Creates a success response
    pub fn success(id: u64, result: JsonValue) -> Self {
        Self::Success { id, result }
    }

    /// Creates an error response
    pub fn error(id: u64, code: impl Into<String>, message: impl Into<String>) -> Self {
        Self::Error {
            id,
            error: ErrorObject {
                code: code.into(),
                message: message.into(),
                details: None,
            },
        }
    }

    /// Creates an error response with details
    pub fn error_with_details(
        id: u64,
        code: impl Into<String>,
        message: impl Into<String>,
        details: JsonValue,
    ) -> Self {
        Self::Error {
            id,
            error: ErrorObject {
                code: code.into(),
                message: message.into(),
                details: Some(details),
            },
        }
    }
}

/// Error object in response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ErrorObject {
    /// Error code
    pub code: String,

    /// Human-readable error message
    pub message: String,

    /// Additional error details (optional)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub details: Option<JsonValue>,
}

/// Event message from server (subscription push)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Event {
    /// Subscription identifier
    pub subscription_id: String,

    /// Monotonic sequence number
    pub sequence: u64,

    /// Event data (record value)
    pub data: JsonValue,

    /// Unix timestamp in "secs.nanosecs" format (e.g., "1730379296.123456789")
    pub timestamp: String,

    /// Number of dropped events since last delivery (optional)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dropped: Option<u64>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::string::ToString;
    use alloc::vec;

    #[test]
    fn test_hello_serialization() {
        let hello = HelloMessage {
            version: PROTOCOL_VERSION.to_string(),
            client: "test-client".to_string(),
            capabilities: Some(vec!["read".to_string()]),
            auth_token: None,
        };

        let json = serde_json::to_string(&hello).unwrap();
        assert!(json.contains("\"version\":\"4.0\""));
        assert!(json.contains("\"client\":\"test-client\""));
    }

    fn welcome(instance_name: Option<&str>) -> WelcomeMessage {
        WelcomeMessage {
            version: PROTOCOL_VERSION.to_string(),
            server: "aimdb".to_string(),
            permissions: vec!["read".to_string()],
            writable_records: vec![],
            max_subscriptions: Some(8),
            authenticated: Some(false),
            instance_name: instance_name.map(String::from),
        }
    }

    #[test]
    fn instance_name_is_omitted_when_unset() {
        let json = serde_json::to_string(&welcome(None)).unwrap();
        assert!(!json.contains("instance_name"), "{json}");
        let json = serde_json::to_string(&welcome(Some("gateway-3"))).unwrap();
        assert!(json.contains(r#""instance_name":"gateway-3""#), "{json}");
    }

    /// 3.1 is additive: a 3.0 client parses a 3.1 welcome, and a 3.1 client
    /// parses a 3.0 welcome.
    #[test]
    fn welcome_is_compatible_both_ways() {
        /// `WelcomeMessage` as of protocol 3.0, frozen.
        #[derive(Deserialize, Serialize)]
        struct WelcomeV30 {
            version: String,
            server: String,
            permissions: Vec<String>,
            writable_records: Vec<String>,
            #[serde(skip_serializing_if = "Option::is_none")]
            max_subscriptions: Option<usize>,
            #[serde(skip_serializing_if = "Option::is_none")]
            authenticated: Option<bool>,
        }

        let v31 = serde_json::to_string(&welcome(Some("gateway-3"))).unwrap();
        let old: WelcomeV30 = serde_json::from_str(&v31).unwrap();
        assert_eq!(old.server, "aimdb");

        let v30 = serde_json::to_string(&WelcomeV30 {
            version: "3.0".to_string(),
            ..old
        })
        .unwrap();
        let new: WelcomeMessage = serde_json::from_str(&v30).unwrap();
        assert_eq!(new.instance_name, None);
    }

    #[test]
    fn post_link_reply_shapes() {
        let cases = [
            (PostLinkReply::Erased, r#"{"state":"erased"}"#),
            (
                PostLinkReply::Written { len: 1472 },
                r#"{"state":"written","len":1472}"#,
            ),
            (PostLinkReply::Malformed, r#"{"state":"malformed"}"#),
        ];
        for (reply, json) in cases {
            assert_eq!(serde_json::to_string(&reply).unwrap(), json);
            assert_eq!(serde_json::from_str::<PostLinkReply>(json).unwrap(), reply);
        }
    }

    #[test]
    fn version_compatible_matches_on_major() {
        // Same major (current + a hypothetical future minor) → compatible.
        assert!(version_compatible(PROTOCOL_VERSION));
        assert!(version_compatible("4.0"));
        assert!(version_compatible("4.7"));
        assert!(version_compatible("4")); // bare major

        // Older majors → refused: 3.x has no write stamps (`ts`), 2.x is the
        // legacy WS-era wire.
        assert!(!version_compatible("3.1"));
        assert!(!version_compatible("3.0"));
        assert!(!version_compatible("2.0"));
        assert!(!version_compatible("1.0"));

        // Missing / malformed → fail closed.
        assert!(!version_compatible(""));
        assert!(!version_compatible(".0"));
        assert!(!version_compatible("garbage"));
    }

    #[test]
    fn test_request_serialization() {
        let request = Request {
            id: 1,
            method: "record.list".to_string(),
            params: Some(serde_json::json!({})),
        };

        let json = serde_json::to_string(&request).unwrap();
        assert!(json.contains("\"id\":1"));
        assert!(json.contains("\"method\":\"record.list\""));
    }

    #[test]
    fn test_response_success() {
        let response = Response::success(1, serde_json::json!({"status": "ok"}));

        let json = serde_json::to_string(&response).unwrap();
        assert!(json.contains("\"id\":1"));
        assert!(json.contains("\"result\""));
        assert!(json.contains("\"status\":\"ok\""));
    }

    #[test]
    fn test_response_error() {
        let response = Response::error(2, "NOT_FOUND", "Record not found");

        let json = serde_json::to_string(&response).unwrap();
        assert!(json.contains("\"id\":2"));
        assert!(json.contains("\"error\""));
        assert!(json.contains("\"code\":\"NOT_FOUND\""));
        assert!(json.contains("\"message\":\"Record not found\""));
    }

    #[test]
    fn test_event_serialization() {
        let event = Event {
            subscription_id: "sub-123".to_string(),
            sequence: 42,
            data: serde_json::json!({"temp": 23.5}),
            timestamp: "1730379296.123456789".to_string(),
            dropped: None,
        };

        let json = serde_json::to_string(&event).unwrap();
        assert!(json.contains("\"subscription_id\":\"sub-123\""));
        assert!(json.contains("\"sequence\":42"));
        assert!(json.contains("\"temp\":23.5"));
    }

    #[test]
    fn test_event_with_dropped() {
        let event = Event {
            subscription_id: "sub-456".to_string(),
            sequence: 100,
            data: serde_json::json!({"value": 1}),
            timestamp: "1730379300.987654321".to_string(),
            dropped: Some(5),
        };

        let json = serde_json::to_string(&event).unwrap();
        assert!(json.contains("\"dropped\":5"));
    }
}