Skip to main content

aimdb_core/remote/
metadata.rs

1//! Record metadata types for remote introspection (feature `remote`).
2//!
3//! [`RecordMetadata`] describes a registered record's runtime state — buffer
4//! configuration, producer/consumer counts, the `writable` flag, and
5//! (feature-gated) buffer metrics / stage profiling — for the AimX `record.list`
6//! response. Computed on demand from a record's static structure; core keeps no
7//! per-record metadata state.
8
9use alloc::format;
10use alloc::string::{String, ToString};
11use alloc::vec::Vec;
12use core::any::TypeId;
13use serde::{Deserialize, Serialize};
14
15use crate::graph::RecordOrigin;
16use crate::record_id::{RecordId, RecordKey};
17
18/// Metadata about a registered record type
19///
20/// Provides information for remote introspection, including buffer
21/// configuration and producer/consumer counts.
22///
23/// When the `observability` feature is enabled, additional fields are included
24/// for buffer-level statistics (produced_count, consumed_count, etc.).
25///
26/// # Liveness is an observability extra
27///
28/// A `record.list` reply enumerates records the server **registered**, not
29/// records that have carried a value — a server registering a fixed pool up
30/// front lists the whole pool. Only `produced_count` distinguishes them, and
31/// it is `observability`-gated by design (liveness
32/// derives from buffer counters, which constrained targets compile away). So a
33/// server whose clients need that distinction must be built with
34/// `observability` on; without it the honest client answer is "unknown".
35#[derive(Debug, Clone, Serialize, Deserialize)]
36#[non_exhaustive]
37pub struct RecordMetadata {
38    /// Unique record identifier (index in the storage)
39    pub record_id: u32,
40
41    /// Unique record key (stable identifier for lookup)
42    pub record_key: String,
43
44    /// Record type name (Rust type name)
45    pub name: String,
46
47    /// TypeId as hexadecimal string
48    pub type_id: String,
49
50    /// How the record gets its values (Source, Link, Transform, Passive)
51    pub origin: RecordOrigin,
52
53    /// Buffer type: "spmc_ring", "single_latest", "mailbox", or "none"
54    pub buffer_type: String,
55
56    /// Buffer capacity (None for unbounded or no buffer)
57    #[serde(skip_serializing_if = "Option::is_none")]
58    pub buffer_capacity: Option<usize>,
59
60    /// Number of registered producer services
61    pub producer_count: usize,
62
63    /// Number of registered consumer services
64    pub consumer_count: usize,
65
66    /// Whether write operations are permitted for this record
67    pub writable: bool,
68
69    /// Number of outbound connector links registered
70    pub outbound_connector_count: usize,
71
72    /// Data-contract schema name (e.g. `"temperature"`). Set from the schema
73    /// the record was configured with (`RecordRegistrar::schema`, filled by
74    /// `aimdb-data-contracts` from `SchemaType`); otherwise a serving dispatch
75    /// that owns a schema registry may fill it (the WebSocket connector's
76    /// `StreamableRegistry`).
77    #[serde(default, skip_serializing_if = "Option::is_none")]
78    pub schema_type: Option<String>,
79
80    /// Version of the schema named by `schema_type`, when the record was
81    /// configured with one.
82    #[serde(default, skip_serializing_if = "Option::is_none")]
83    pub schema_version: Option<u32>,
84
85    /// The record key's **leaf segment** — everything after the last `.` or `/`
86    /// (`"vienna"` for `"temp.vienna"` or `"sensors/temp/vienna"`).
87    ///
88    /// Only an entity identifier where the leaf *is* the node. Under a deeper
89    /// scheme it is not: `"station.17.temperature"` yields `"temperature"`, not
90    /// the `"17"` a caller wants — such clients must parse the key themselves.
91    #[serde(default, skip_serializing_if = "Option::is_none")]
92    pub entity: Option<String>,
93
94    /// The record's key table, when it has keyed inbound links.
95    #[serde(default, skip_serializing_if = "Option::is_none")]
96    pub inbound_keys: Option<InboundKeysInfo>,
97
98    // ===== Buffer metrics (feature-gated) =====
99    /// Total items pushed to the buffer (metrics feature only).
100    ///
101    /// Doubles as the liveness signal: `> 0` has carried a value, `0` is an
102    /// untouched registration, absent is unknowable (see the type-level note).
103    #[cfg(feature = "observability")]
104    #[serde(skip_serializing_if = "Option::is_none")]
105    pub produced_count: Option<u64>,
106
107    /// Total items consumed from the buffer (metrics feature only)
108    #[cfg(feature = "observability")]
109    #[serde(skip_serializing_if = "Option::is_none")]
110    pub consumed_count: Option<u64>,
111
112    /// Total items dropped due to overflow/lag (metrics feature only)
113    #[cfg(feature = "observability")]
114    #[serde(skip_serializing_if = "Option::is_none")]
115    pub dropped_count: Option<u64>,
116
117    /// Current buffer occupancy: (items, capacity) (metrics feature only)
118    #[cfg(feature = "observability")]
119    #[serde(skip_serializing_if = "Option::is_none")]
120    pub occupancy: Option<(usize, usize)>,
121
122    // ===== Stage profiling (feature-gated) =====
123    /// Per-stage timing metrics (`.source()`/`.tap()`/`.link()`), if the
124    /// `observability` feature is enabled and any stage has been registered.
125    #[cfg(feature = "observability")]
126    #[serde(skip_serializing_if = "Option::is_none")]
127    pub stage_profiling: Option<Vec<crate::profiling::StageProfilingInfo>>,
128
129    // ===== Signal gauges (feature-gated) =====
130    /// Per-record domain-signal statistics (last/min/max/mean) fed by
131    /// `Observable::observe()`, if the `observability` feature is enabled and any
132    /// gauge has been registered.
133    #[cfg(feature = "observability")]
134    #[serde(skip_serializing_if = "Option::is_none")]
135    pub signal_stats: Option<Vec<crate::profiling::SignalStatsInfo>>,
136}
137
138/// A record's key table. Key names are not listed; `inbound_key_name`
139/// resolves one.
140#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
141#[non_exhaustive]
142pub struct InboundKeysInfo {
143    /// The keyed capture of each keyed link.
144    pub captures: Vec<String>,
145    pub capacity: u16,
146    pub assigned: usize,
147    /// Messages turned away because the table was full, once per matching
148    /// keyed link.
149    pub dropped: u32,
150}
151
152impl RecordMetadata {
153    /// Creates a new record metadata entry
154    ///
155    /// # Arguments
156    /// * `record_id` - The RecordId index
157    /// * `record_key` - The unique record key
158    /// * `type_id` - The TypeId of the record
159    /// * `name` - The Rust type name
160    /// * `origin` - How the record gets its values (Source, Link, Transform, Passive)
161    /// * `buffer_type` - Buffer type string
162    /// * `buffer_capacity` - Optional buffer capacity
163    /// * `producer_count` - Number of producers
164    /// * `consumer_count` - Number of consumers
165    /// * `writable` - Whether writes are permitted
166    /// * `outbound_connector_count` - Number of outbound connectors
167    #[allow(clippy::too_many_arguments)]
168    pub fn new<K: RecordKey>(
169        record_id: RecordId,
170        record_key: K,
171        type_id: TypeId,
172        name: String,
173        origin: RecordOrigin,
174        buffer_type: String,
175        buffer_capacity: Option<usize>,
176        producer_count: usize,
177        consumer_count: usize,
178        writable: bool,
179        outbound_connector_count: usize,
180    ) -> Self {
181        let entity = Some(super::topic_leaf(record_key.as_str()).to_string());
182        Self {
183            record_id: record_id.raw(),
184            record_key: record_key.as_str().to_string(),
185            name,
186            type_id: format!("{:?}", type_id),
187            origin,
188            buffer_type,
189            buffer_capacity,
190            producer_count,
191            consumer_count,
192            writable,
193            outbound_connector_count,
194            schema_type: None,
195            schema_version: None,
196            entity,
197            inbound_keys: None,
198            #[cfg(feature = "observability")]
199            produced_count: None,
200            #[cfg(feature = "observability")]
201            consumed_count: None,
202            #[cfg(feature = "observability")]
203            dropped_count: None,
204            #[cfg(feature = "observability")]
205            occupancy: None,
206            #[cfg(feature = "observability")]
207            stage_profiling: None,
208            #[cfg(feature = "observability")]
209            signal_stats: None,
210        }
211    }
212
213    /// Sets `schema_type` and `schema_version` from the record's schema, if
214    /// it has one.
215    pub fn with_schema(mut self, schema: Option<&crate::graph::SchemaInfo>) -> Self {
216        if let Some(schema) = schema {
217            self.schema_type = Some(schema.name.clone());
218            self.schema_version = Some(schema.version);
219        }
220        self
221    }
222
223    /// Sets buffer metrics from a snapshot (metrics feature only)
224    ///
225    /// Populates produced_count, consumed_count, dropped_count, and occupancy
226    /// from the provided metrics snapshot.
227    #[cfg(feature = "observability")]
228    pub fn with_buffer_metrics(mut self, snapshot: crate::buffer::BufferMetricsSnapshot) -> Self {
229        self.produced_count = Some(snapshot.produced_count);
230        self.consumed_count = Some(snapshot.consumed_count);
231        self.dropped_count = Some(snapshot.dropped_count);
232        // Only include occupancy if it's meaningful (non-zero capacity)
233        if snapshot.occupancy.1 > 0 {
234            self.occupancy = Some(snapshot.occupancy);
235        }
236        self
237    }
238
239    /// Attaches a stage profiling snapshot (profiling feature only).
240    #[cfg(feature = "observability")]
241    pub fn with_stage_profiling(
242        mut self,
243        stages: Vec<crate::profiling::StageProfilingInfo>,
244    ) -> Self {
245        if !stages.is_empty() {
246            self.stage_profiling = Some(stages);
247        }
248        self
249    }
250
251    /// Attaches a signal-gauge snapshot (observability feature only).
252    #[cfg(feature = "observability")]
253    pub fn with_signal_stats(mut self, signals: Vec<crate::profiling::SignalStatsInfo>) -> Self {
254        if !signals.is_empty() {
255            self.signal_stats = Some(signals);
256        }
257        self
258    }
259}
260
261#[cfg(test)]
262mod tests {
263    use super::*;
264    use crate::record_id::StringKey;
265
266    #[test]
267    fn test_record_metadata_creation() {
268        let type_id = TypeId::of::<i32>();
269        let metadata = RecordMetadata::new(
270            RecordId::new(0),
271            StringKey::new("test.record"),
272            type_id,
273            "i32".to_string(),
274            RecordOrigin::Source,
275            "spmc_ring".to_string(),
276            Some(100),
277            1,
278            2,
279            false,
280            0,
281        );
282
283        assert_eq!(metadata.record_id, 0);
284        assert_eq!(metadata.record_key, "test.record");
285        assert_eq!(metadata.name, "i32");
286        assert!(matches!(metadata.origin, RecordOrigin::Source));
287        assert_eq!(metadata.buffer_type, "spmc_ring");
288        assert_eq!(metadata.buffer_capacity, Some(100));
289        assert_eq!(metadata.producer_count, 1);
290        assert_eq!(metadata.consumer_count, 2);
291        assert_eq!(metadata.outbound_connector_count, 0);
292        assert!(!metadata.writable);
293    }
294
295    #[test]
296    fn test_record_metadata_serialization() {
297        let type_id = TypeId::of::<String>();
298        let metadata = RecordMetadata::new(
299            RecordId::new(1),
300            StringKey::new("app.config"),
301            type_id,
302            "String".to_string(),
303            RecordOrigin::Passive,
304            "single_latest".to_string(),
305            None,
306            1,
307            1,
308            true,
309            2,
310        );
311
312        let json = serde_json::to_string(&metadata).unwrap();
313        assert!(json.contains("\"record_id\":1"));
314        assert!(json.contains("\"record_key\":\"app.config\""));
315        assert!(json.contains("\"name\":\"String\""));
316        assert!(json.contains("\"origin\":\"passive\""));
317        assert!(json.contains("\"buffer_type\":\"single_latest\""));
318        assert!(json.contains("\"writable\":true"));
319        assert!(json.contains("\"outbound_connector_count\":2"));
320        assert!(!json.contains("inbound_keys"));
321    }
322
323    #[test]
324    fn inbound_keys_are_optional_on_the_wire() {
325        let mut metadata = RecordMetadata::new(
326            RecordId::new(0),
327            StringKey::new("sensors.readings"),
328            TypeId::of::<i32>(),
329            "i32".to_string(),
330            RecordOrigin::Passive,
331            "spmc_ring".to_string(),
332            Some(256),
333            0,
334            0,
335            false,
336            0,
337        );
338
339        // An older server's reply has no `inbound_keys`.
340        let json = serde_json::to_string(&metadata).unwrap();
341        let old: RecordMetadata = serde_json::from_str(&json).unwrap();
342        assert_eq!(old.inbound_keys, None);
343
344        let keys = InboundKeysInfo {
345            captures: alloc::vec!["device".to_string()],
346            capacity: 1024,
347            assigned: 3,
348            dropped: 1,
349        };
350        metadata.inbound_keys = Some(keys.clone());
351        let json = serde_json::to_string(&metadata).unwrap();
352        let parsed: RecordMetadata = serde_json::from_str(&json).unwrap();
353        assert_eq!(parsed.inbound_keys, Some(keys));
354    }
355}