Skip to main content

aimdb_core/session/aimx/
dispatch.rs

1//! AimX server dispatch (`no_std + alloc`; features `connector-session` +
2//! `remote`) — the method semantics of AimX remote access, served on the
3//! shared session engine (`serve`/`run_session`).
4//!
5//! Reaches into core's `record.list` / JSON API (the `AnyRecord` JSON + metadata
6//! methods), which are gated on `remote` and de-std'd alongside this
7//! dispatch, so a board can serve a host over serial. A transport pairs this
8//! dispatch with the generic
9//! [`SessionServerConnector`](crate::session::SessionServerConnector) — see
10//! `aimdb-uds-connector`'s `UdsServer`.
11//!
12//! The role is split in two:
13//! - [`AimxDispatch`] — the shared half (one `Arc` per server): peer-only
14//!   `authenticate` + an `open` factory.
15//! - `AimxSession` — the per-connection half the engine owns by value, homing
16//!   `record.drain`'s lazy per-record cursors (`drain_readers`).
17//!
18//! Param shapes follow the client ([`aimdb_client::AimxConnection`]):
19//! `record.get`/`record.set` take `{name[, value]}`, `write` takes `{value}`.
20
21use crate::session::events::{report, SessionEvent};
22
23use alloc::boxed::Box;
24use alloc::string::{String, ToString};
25use alloc::sync::Arc;
26use alloc::vec;
27use alloc::vec::Vec;
28use hashbrown::HashMap;
29
30use serde_json::{json, Value};
31
32use futures_util::StreamExt;
33
34use crate::buffer::JsonBufferReader;
35use crate::remote::{AimxConfig, RecordMetadata, SecurityPolicy, WelcomeMessage, PROTOCOL_VERSION};
36use crate::session::{
37    is_wildcard, topic_matches, AuthError, BoxFut, BoxStream, Dispatch, Payload, PeerInfo,
38    RpcError, Session, SessionCtx, SubUpdate,
39};
40use crate::{AimDb, DbError, Stamped};
41
42/// The shared AimX dispatch — `authenticate` (peer-only) + the `AimxSession`
43/// factory. One `Arc<AimxDispatch>` is shared across every accepted connection.
44pub struct AimxDispatch {
45    db: Arc<AimDb>,
46    config: Arc<AimxConfig>,
47}
48
49impl AimxDispatch {
50    /// Build a dispatch over `db` with the given remote-access `config`.
51    pub fn new(db: Arc<AimDb>, config: AimxConfig) -> Self {
52        Self {
53            db,
54            config: Arc::new(config),
55        }
56    }
57}
58
59impl Dispatch for AimxDispatch {
60    fn authenticate<'a>(
61        &'a self,
62        _peer: &'a PeerInfo,
63        _first: Option<&'a [u8]>,
64    ) -> BoxFut<'a, Result<SessionCtx, AuthError>> {
65        // Peer-only: AimX over UDS relies on socket file permissions for access
66        // control. Permission policy (ReadOnly / writable_records) is enforced
67        // per-call from the config.
68        Box::pin(async { Ok(SessionCtx::default()) })
69    }
70
71    fn open(&self, _ctx: &SessionCtx) -> Box<dyn Session> {
72        Box::new(AimxSession {
73            db: self.db.clone(),
74            config: self.config.clone(),
75            drain_readers: HashMap::new(),
76        })
77    }
78}
79
80/// One AimX connection's mutable dispatch state. The engine owns this by value
81/// and threads `&mut self` into each method, so `drain_readers` (lazy per-record
82/// cursors) need no lock.
83struct AimxSession {
84    db: Arc<AimDb>,
85    config: Arc<AimxConfig>,
86    /// Per-record drain readers, created lazily on first `record.drain`.
87    drain_readers: HashMap<String, Box<dyn JsonBufferReader + Send>>,
88}
89
90/// Internal dispatch result. Most methods still build a JSON tree; hot record
91/// paths can hand already-serialized JSON to the session engine.
92enum DispatchReply {
93    Value(Value),
94    RawJson(Payload),
95}
96
97impl DispatchReply {
98    fn into_payload(self) -> Payload {
99        match self {
100            Self::Value(value) => to_payload(&value),
101            Self::RawJson(payload) => payload,
102        }
103    }
104}
105
106impl Session for AimxSession {
107    /// `hello` opens every AimX session; a second one on a connection comes
108    /// from a new client (a serial line never closes between clients).
109    fn starts_session(&self, method: &str) -> bool {
110        method == "hello"
111    }
112
113    fn call<'a>(
114        &'a mut self,
115        method: &'a str,
116        params: Payload,
117    ) -> BoxFut<'a, Result<Payload, RpcError>> {
118        Box::pin(async move {
119            let params: Value = serde_json::from_slice(&params).unwrap_or(Value::Null);
120            self.dispatch_call(method, params)
121                .await
122                .map(DispatchReply::into_payload)
123        })
124    }
125
126    fn subscribe<'a>(
127        &'a mut self,
128        topic: &'a str,
129    ) -> BoxFut<'a, Result<BoxStream<'static, SubUpdate>, RpcError>> {
130        // The engine owns the subscription lifecycle and the per-connection cap;
131        // AimX has no async authorization, so this is a trivial wrapper.
132        Box::pin(async move {
133            if is_wildcard(topic) {
134                return Ok(self.subscribe_wildcard(topic));
135            }
136            // Exact-topic fast path: resolve one key, untagged updates.
137            let stream = crate::remote::stream::stream_record_updates(&self.db, topic)
138                .map_err(map_db_err)?;
139            Ok(Box::pin(
140                stream.map(|(data, ts, skipped)| SubUpdate::new(data, ts).with_skipped(skipped)),
141            ) as BoxStream<'static, SubUpdate>)
142        })
143    }
144
145    fn snapshots(&mut self, topic: &str) -> Vec<(String, Payload, crate::Stamp)> {
146        // Late-join state for wildcard subscriptions: the current value of every
147        // matched record that has one. Exact-topic AimX subscribes stay
148        // event-only (unchanged wire for UDS/serial/TCP clients).
149        if !is_wildcard(topic) {
150            return Vec::new();
151        }
152        self.matched_keys(topic)
153            .into_iter()
154            .filter_map(|key| {
155                let sample = self.db.try_latest_as_json(&key)?;
156                Some((key, to_payload(&sample.value), sample.stamp()))
157            })
158            .collect()
159    }
160
161    fn write<'a>(
162        &'a mut self,
163        topic: &'a str,
164        payload: Payload,
165    ) -> BoxFut<'a, Result<(), RpcError>> {
166        Box::pin(async move {
167            self.ensure_writable(topic)?;
168            // The v2 client wraps the value as `{"value": <v>}`; fall back to the
169            // whole payload if the wrapper is absent.
170            let v: Value = serde_json::from_slice(&payload).unwrap_or(Value::Null);
171            let value = v.get("value").cloned().unwrap_or(v);
172            // Routes through the producer/arbiter path — single-writer-per-key
173            // stays enforced inside `set_record_from_json`.
174            self.db
175                .set_record_from_json(topic, value)
176                .map_err(map_db_err)
177        })
178    }
179}
180
181impl AimxSession {
182    /// Record keys matching a wildcard pattern. The record set is frozen at
183    /// builder time, so matching once at subscribe time is complete — dynamic
184    /// membership would require runtime registration.
185    fn matched_keys(&self, pattern: &str) -> Vec<String> {
186        self.db
187            .list_records()
188            .into_iter()
189            .map(|m: RecordMetadata| m.record_key)
190            .filter(|key| topic_matches(pattern, key))
191            .collect()
192    }
193
194    /// One wildcard subscription fans in every matched record's update stream,
195    /// each event tagged with the record that fired. Records without remote
196    /// access are skipped — the subscription covers what can stream.
197    fn subscribe_wildcard(&self, pattern: &str) -> BoxStream<'static, SubUpdate> {
198        let mut streams: Vec<BoxStream<'static, SubUpdate>> = Vec::new();
199        for key in self.matched_keys(pattern) {
200            match crate::remote::stream::stream_record_updates(&self.db, &key) {
201                Ok(stream) => {
202                    let tag: Arc<str> = Arc::from(key.as_str());
203                    streams.push(Box::pin(stream.map(move |(data, ts, skipped)| {
204                        SubUpdate::tagged(tag.clone(), data, ts).with_skipped(skipped)
205                    })));
206                }
207                Err(_e) => {
208                    report(SessionEvent::WildcardSubscribeFailed {
209                        pattern,
210                        record: &key,
211                        error: &_e,
212                    });
213                }
214            }
215        }
216        // An empty match set yields a stream that ends immediately — with a
217        // builder-frozen record set, "no matches now" is "no matches ever".
218        Box::pin(futures_util::stream::select_all(streams))
219    }
220
221    /// Match the method and produce a tree or already-serialized JSON reply.
222    async fn dispatch_call(
223        &mut self,
224        method: &str,
225        params: Value,
226    ) -> Result<DispatchReply, RpcError> {
227        // Hot record read: hand already-serialized JSON straight to the engine,
228        // skipping the `serde_json::Value` round-trip (main's clone-avoidance).
229        if method == "record.get" {
230            let name = str_field(&params, "name").ok_or(RpcError::NotFound)?;
231            return self.record_get(&name).map(DispatchReply::RawJson);
232        }
233        // Identity (3.1): built as JSON bytes, the build-info payload spliced in.
234        if method == "instance.info" {
235            let reply = crate::remote::instance_info_reply(&self.db);
236            return Ok(DispatchReply::RawJson(Payload::from(reply.as_slice())));
237        }
238        if method == "instance.post_link" {
239            return crate::remote::post_link_chunk_reply(&self.db, &params)
240                .map(|reply| DispatchReply::RawJson(Payload::from(reply.as_slice())))
241                .map_err(map_post_link_err);
242        }
243
244        let value = match method {
245            // Version gate: refuse an incompatible/absent client version at the
246            // handshake rather than letting it trip over the new wire shapes.
247            "hello" => self.hello(params),
248            "record.list" => Ok(json!(self.db.list_records())),
249            "record.set" => self.record_set(params),
250            "record.drain" => self.record_drain(params),
251            "record.query" => self
252                .record_query(params)?
253                .await
254                .map_err(|_| RpcError::Internal),
255            "graph.nodes" => Ok(json!(self.db.inner().dependency_graph().nodes)),
256            "graph.edges" => Ok(json!(self.db.inner().dependency_graph().edges)),
257            "graph.topo_order" => Ok(json!(self.db.inner().dependency_graph().topo_order())),
258            #[cfg(feature = "observability")]
259            "profiling.reset" => {
260                self.ensure_write_permission()?;
261                self.db.reset_stage_profiling();
262                Ok(json!({ "reset": true }))
263            }
264            #[cfg(feature = "observability")]
265            "buffer_metrics.reset" => {
266                self.ensure_write_permission()?;
267                self.db.reset_buffer_metrics();
268                Ok(json!({ "reset": true }))
269            }
270            _ => Err(RpcError::NotFound),
271        }?;
272
273        Ok(DispatchReply::Value(value))
274    }
275
276    /// `record.set` (RPC): permission-checked write that echoes the new value
277    /// and its write stamp: `{status, value, ts}`, or `{status}` when the
278    /// record has no readable latest value (a ring).
279    ///
280    /// The echo is one read after the write, so under concurrent writers it can
281    /// be a newer write than this call's (design 058 §5.1).
282    fn record_set(&self, params: Value) -> Result<Value, RpcError> {
283        let name = str_field(&params, "name").ok_or(RpcError::Internal)?;
284        let value = params.get("value").cloned().ok_or(RpcError::Internal)?;
285        self.ensure_writable(&name)?;
286        self.db
287            .set_record_from_json(&name, value)
288            .map_err(map_db_err)?;
289        Ok(match self.db.try_latest_as_json(&name) {
290            Some(updated) => json!({
291                "status": "success",
292                "ts": updated.stamp().as_nanos(),
293                "value": updated.value,
294            }),
295            None => json!({ "status": "success" }),
296        })
297    }
298
299    /// `record.get`: the record's current value and its write stamp,
300    /// `{"value": <value>, "ts": <ns>}`.
301    ///
302    /// A `SingleLatest`/state record exposes a non-destructive canonical latest
303    /// ([`try_latest_as_json_bytes`](crate::AimDb::try_latest_as_json_bytes)).
304    /// A ring
305    /// ([`SpmcRing`](crate::buffer::BufferCfg::SpmcRing)) has none, so we fall back
306    /// to the connection's drain cursor and return the **most recent** available
307    /// value. Two consequences of that fallback: it *advances the shared drain
308    /// cursor* (so `record.get` and `record.drain` interleave on one connection),
309    /// and it yields `NotFound` until the ring produces a value *after* the cursor
310    /// is first opened (a fresh broadcast reader starts at the tail). Use
311    /// `record.drain` for a ring's full backlog.
312    fn record_get(&mut self, name: &str) -> Result<Payload, RpcError> {
313        if let Some(sample) = self.db.try_latest_as_json_bytes(name) {
314            return Ok(super::value_reply(&sample.value, sample.stamp()));
315        }
316        // Ring fallback: drain to the newest currently-available value (or NotFound).
317        self.drain_values(name, usize::MAX)?
318            .pop()
319            .map(|sample| to_payload(&stamped_value_json(sample)))
320            .ok_or(RpcError::NotFound)
321    }
322
323    /// `record.drain`: return everything accumulated since the previous drain
324    /// (capped by an optional `limit`), via the per-connection cursor.
325    fn record_drain(&mut self, params: Value) -> Result<Value, RpcError> {
326        let name = str_field(&params, "name").ok_or(RpcError::Internal)?;
327        let limit = params
328            .get("limit")
329            .and_then(|v| v.as_u64())
330            .map(|v| usize::try_from(v).unwrap_or(usize::MAX))
331            .unwrap_or(usize::MAX);
332        let values: Vec<Value> = self
333            .drain_values(&name, limit)?
334            .into_iter()
335            .map(stamped_value_json)
336            .collect();
337        let count = values.len();
338        Ok(json!({ "record_name": name, "values": values, "count": count }))
339    }
340
341    /// Lazily open (on first call) the per-record drain cursor and read up to
342    /// `limit` values accumulated since the previous read (oldest-first). Shared
343    /// by [`record.drain`](Self::record_drain) and [`record.get`](Self::record_get)'s
344    /// ring fallback, so both read from the same per-connection cursor.
345    fn drain_values(&mut self, name: &str, limit: usize) -> Result<Vec<Stamped<Value>>, RpcError> {
346        if !self.drain_readers.contains_key(name) {
347            let id = self
348                .db
349                .inner()
350                .resolve_str(name)
351                .ok_or(RpcError::NotFound)?;
352            let record = self.db.inner().storage(id).ok_or(RpcError::NotFound)?;
353            // `subscribe_json` fails if the record was not configured with
354            // `.with_remote_access()`.
355            let reader = record
356                .json_access()
357                .ok_or_else(|| {
358                    map_db_err(DbError::runtime_error(alloc::format!(
359                        "Record '{name}' does not support JSON remote access"
360                    )))
361                })?
362                .subscribe_json()
363                .map_err(map_db_err)?;
364            self.drain_readers.insert(name.to_string(), reader);
365        }
366
367        // Unreachable, but reported rather than asserted: this is the session
368        // pump.
369        let reader = self.drain_readers.get_mut(name).ok_or_else(|| {
370            map_db_err(DbError::runtime_error(alloc::format!(
371                "Record '{name}' drain reader vanished between insert and use"
372            )))
373        })?;
374        let mut values = Vec::new();
375        while values.len() < limit {
376            match reader.try_recv_json() {
377                Ok(sample) => values.push(sample),
378                Err(DbError::BufferEmpty) => break,
379                // Ring overflowed since the last read — cursor resets; keep going.
380                Err(DbError::BufferLagged { .. }) => continue,
381                Err(_) => break,
382            }
383        }
384        Ok(values)
385    }
386
387    /// `record.query`: resolve the persistence query handler registered in the
388    /// db's `Extensions` (absent → not configured) and return its handler
389    /// future.
390    ///
391    /// Deliberately **not** an `async fn`: an `async fn(&self)` future would
392    /// capture `&self` across its await, forcing `AimxSession: Sync` — which the
393    /// per-connection `drain_readers` (`Box<dyn _ + Send>`, not `Sync`) is not.
394    /// Returning the (`'static`, `Send`) handler future lets the borrow of
395    /// `self` end here; the caller awaits the owned future.
396    #[allow(clippy::type_complexity)]
397    fn record_query(
398        &self,
399        params: Value,
400    ) -> Result<
401        core::pin::Pin<
402            Box<dyn core::future::Future<Output = Result<Value, String>> + Send + 'static>,
403        >,
404        RpcError,
405    > {
406        let handler = self
407            .db
408            .extensions()
409            .get::<crate::remote::QueryHandlerFn>()
410            .ok_or(RpcError::Internal)?;
411        let name = params
412            .get("name")
413            .and_then(|v| v.as_str())
414            .unwrap_or(crate::remote::QUERY_ALL_PATTERN)
415            .to_string();
416        let limit = params
417            .get("limit")
418            .and_then(|v| v.as_u64())
419            .and_then(|v| usize::try_from(v).ok());
420        let start = params.get("start").and_then(|v| v.as_u64());
421        let end = params.get("end").and_then(|v| v.as_u64());
422        Ok(handler(crate::remote::QueryHandlerParams {
423            name,
424            limit,
425            start,
426            end,
427        }))
428    }
429
430    /// `hello`: the version-gated handshake.
431    ///
432    /// The client's declared `version` must be major-compatible with this
433    /// server's [`PROTOCOL_VERSION`] ([`version_compatible`](crate::remote::version_compatible)).
434    /// A pre-3.x — or version-less — client is refused **here** with
435    /// [`RpcError::VersionMismatch`], rather than completing the handshake and
436    /// letting the client trip over the new `reply`/`event` shapes on its first
437    /// `record.query` — a hard refusal at `hello`.
438    fn hello(&self, params: Value) -> Result<Value, RpcError> {
439        let version = str_field(&params, "version").unwrap_or_default();
440        if !crate::remote::version_compatible(&version) {
441            report(SessionEvent::HandshakeVersionRejected {
442                client_version: &version,
443                server_version: PROTOCOL_VERSION,
444            });
445            return Err(RpcError::VersionMismatch);
446        }
447        Ok(self.welcome())
448    }
449
450    /// Build the `Welcome` from the security policy + writable records.
451    ///
452    /// `writable_records` is derived from the policy directly and intersected with
453    /// the records that actually exist, so the server never advertises a phantom key.
454    fn welcome(&self) -> Value {
455        let (permissions, writable_records) = match &self.config.security_policy {
456            SecurityPolicy::ReadOnly => (vec!["read".to_string()], Vec::new()),
457            SecurityPolicy::ReadWrite { writable_records } => {
458                let existing: hashbrown::HashSet<String> = self
459                    .db
460                    .list_records()
461                    .into_iter()
462                    .map(|m: RecordMetadata| m.record_key)
463                    .collect();
464                let writable = writable_records
465                    .iter()
466                    .filter(|name| existing.contains(name.as_str()))
467                    .cloned()
468                    .collect();
469                (vec!["read".to_string(), "write".to_string()], writable)
470            }
471        };
472        let welcome = WelcomeMessage {
473            version: PROTOCOL_VERSION.to_string(),
474            server: "aimdb".to_string(),
475            permissions,
476            writable_records,
477            max_subscriptions: Some(self.config.max_subs_per_connection),
478            authenticated: Some(false),
479            instance_name: self.db.identity().name().map(String::from),
480        };
481        json!(welcome)
482    }
483
484    /// Deny unless the policy is ReadWrite and `name` is in its writable set.
485    fn ensure_writable(&self, name: &str) -> Result<(), RpcError> {
486        match &self.config.security_policy {
487            SecurityPolicy::ReadWrite { writable_records } if writable_records.contains(name) => {
488                Ok(())
489            }
490            _ => Err(RpcError::Denied),
491        }
492    }
493
494    /// Deny under a ReadOnly policy (used by the `*.reset` admin methods).
495    #[cfg(feature = "observability")]
496    fn ensure_write_permission(&self) -> Result<(), RpcError> {
497        match self.config.security_policy {
498            SecurityPolicy::ReadOnly => Err(RpcError::Denied),
499            SecurityPolicy::ReadWrite { .. } => Ok(()),
500        }
501    }
502}
503
504/// A value with its write stamp as the AimX 4.0 reply element
505/// `{"value": <value>, "ts": <ns>}`. The wire carries the stamp explicitly;
506/// other write metadata stays off the wire (design 058 §5).
507fn stamped_value_json(sample: Stamped<Value>) -> Value {
508    let ts = sample.stamp().as_nanos();
509    json!({ "value": sample.value, "ts": ts })
510}
511
512/// Serialize a JSON value into an owned record-value [`Payload`] — one serde
513/// pass at the reply boundary.
514fn to_payload(v: &Value) -> Payload {
515    Payload::from(serde_json::to_vec(v).unwrap_or_default().as_slice())
516}
517
518/// Extract a string field from a params object.
519fn str_field(params: &Value, key: &str) -> Option<String> {
520    params.get(key).and_then(|v| v.as_str()).map(String::from)
521}
522
523/// Map a [`PostLinkError`](crate::remote::PostLinkError) onto the wire's
524/// error set.
525fn map_post_link_err(e: crate::remote::PostLinkError) -> RpcError {
526    match e {
527        crate::remote::PostLinkError::NotWritten => RpcError::NotFound,
528        crate::remote::PostLinkError::InvalidParams => RpcError::Internal,
529    }
530}
531
532/// Map a [`DbError`] onto the reshaped wire's coarse [`RpcError`] set.
533fn map_db_err(e: DbError) -> RpcError {
534    match e {
535        DbError::RecordKeyNotFound { .. } | DbError::InvalidRecordId { .. } => RpcError::NotFound,
536        DbError::PermissionDenied { .. } => RpcError::Denied,
537        _ => RpcError::Internal,
538    }
539}
540
541#[cfg(test)]
542mod tests {
543    use super::*;
544    use crate::remote::{QueryHandlerFn, QUERY_ALL_PATTERN};
545    use std::sync::Mutex;
546
547    /// `record.query` with no `name` must reach the handler as the same pattern
548    /// on every transport. It is a *record set*, not a formatting detail: under
549    /// the MQTT grammar `*` spans exactly one dot-separated segment, so the old
550    /// default silently dropped every nested record here while the WS connector
551    /// returned them — the same request answering differently per link.
552    ///
553    /// Driven through the real dispatch (`Dispatch::open` → `Session::call`),
554    /// since the defaulting lives in `record_query`, not at the wire edge. The
555    /// WS dispatch defaults through the same constant, so the two cannot
556    /// drift again.
557    #[tokio::test]
558    async fn an_omitted_query_name_spans_every_record() {
559        static SEEN: Mutex<Option<String>> = Mutex::new(None);
560
561        let handler: QueryHandlerFn = Box::new(|params| {
562            *SEEN.lock().expect("uncontended") = Some(params.name.clone());
563            Box::pin(async { Ok(json!({ "records": [], "total": 0 })) })
564        });
565
566        let mut builder = crate::AimDbBuilder::new()
567            .runtime(Arc::new(crate::executor::test_support::NoopRuntimeOps));
568        builder.extensions_mut().insert(handler);
569        let (db, _runner) = builder.build().await.expect("build db");
570
571        let dispatch = AimxDispatch::new(Arc::new(db), AimxConfig::uds_default());
572        let mut session = dispatch.open(&SessionCtx::default());
573        session
574            .call("record.query", to_payload(&json!({})))
575            .await
576            .expect("the query resolves");
577
578        assert_eq!(
579            SEEN.lock().expect("uncontended").as_deref(),
580            Some(QUERY_ALL_PATTERN),
581            "an omitted name must span every record, at every depth"
582        );
583    }
584    #[cfg(feature = "std")]
585    #[tokio::test]
586    async fn protocol_and_wildcard_failures_are_typed() {
587        let mut builder = crate::AimDbBuilder::new()
588            .runtime(Arc::new(crate::executor::test_support::NoopRuntimeOps));
589        // Listed metadata, but no JSON access: wildcard subscribe must skip it.
590        builder.configure::<u32>("plain", |reg| {
591            reg.buffer_cfg(crate::buffer::BufferCfg::SingleLatest);
592        });
593        let (db, _runner) = builder.build().await.expect("build db");
594        let dispatch = AimxDispatch::new(Arc::new(db), AimxConfig::uds_default());
595        let mut session = dispatch.open(&SessionCtx::default());
596        let seen = Arc::new(Mutex::new(Vec::new()));
597        let observer = {
598            let seen = seen.clone();
599            Arc::new(move |event: &SessionEvent<'_>| {
600                let tag = match event {
601                    SessionEvent::HandshakeVersionRejected {
602                        client_version,
603                        server_version,
604                    } => {
605                        assert_eq!(
606                            (*client_version, *server_version),
607                            ("0.0.0", PROTOCOL_VERSION)
608                        );
609                        "version"
610                    }
611                    SessionEvent::WildcardSubscribeFailed {
612                        pattern,
613                        record,
614                        error,
615                    } => {
616                        assert_eq!((*pattern, *record), ("#", "plain"));
617                        assert!(matches!(error, DbError::RuntimeError { .. }));
618                        "wildcard"
619                    }
620                    other => panic!("unexpected event: {other:?}"),
621                };
622                seen.lock().unwrap().push(tag);
623            })
624        };
625        crate::session::events::capture::future(observer, async {
626            assert_eq!(
627                session
628                    .call("hello", to_payload(&json!({ "version": "0.0.0" })))
629                    .await,
630                Err(RpcError::VersionMismatch)
631            );
632            let mut stream = session.subscribe("#").await.expect("wildcard stream");
633            assert!(stream.next().await.is_none());
634        })
635        .await;
636        assert_eq!(*seen.lock().unwrap(), ["version", "wildcard"]);
637    }
638
639    // ── instance.info / instance.post_link (3.1) ─────────────────────────
640
641    /// The post-link region a test section carries.
642    enum Region<'a> {
643        None,
644        Erased,
645        Written(&'a [u8]),
646        /// A length past the region's end.
647        Malformed,
648    }
649
650    /// A format-1 section around `payload`, by hand, leaked as `section!()`.
651    fn section(payload: &[u8], region: Region<'_>) -> &'static [u8] {
652        let region_len = match region {
653            Region::None => 0,
654            Region::Written(data) => 4 + data.len(),
655            Region::Erased | Region::Malformed => 16,
656        };
657        let region_off = (32 + payload.len()).div_ceil(8) * 8;
658        let total = region_off + region_len;
659        let mut b = vec![0u8; total];
660        b[..8].copy_from_slice(&aimdb_build_info::MAGIC);
661        b[8..10].copy_from_slice(&1u16.to_le_bytes());
662        b[10..12].copy_from_slice(&32u16.to_le_bytes());
663        b[12..16].copy_from_slice(&(payload.len() as u32).to_le_bytes());
664        b[16..20].copy_from_slice(&(region_off as u32).to_le_bytes());
665        b[20..24].copy_from_slice(&(region_len as u32).to_le_bytes());
666        b[24..28].copy_from_slice(&(total as u32).to_le_bytes());
667        b[32..32 + payload.len()].copy_from_slice(payload);
668        b[region_off..].fill(0xFF);
669        match region {
670            Region::Written(data) => {
671                b[region_off..region_off + 4].copy_from_slice(&(data.len() as u32).to_le_bytes());
672                b[region_off + 4..].copy_from_slice(data);
673            }
674            Region::Malformed => {
675                b[region_off..region_off + 4].copy_from_slice(&13u32.to_le_bytes());
676            }
677            Region::None | Region::Erased => {}
678        }
679        Box::leak(b.into_boxed_slice())
680    }
681
682    async fn session_for(builder: crate::AimDbBuilder) -> Box<dyn Session> {
683        let (db, _runner) = builder
684            .runtime(Arc::new(crate::executor::test_support::NoopRuntimeOps))
685            .build()
686            .await
687            .expect("build db");
688        AimxDispatch::new(Arc::new(db), AimxConfig::uds_default()).open(&SessionCtx::default())
689    }
690
691    async fn call_raw(
692        session: &mut Box<dyn Session>,
693        method: &str,
694        params: &[u8],
695    ) -> Result<Vec<u8>, RpcError> {
696        session
697            .call(method, Payload::from(params))
698            .await
699            .map(|p| p.to_vec())
700    }
701
702    async fn call(
703        session: &mut Box<dyn Session>,
704        method: &str,
705        params: Value,
706    ) -> Result<Value, RpcError> {
707        let reply = call_raw(session, method, &serde_json::to_vec(&params).unwrap()).await?;
708        Ok(serde_json::from_slice(&reply).expect("reply is JSON"))
709    }
710
711    const PAYLOAD: &[u8] =
712        br#"{"schema":1,"name":"boiler-gateway","version":"1.4.0","ext":{"board":"h563"}}"#;
713
714    #[tokio::test]
715    async fn instance_info_without_identity() {
716        let mut session = session_for(crate::AimDbBuilder::new()).await;
717        let reply = call(&mut session, "instance.info", Value::Null)
718            .await
719            .unwrap();
720        assert_eq!(
721            reply,
722            json!({
723                "aimdb_version": env!("CARGO_PKG_VERSION"),
724                "instance": { "name": null, "uid": null },
725                "build": null,
726            })
727        );
728        let welcome = call(
729            &mut session,
730            "hello",
731            json!({ "version": PROTOCOL_VERSION }),
732        )
733        .await
734        .unwrap();
735        assert!(welcome.get("instance_name").is_none(), "{welcome}");
736        assert_eq!(
737            call(&mut session, "instance.post_link", json!({})).await,
738            Err(RpcError::NotFound)
739        );
740    }
741
742    #[tokio::test]
743    async fn instance_info_with_identity() {
744        let mut session = session_for(
745            crate::AimDbBuilder::new()
746                .instance_name("gateway-3")
747                .instance_uid(&[0x00, 0x35, 0x00, 0x2e, 0xab])
748                .build_info(section(PAYLOAD, Region::Written(b"signed"))),
749        )
750        .await;
751        let reply = call_raw(&mut session, "instance.info", b"null")
752            .await
753            .unwrap();
754        // The payload is spliced in byte for byte.
755        let text = core::str::from_utf8(&reply).unwrap();
756        assert!(
757            text.contains(core::str::from_utf8(PAYLOAD).unwrap()),
758            "{text}"
759        );
760        let reply: crate::remote::InstanceInfoReply = serde_json::from_slice(&reply).unwrap();
761        assert_eq!(reply.instance.name.as_deref(), Some("gateway-3"));
762        assert_eq!(reply.instance.uid.as_deref(), Some("0035002eab"));
763        let build = reply.build.expect("build");
764        assert_eq!(build.format, 1);
765        assert_eq!(build.info["ext"]["board"], "h563");
766        assert_eq!(
767            build.post_link,
768            Some(crate::remote::PostLinkReply::Written { len: 6 })
769        );
770
771        let welcome = call(
772            &mut session,
773            "hello",
774            json!({ "version": PROTOCOL_VERSION }),
775        )
776        .await
777        .unwrap();
778        assert_eq!(welcome["instance_name"], "gateway-3");
779    }
780
781    #[tokio::test]
782    async fn instance_info_reports_each_region_state() {
783        use crate::remote::PostLinkReply;
784        for (region, expected) in [
785            (Region::None, Value::Null),
786            (Region::Erased, json!({ "state": "erased" })),
787            (
788                Region::Written(b""),
789                json!({ "state": "written", "len": 0 }),
790            ),
791            (Region::Malformed, json!({ "state": "malformed" })),
792        ] {
793            let mut session =
794                session_for(crate::AimDbBuilder::new().build_info(section(b"{}", region))).await;
795            let reply = call(&mut session, "instance.info", json!({}))
796                .await
797                .unwrap();
798            assert_eq!(reply["build"]["post_link"], expected);
799            assert_eq!(reply["build"]["info"], json!({}));
800            // Every state but `written` has nothing to read.
801            let chunk = call(&mut session, "instance.post_link", json!({})).await;
802            match serde_json::from_value::<Option<PostLinkReply>>(expected).unwrap() {
803                Some(PostLinkReply::Written { .. }) => assert!(chunk.is_ok()),
804                _ => assert_eq!(chunk, Err(RpcError::NotFound)),
805            }
806        }
807    }
808
809    async fn chunk(session: &mut Box<dyn Session>, params: Value) -> Value {
810        call(session, "instance.post_link", params).await.unwrap()
811    }
812
813    #[tokio::test]
814    async fn post_link_chunks() {
815        let data: Vec<u8> = (0..1500u32).map(|i| i as u8).collect();
816        let hex = |bytes: &[u8]| {
817            bytes
818                .iter()
819                .map(|b| alloc::format!("{b:02x}"))
820                .collect::<String>()
821        };
822        let mut session = session_for(
823            crate::AimDbBuilder::new().build_info(section(b"{}", Region::Written(&data))),
824        )
825        .await;
826
827        // Defaults: offset 0, 1 KiB; `null` params equal `{}`.
828        for params in [Value::Null, json!({})] {
829            assert_eq!(
830                chunk(&mut session, params).await,
831                json!({ "offset": 0, "total": 1500, "data": hex(&data[..1024]) })
832            );
833        }
834        // The rest, with `len` over the maximum clamped.
835        assert_eq!(
836            chunk(&mut session, json!({ "offset": 1024, "len": u32::MAX })).await,
837            json!({ "offset": 1024, "total": 1500, "data": hex(&data[1024..]) })
838        );
839        assert_eq!(
840            chunk(&mut session, json!({ "offset": 10, "len": 3 })).await,
841            json!({ "offset": 10, "total": 1500, "data": hex(&data[10..13]) })
842        );
843        // `len: 0` and offsets at or past the end: no data, `total` still set.
844        for params in [
845            json!({ "len": 0 }),
846            json!({ "offset": 1500 }),
847            json!({ "offset": u32::MAX, "len": u32::MAX }),
848        ] {
849            let reply = chunk(&mut session, params.clone()).await;
850            assert_eq!(
851                (reply["data"].as_str(), reply["total"].as_u64()),
852                (Some(""), Some(1500)),
853                "{params}"
854            );
855        }
856    }
857
858    #[tokio::test]
859    async fn post_link_rejects_malformed_params_before_the_region() {
860        let written = section(b"{}", Region::Written(b"x"));
861        for builder in [
862            crate::AimDbBuilder::new().build_info(written),
863            // No section: still `internal`, not `not_found`.
864            crate::AimDbBuilder::new(),
865        ] {
866            let mut session = session_for(builder).await;
867            for params in [
868                json!({ "offset": -1 }),
869                json!({ "offset": 1.5 }),
870                json!({ "offset": "0" }),
871                json!({ "offset": null }),
872                json!({ "offset": u64::from(u32::MAX) + 1 }),
873                json!({ "len": -1 }),
874                json!({ "len": 2.0 }),
875                json!({ "len": "8" }),
876                json!({ "len": null }),
877                json!({ "len": u64::from(u32::MAX) + 1 }),
878                json!([0, 8]),
879                json!("offset"),
880                json!(7),
881            ] {
882                assert_eq!(
883                    call(&mut session, "instance.post_link", params.clone()).await,
884                    Err(RpcError::Internal),
885                    "{params}"
886                );
887            }
888        }
889    }
890
891    /// The largest identity the builder accepts stays within
892    /// `INSTANCE_INFO_REPLY_MAX`.
893    #[tokio::test]
894    async fn worst_case_instance_info_fits_the_bound() {
895        let mut payload = vec![b' '; aimdb_build_info::PAYLOAD_MAX];
896        payload[0] = b'{';
897        payload[aimdb_build_info::PAYLOAD_MAX - 1] = b'}';
898        // Control characters escape to `\u00XX`: six bytes each.
899        let name: String = core::iter::repeat_n('\u{1}', crate::identity::NAME_MAX).collect();
900        let mut session = session_for(
901            crate::AimDbBuilder::new()
902                .instance_name(name)
903                .instance_uid(&[0xff; crate::identity::UID_MAX])
904                .build_info(section(&payload, Region::Erased)),
905        )
906        .await;
907        let reply = call_raw(&mut session, "instance.info", b"{}")
908            .await
909            .unwrap();
910        assert!(
911            reply.len() <= crate::remote::INSTANCE_INFO_REPLY_MAX,
912            "{} bytes",
913            reply.len()
914        );
915        assert!(!reply.contains(&b'\n') && !reply.contains(&b'\r'));
916    }
917}