Skip to main content

aimdb_core/
builder.rs

1//! Database builder with type-safe record registration
2//!
3//! Provides `AimDb` and `AimDbBuilder` for constructing databases with
4//! type-safe, self-registering records using the producer-consumer pattern.
5
6use core::any::TypeId;
7use core::fmt::Debug;
8
9use alloc::{
10    boxed::Box,
11    string::{String, ToString},
12    sync::Arc,
13    vec::Vec,
14};
15use hashbrown::HashMap;
16
17use crate::extensions::Extensions;
18use crate::graph::DependencyGraph;
19
20/// Shorthand for a heap-pinned, `Send`, `'static` future — the unit of work
21/// the `AimDbRunner` drives. Canonical definition lives in `crate::executor`.
22pub type BoxFuture = crate::executor::BoxFuture;
23
24/// `on_start` task stored in `AimDbBuilder::start_fns`, invoked at `build()`.
25type StartFnType = Box<dyn FnOnce(crate::RuntimeContext) -> BoxFuture + Send>;
26
27/// Per-record future collector stored in `AimDbBuilder::spawn_fns`.
28///
29/// At `build()` time each is invoked in topological order; the returned
30/// `Vec<BoxFuture>` is appended to the runner's accumulator.
31type SpawnFnType = Box<dyn FnOnce(&Arc<AimDb>, RecordId) -> DbResult<Vec<BoxFuture>> + Send>;
32use crate::record_id::{RecordId, RecordKey, StringKey};
33use crate::typed_api::RecordRegistrar;
34use crate::typed_record::{AnyRecord, AnyRecordExt, RecordFutureCollector, TypedRecord};
35use crate::{DbError, DbResult};
36
37/// One registered record: its key, concrete type, and type-erased storage.
38struct RecordEntry {
39    key: StringKey,
40    type_id: TypeId,
41    record: Box<dyn AnyRecord>,
42    key_table: Option<Arc<crate::inbound_key::KeyTable>>,
43}
44
45/// Internal database state
46///
47/// The registry is immutable after `build()` and holds tens of records, so
48/// it needs exactly two structures: the entries in registration order
49/// (indexed by `RecordId`) and a key → id map for name resolution. The hot
50/// path (produce/consume) uses pre-resolved handles and never touches the
51/// registry; everything else here is control-plane/introspection.
52pub struct AimDbInner {
53    /// Record entries, indexed by `RecordId`. Order matches registration
54    /// order. Immutable after build().
55    ///
56    /// Per-client authorization is based on index of RecordEntry in `storage`
57    /// Never reorder, remove, or `swap_remove` entries as these could break current logic.
58    storages: Vec<RecordEntry>,
59
60    /// Name → RecordId lookup (control plane)
61    ///
62    /// Used by remote access, CLI, MCP for name resolution.
63    by_key: HashMap<StringKey, RecordId>,
64
65    /// Dependency graph (immutable after build)
66    ///
67    /// Contains all record nodes, edges, and topological order.
68    /// Used for introspection, spawn ordering, and graph queries.
69    dependency_graph: crate::graph::DependencyGraph,
70
71    /// Generic extension storage (frozen after build)
72    ///
73    /// External crates (e.g. `aimdb-persistence`) store typed state here
74    /// during builder configuration and retrieve it at query time via
75    /// `AimDb::extensions()`.
76    pub(crate) extensions: Extensions,
77
78    /// Build info, instance name and UID, checked at build().
79    identity: crate::identity::Identity,
80
81    /// The instance clock every write is stamped from, created in build().
82    clock: Arc<dyn crate::clock::InstanceClock>,
83}
84
85impl AimDbInner {
86    /// Resolve RecordKey to RecordId (control plane - O(1) average)
87    #[inline]
88    pub fn resolve<K: RecordKey>(&self, key: &K) -> Option<RecordId> {
89        self.by_key.get(key.as_str()).copied()
90    }
91
92    /// Resolve string to RecordId (convenience for remote access)
93    ///
94    /// O(1) average thanks to `Borrow<str>` implementation on `RecordKey`.
95    #[inline]
96    pub fn resolve_str(&self, name: &str) -> Option<RecordId> {
97        self.by_key.get(name).copied()
98    }
99
100    /// Get storage by RecordId (hot path - O(1))
101    #[inline]
102    pub fn storage(&self, id: RecordId) -> Option<&dyn AnyRecord> {
103        self.storages.get(id.index()).map(|e| e.record.as_ref())
104    }
105
106    /// Get the StringKey for a given RecordId
107    #[inline]
108    pub fn key_for(&self, id: RecordId) -> Option<&StringKey> {
109        self.storages.get(id.index()).map(|e| &e.key)
110    }
111
112    /// Get all RecordIds for a type (introspection)
113    ///
114    /// Linear scan — the registry is immutable after `build()`, holds tens of
115    /// records, and this is called from introspection paths only.
116    pub fn records_of_type<T: 'static>(&self) -> Vec<RecordId> {
117        let wanted = TypeId::of::<T>();
118        self.storages
119            .iter()
120            .enumerate()
121            .filter(|(_, e)| e.type_id == wanted)
122            .map(|(i, _)| RecordId::new(i as u32))
123            .collect()
124    }
125
126    /// Get the number of registered records
127    #[inline]
128    pub fn record_count(&self) -> usize {
129        self.storages.len()
130    }
131
132    /// Get the dependency graph (immutable reference)
133    ///
134    /// The graph is constructed once during `build()` and never changes.
135    /// Contains all record nodes, edges, and topological ordering.
136    #[inline]
137    pub fn dependency_graph(&self) -> &crate::graph::DependencyGraph {
138        &self.dependency_graph
139    }
140
141    /// Helper to get a typed record by RecordKey
142    ///
143    /// This encapsulates the common pattern of:
144    /// 1. Resolving key to RecordId
145    /// 2. Validating TypeId matches
146    /// 3. Downcasting to the typed record
147    pub fn get_typed_record_by_key<T>(&self, key: impl AsRef<str>) -> DbResult<&TypedRecord<T>>
148    where
149        T: Send + 'static + Debug + Clone,
150    {
151        let key_str = key.as_ref();
152
153        // Resolve key to RecordId
154        let id = self
155            .resolve_str(key_str)
156            .ok_or_else(|| DbError::record_key_not_found(key_str))?;
157
158        self.get_typed_record_by_id::<T>(id)
159    }
160
161    /// Helper to get a typed record by RecordId with type validation
162    pub fn get_typed_record_by_id<T>(&self, id: RecordId) -> DbResult<&TypedRecord<T>>
163    where
164        T: Send + 'static + Debug + Clone,
165    {
166        use crate::typed_record::AnyRecordExt;
167
168        let entry = self
169            .storages
170            .get(id.index())
171            .ok_or(DbError::InvalidRecordId { id: id.raw() })?;
172
173        // The downcast is the type check; keep the descriptive error on failure.
174        entry
175            .record
176            .as_typed::<T>()
177            .ok_or_else(|| DbError::TypeMismatch {
178                record_id: id.raw(),
179                expected_type: core::any::type_name::<T>().to_string(),
180            })
181    }
182
183    /// Collects metadata for all registered records
184    ///
185    /// Returns a vector of `RecordMetadata` for remote introspection.
186    /// Available only when the `remote` feature is enabled.
187    #[cfg(feature = "remote")]
188    pub fn list_records(&self) -> Vec<crate::remote::RecordMetadata> {
189        self.storages
190            .iter()
191            .enumerate()
192            .map(|(i, e)| {
193                let id = RecordId::new(i as u32);
194                let mut metadata = e.record.collect_metadata(e.type_id, e.key, id);
195                metadata.inbound_keys = e.key_table.as_ref().map(|table| {
196                    let captures = e.record.inbound_connectors().iter();
197                    crate::remote::InboundKeysInfo {
198                        captures: captures
199                            .filter_map(|l| l.key.as_ref().map(|(capture, _)| capture.clone()))
200                            .collect(),
201                        capacity: table.capacity(),
202                        assigned: table.assigned(),
203                        dropped: table.dropped(),
204                    }
205                });
206                metadata
207            })
208            .collect()
209    }
210
211    /// Try to get record's latest value as JSON by record key
212    ///
213    /// O(1) lookup using the key-based index.
214    ///
215    /// # Arguments
216    /// * `record_key` - The record key (e.g., "sensors.temperature")
217    ///
218    /// # Returns
219    /// `Some` with the current record value and its write metadata, or `None`
220    #[cfg(feature = "remote")]
221    pub fn try_latest_as_json(
222        &self,
223        record_key: &str,
224    ) -> Option<crate::Stamped<serde_json::Value>> {
225        let id = self.resolve_str(record_key)?;
226        self.storages
227            .get(id.index())?
228            .record
229            .json_access()?
230            .latest_json()
231    }
232
233    /// Try to get a record's latest value as owned JSON bytes.
234    ///
235    /// This is the byte-oriented sibling of
236    /// [`try_latest_as_json`](Self::try_latest_as_json). The built-in Serde
237    /// codec serializes the typed record directly; compatibility codecs may
238    /// inherit a `Value`-based fallback.
239    #[cfg(feature = "remote")]
240    pub fn try_latest_as_json_bytes(&self, record_key: &str) -> Option<crate::Stamped<Vec<u8>>> {
241        let id = self.resolve_str(record_key)?;
242        self.storages
243            .get(id.index())?
244            .record
245            .json_access()?
246            .latest_json_bytes()
247    }
248
249    /// Sets a record value from JSON (remote access API)
250    ///
251    /// Deserializes the JSON value and writes it to the record's buffer.
252    ///
253    /// **SAFETY:** Enforces the "No Producer Override" rule:
254    /// - Only works for records with `producer_count == 0`
255    /// - Returns error if the record has active producers
256    ///
257    /// # Arguments
258    /// * `record_key` - The record key (e.g., "config.app")
259    /// * `json_value` - JSON representation of the value
260    ///
261    /// # Returns
262    /// - `Ok(())` - Successfully set the value
263    /// - `Err(DbError)` - If record not found, has producers, or deserialization fails
264    #[cfg(feature = "remote")]
265    pub fn set_record_from_json(
266        &self,
267        record_key: &str,
268        json_value: serde_json::Value,
269    ) -> DbResult<()> {
270        let id = self
271            .resolve_str(record_key)
272            .ok_or_else(|| DbError::record_key_not_found(record_key.to_string()))?;
273
274        self.storages[id.index()]
275            .record
276            .json_access()
277            .ok_or_else(|| {
278                DbError::runtime_error(alloc::format!(
279                    "Record '{record_key}' does not support JSON remote access"
280                ))
281            })?
282            .set_from_json(json_value)
283    }
284}
285
286/// Database builder for producer-consumer pattern
287///
288/// Provides a fluent API for constructing databases with type-safe record registration.
289/// Set the runtime via `.runtime()`; a missing runtime is reported by `build()`
290/// like any other configuration mistake.
291pub struct AimDbBuilder {
292    /// Registered records with their keys (order matters for RecordId assignment)
293    records: Vec<(StringKey, TypeId, Box<dyn AnyRecord>)>,
294
295    /// Key → index into `records`, so repeated `configure()` calls resolve a
296    /// key without scanning the vec.
297    record_index: HashMap<StringKey, usize>,
298
299    /// Runtime capabilities, held as a value
300    runtime: Option<Arc<dyn crate::executor::RuntimeOps>>,
301
302    /// Connector builders that will be invoked during build()
303    connector_builders: Vec<Box<dyn crate::connector::ConnectorBuilder>>,
304
305    /// Identifies this builder in the
306    /// [`ConnectorHandle`](crate::connector::ConnectorHandle)s it returns.
307    builder_id: u32,
308
309    /// Per-record future collectors with their keys.
310    spawn_fns: Vec<(StringKey, SpawnFnType)>,
311
312    /// Startup tasks registered via on_start() — spawned after build() completes.
313    start_fns: Vec<StartFnType>,
314
315    /// Generic extension storage for external crates (e.g., persistence, metrics).
316    /// Moved into AimDbInner during build() so it can be read on the live AimDb handle.
317    extensions: Extensions,
318
319    /// Builder-level configuration mistakes (e.g. re-registering a key with a
320    /// different type), recorded instead of panicking and reported — together
321    /// with the per-record errors — by `build()` via
322    /// [`DbError::InvalidConfiguration`].
323    config_errors: Vec<crate::error::ConfigError>,
324
325    /// Build info, instance name and UID; checked by `build()`.
326    identity: crate::identity::IdentityConfig,
327
328    /// Permutes the record task start order; see [`Self::start_order_seed`].
329    #[cfg(feature = "start-order-seed")]
330    start_order_seed: Option<u64>,
331}
332
333impl AimDbBuilder {
334    /// Creates a new database builder without a runtime
335    ///
336    /// Call `.runtime()` to set the runtime adapter.
337    pub fn new() -> Self {
338        Self {
339            records: Vec::new(),
340            record_index: HashMap::new(),
341            runtime: None,
342            connector_builders: Vec::new(),
343            builder_id: crate::connector::next_builder_id(),
344            spawn_fns: Vec::new(),
345            start_fns: Vec::new(),
346            extensions: Extensions::new(),
347            config_errors: Vec::new(),
348            identity: Default::default(),
349            #[cfg(feature = "start-order-seed")]
350            start_order_seed: None,
351        }
352    }
353
354    /// This binary's build-info section, from
355    /// [`aimdb_build_info::section!`]. Served by the AimX method
356    /// `instance.info`; `build()` fails if AimX could not serve it (see
357    /// [`Identity::build_info`](crate::identity::Identity::build_info)).
358    pub fn build_info(mut self, section: &'static [u8]) -> Self {
359        self.identity.build_info = Some(section);
360        self
361    }
362
363    /// The instance's name, given at startup: at most
364    /// [`NAME_MAX`](crate::identity::NAME_MAX) bytes. Sent in the AimX welcome
365    /// and by `instance.info`.
366    pub fn instance_name(mut self, name: impl Into<String>) -> Self {
367        self.identity.name = Some(name.into());
368        self
369    }
370
371    /// The instance's unique ID, e.g. the chip's: at most
372    /// [`UID_MAX`](crate::identity::UID_MAX) bytes. Reported by
373    /// `instance.info` as lowercase hex, in the given byte order.
374    pub fn instance_uid(mut self, uid: &[u8]) -> Self {
375        self.identity.uid = Some(uid.to_vec());
376        self
377    }
378
379    /// Permutes the order in which record tasks start, reproducibly per seed.
380    ///
381    /// Records that are ready at the same time start in an order drawn from
382    /// `seed`; every record still starts after its inputs. Without a seed they
383    /// start in registration order. Run a test under several seeds to find
384    /// results that depend on start order, and replay a failing one by its
385    /// seed. `graph.topo_order` reports the order used.
386    ///
387    /// For tests and simulation only, so it sits behind the
388    /// `start-order-seed` feature.
389    #[cfg(feature = "start-order-seed")]
390    pub fn start_order_seed(mut self, seed: u64) -> Self {
391        self.start_order_seed = Some(seed);
392        self
393    }
394
395    /// Sets the runtime adapter.
396    ///
397    /// Accepts any adapter implementing the dyn-safe
398    /// [`RuntimeOps`](crate::executor::RuntimeOps) capability surface
399    /// (`TokioAdapter`, `EmbassyAdapter`, `WasmAdapter`); the builder stores it
400    /// as a value — no runtime type parameter.
401    pub fn runtime(mut self, rt: Arc<impl crate::executor::RuntimeOps + 'static>) -> Self {
402        self.runtime = Some(rt);
403        self
404    }
405    /// Returns a shared reference to the extension storage.
406    ///
407    /// External crates use this to retrieve state stored via `extensions_mut()`.
408    pub fn extensions(&self) -> &Extensions {
409        &self.extensions
410    }
411
412    /// Returns a mutable reference to the extension storage.
413    ///
414    /// Use this inside `AimDbBuilderPersistExt` (or similar) to store typed state
415    /// that `.persist()` and `AimDbQueryExt` will later retrieve.
416    pub fn extensions_mut(&mut self) -> &mut Extensions {
417        &mut self.extensions
418    }
419
420    /// Registers a task to be spawned after `build()` completes.
421    ///
422    /// The closure receives the [`RuntimeContext`](crate::RuntimeContext) and
423    /// must return a future that runs for as long as needed (e.g. an infinite
424    /// cleanup loop). Tasks are spawned in registration order, after all
425    /// record tasks and connectors have been started.
426    pub fn on_start<F, Fut>(&mut self, f: F) -> &mut Self
427    where
428        F: FnOnce(crate::RuntimeContext) -> Fut + Send + 'static,
429        Fut: core::future::Future<Output = ()> + Send + 'static,
430    {
431        self.start_fns.push(Box::new(move |ctx| Box::pin(f(ctx))));
432        self
433    }
434
435    /// Registers a connector builder, invoked during [`build`](Self::build).
436    ///
437    /// This single entry point registers **two kinds** of connector — both
438    /// implement [`ConnectorBuilder`](crate::connector::ConnectorBuilder) and are
439    /// driven the same way:
440    ///
441    /// 1. **Data-plane links** (MQTT / KNX / WebSocket): a record opts in with
442    ///    `link_to("<scheme>://<topic>")` / `link_from(...)`, and the connector
443    ///    mirrors that record to/from the external topic. The connector's
444    ///    [`scheme`](crate::connector::ConnectorBuilder::scheme) is what those
445    ///    links match against.
446    /// 2. **Remote-access session connectors** (UDS / serial / TCP): these expose
447    ///    AimDB itself over a transport so peers can introspect/subscribe/write.
448    ///    - The **client** half (e.g. `UdsClient`) dials a peer and *does* use
449    ///      `link_to`/`link_from` under its scheme — just like (1), the scheme is
450    ///      `"uds"` by default instead of `"mqtt"`.
451    ///    - The **server** half (e.g. `UdsServer`) *accepts* connections and takes
452    ///      **no links** — registering it is how a server stands up remote access
453    ///      (this replaces the old `with_remote_access(config)`).
454    ///
455    /// To keep a handle to the connector, register it with
456    /// [`connect`](Self::connect) instead.
457    ///
458    /// # Examples
459    ///
460    /// Illustrative (not compiled: the connector types live in downstream
461    /// crates `aimdb-core` cannot depend on):
462    ///
463    /// ```rust,ignore
464    /// // (1) data-plane link to an MQTT topic
465    /// let mut b = AimDbBuilder::new().runtime(rt)
466    ///     .with_connector(MqttConnector::new("mqtt://broker.local:1883"));
467    /// b.configure::<Temperature>("commands.temp", |r| {
468    ///     r.link_from("mqtt://commands/temp").with_deserializer(parse).finish();
469    /// });
470    /// b.build().await?;
471    ///
472    /// // (2a) remote-access SERVER — no links, just expose this db over UDS
473    /// AimDbBuilder::new().runtime(rt)
474    ///     .with_connector(UdsServer::from_config(remote_config))
475    ///     .build().await?;
476    ///
477    /// // (2b) remote-access CLIENT — mirror a record to a peer over UDS
478    /// let mut b = AimDbBuilder::new().runtime(rt)
479    ///     .with_connector(UdsClient::new("/run/aimdb.sock"));
480    /// b.configure::<Temp>("temp", |r| { r.with_remote_access().link_to("uds://temp"); });
481    /// b.build().await?;
482    /// ```
483    pub fn with_connector(
484        mut self,
485        builder: impl crate::connector::ConnectorBuilder + 'static,
486    ) -> Self {
487        self.connector_builders.push(Box::new(builder));
488        self
489    }
490
491    /// Registers a connector, exactly like [`with_connector`](Self::with_connector),
492    /// and returns a [`ConnectorHandle`](crate::connector::ConnectorHandle) for it.
493    ///
494    /// Takes `&mut self`, so it follows the by-value setup chain, like
495    /// [`configure`](Self::configure):
496    ///
497    /// ```rust,ignore
498    /// let mut b = AimDbBuilder::new().runtime(rt);
499    /// let mqtt = b.connect(MqttConnector::new("mqtt://broker.local:1883"));
500    /// b.configure::<Temperature>("temp.indoor", |r| {
501    ///     // A contract (`Linkable`) brings its own wire format:
502    ///     r.output(aimdb_data_contracts::publish(mqtt, "sensors/temp/indoor"));
503    ///     // Any other type, with a serializer of its own:
504    ///     r.output(OutboundLink::on(mqtt, "sensors/temp/raw").with_serializer(ser));
505    /// });
506    /// ```
507    pub fn connect(
508        &mut self,
509        builder: impl crate::connector::ConnectorBuilder + 'static,
510    ) -> crate::connector::ConnectorHandle {
511        let index = self.connector_builders.len();
512        self.connector_builders.push(Box::new(builder));
513        // Nobody registers more than u16::MAX connectors; saturating leaves an
514        // index that matches no connector rather than wrapping onto one.
515        crate::connector::ConnectorHandle {
516            builder: self.builder_id,
517            index: u16::try_from(index).unwrap_or(u16::MAX),
518        }
519    }
520
521    // NOTE: a remote-access **server** is registered like any other connector —
522    // there is no dedicated builder method:
523    //
524    //     .with_connector(aimdb_uds_connector::UdsServer::from_config(config))
525    //
526    // This rides the `with_connector` spine (see its docs) and lets the transport
527    // be swapped (UDS / serial / TCP) without touching the builder. The per-record
528    // `TypedRecord::with_remote_access()` is unrelated.
529
530    /// Configures a record type manually with a unique key
531    ///
532    /// The key uniquely identifies this record instance. Multiple records of the same
533    /// type can exist with different keys (e.g., "sensor.temperature.room1" and
534    /// "sensor.temperature.room2").
535    ///
536    /// # Arguments
537    /// * `key` - A unique identifier for this record. Can be a string literal, `StringKey`,
538    ///   or any type implementing `RecordKey` (including user-defined enum keys).
539    /// * `f` - Configuration closure
540    pub fn configure<T>(
541        &mut self,
542        key: impl RecordKey,
543        f: impl FnOnce(&mut RecordRegistrar<'_, T>),
544    ) -> &mut Self
545    where
546        T: Send + Sync + 'static + Debug + Clone,
547    {
548        // Convert any RecordKey to StringKey for internal storage
549        let record_key: StringKey = StringKey::from_dynamic(key.as_str());
550        let type_id = TypeId::of::<T>();
551
552        // Find existing record with this key, or create new one
553        let record_index = self.record_index.get(&record_key).copied();
554
555        // Reporting these instead would need a second mutable borrow of `self`
556        // while the first is live.
557        #[allow(
558            clippy::expect_used,
559            clippy::unwrap_used,
560            reason = "unreachable given the TypeId check above"
561        )]
562        let (rec, is_new_record) = match record_index {
563            Some(idx) => {
564                // Use existing record. A key re-registered with a different
565                // type is a user mistake: record it (reported from build())
566                // and skip the closure — a registrar for the wrong `T`
567                // cannot even be constructed.
568                let (_, existing_type, record) = &mut self.records[idx];
569                if *existing_type != type_id {
570                    self.config_errors.push(crate::error::ConfigError::new(
571                        record_key.as_str(),
572                        None,
573                        "key already registered with a different type",
574                    ));
575                    return self;
576                }
577                (
578                    record.as_typed_mut::<T>().expect(
579                        "record registry type mismatch despite TypeId check — \
580                         this is a bug in aimdb-core",
581                    ),
582                    false,
583                )
584            }
585            None => {
586                // Create new record
587                self.record_index.insert(record_key, self.records.len());
588                self.records
589                    .push((record_key, type_id, Box::new(TypedRecord::<T>::new())));
590                let (_, _, record) = self.records.last_mut().unwrap();
591                (
592                    record.as_typed_mut::<T>().expect(
593                        "record registry type mismatch despite TypeId check — \
594                         this is a bug in aimdb-core",
595                    ),
596                    true,
597                )
598            }
599        };
600
601        let mut reg = RecordRegistrar {
602            rec,
603            connector_builders: &self.connector_builders,
604            builder_id: self.builder_id,
605            record_key: record_key.as_str().to_string(),
606            extensions: &self.extensions,
607            last_stage: None,
608        };
609        f(&mut reg);
610
611        // Only store spawn function for new records to avoid duplicates
612        if is_new_record {
613            let spawn_key = record_key;
614
615            let spawn_fn: SpawnFnType = Box::new(move |db: &Arc<AimDb>, id: RecordId| {
616                let typed_record = db.inner().get_typed_record_by_id::<T>(id)?;
617                // Resolve the record's key for key-based Producer/Consumer construction.
618                let key = db
619                    .inner()
620                    .key_for(id)
621                    .map(|k| k.as_str().to_string())
622                    .unwrap_or_else(|| alloc::format!("__record_{}", id.index()));
623                RecordFutureCollector::<T>::collect_all_futures(typed_record, db, key.as_str())
624            });
625
626            self.spawn_fns.push((spawn_key, spawn_fn));
627        }
628
629        self
630    }
631
632    /// Builds the database and drives every collected future to completion.
633    ///
634    /// Convenience wrapper for the common case: call `build()`, then immediately
635    /// `runner.run().await`. The database handle is dropped on exit.
636    ///
637    /// For programmatic access to the handle (manual subscriptions, holding the
638    /// `AimDb` for other uses), prefer `build()` directly.
639    ///
640    /// # Returns
641    /// `DbResult<()>` — Ok once the database starts; the call then blocks until
642    /// every future the runner is driving has completed (typically forever).
643    pub async fn run(self) -> DbResult<()> {
644        log_info!("Building database and spawning background tasks...");
645
646        let (_db, runner) = self.build().await?;
647
648        log_info!("Database running, runner driving collected futures.");
649
650        runner.run().await;
651
652        Ok(())
653    }
654
655    /// Builds the database and returns a `(handle, runner)` pair.
656    ///
657    /// `build()` collects every future the database needs to drive (producer
658    /// services, consumer taps, transforms with fan-in forwarders, connectors,
659    /// remote-access supervisor, `on_start` tasks) into the [`AimDbRunner`]
660    /// returned alongside the clone-able [`AimDb`] handle. **No background
661    /// work runs until `runner.run().await` is awaited.**
662    ///
663    /// Use this when you need programmatic access to the handle for manual
664    /// subscriptions or production. For typical services, use `.run().await`
665    /// which calls `build()` and `runner.run()` for you.
666    ///
667    /// **Connector Setup:** Connectors are constructed during `build()` from
668    /// the `ConnectorBuilder`s previously registered via `.with_connector()`.
669    /// Their driving futures are appended to the runner.
670    ///
671    /// # Returns
672    /// `DbResult<(AimDb, AimDbRunner)>` — the handle (cloneable) and the
673    /// non-`Clone` runner that owns the collected futures.
674    ///
675    /// # Errors
676    ///
677    /// `build()` is the single surface for configuration mistakes: everything
678    /// recorded during configuration (conflicting `.source()`/`.transform()`/
679    /// `.link_from()`, missing serializers, unregistered schemes, …) plus the
680    /// build-time checks here (record validation, linked records without a
681    /// buffer, duplicate keys, transform inputs that are unregistered or hold
682    /// another type, dependency-graph cycles) is collected and
683    /// returned as one [`DbError::InvalidConfiguration`] carrying **all**
684    /// findings — one run surfaces every mistake.
685    pub async fn build(mut self) -> DbResult<(AimDb, AimDbRunner)> {
686        use crate::error::ConfigError;
687
688        // ── Validation pass: collect every configuration mistake before any
689        // effectful phase runs. Nothing returns early here.
690        let mut errors = core::mem::take(&mut self.config_errors);
691        let (identity, identity_errors) = core::mem::take(&mut self.identity).freeze();
692        errors.extend(
693            identity_errors
694                .into_iter()
695                .map(|message| ConfigError::new("", None, message)),
696        );
697
698        for (key, _, record) in self.records.iter_mut() {
699            // Mistakes recorded during configuration — fill in the record key
700            // the setters didn't have.
701            for mut e in record.drain_config_errors() {
702                if e.record_key.is_empty() {
703                    e.record_key = key.as_str().to_string();
704                }
705                errors.push(e);
706            }
707
708            // Writer exclusivity: sources, transforms and inbound links all
709            // write into the record's buffer and would race as
710            // last-writer-wins — at most one origin kind per record. Validated
711            // once here (the setters only catch same-stage duplicates). The
712            // message names kinds, not methods: `.input(..)` reaches the same
713            // origins as `.source()` and `.link_from()`.
714            let mut writers: Vec<&str> = Vec::new();
715            if record.has_producer() {
716                writers.push("source");
717            }
718            if record.has_transform() {
719                writers.push("transform");
720            }
721            if !record.inbound_connectors().is_empty() {
722                writers.push("inbound link");
723            }
724            if writers.len() > 1 {
725                let url = record
726                    .inbound_connectors()
727                    .first()
728                    .map(|l| l.url.to_string());
729                errors.push(ConfigError::new(
730                    key.as_str(),
731                    url,
732                    alloc::format!(
733                        "conflicting writers: record has {}; these are mutually \
734                         exclusive (all write the same buffer)",
735                        writers.join(" + ")
736                    ),
737                ));
738            }
739
740            // Connector links subscribe to / produce into the record's buffer;
741            // a linked record without one only surfaced at spawn time before.
742            let has_links =
743                !record.outbound_connectors().is_empty() || !record.inbound_connectors().is_empty();
744            if has_links && !record.has_buffer() {
745                let url = record
746                    .outbound_connectors()
747                    .first()
748                    .map(|l| l.url.to_string())
749                    .or_else(|| {
750                        record
751                            .inbound_connectors()
752                            .first()
753                            .map(|l| l.url.to_string())
754                    });
755                errors.push(ConfigError::new(
756                    key.as_str(),
757                    url,
758                    "linked record requires a buffer (call .buffer(...))",
759                ));
760            }
761        }
762
763        // Ensure runtime is set — a missing runtime is a configuration
764        // mistake, collected like every other so it never hides the rest of
765        // the findings. The runtime is bound at the final check.
766        if self.runtime.is_none() {
767            errors.push(ConfigError::new(
768                "",
769                None,
770                "runtime not set (use .runtime())",
771            ));
772        }
773
774        // Build the registry
775        let record_count = self.records.len();
776        let mut storages: Vec<RecordEntry> = Vec::with_capacity(record_count);
777        let mut by_key: HashMap<StringKey, RecordId> = HashMap::with_capacity(record_count);
778
779        for (key, type_id, record) in self.records.into_iter() {
780            // Duplicate keys (should not happen if configure() is used
781            // correctly): collect and skip so every mistake is reported.
782            if by_key.contains_key(&key) {
783                errors.push(ConfigError::new(key.as_str(), None, "duplicate record key"));
784                continue;
785            }
786
787            let id = RecordId::new(storages.len() as u32);
788            // `finish()` checked that keyed links of a record agree on it.
789            let key_capacity = record
790                .inbound_connectors()
791                .iter()
792                .find_map(|l| l.key.as_ref().map(|(_, capacity)| *capacity));
793            storages.push(RecordEntry {
794                key,
795                type_id,
796                record,
797                key_table: key_capacity.map(|c| Arc::new(crate::inbound_key::KeyTable::new(c))),
798            });
799            by_key.insert(key, id);
800        }
801
802        // Every transform input must hold the type the transform reads it as;
803        // otherwise its consumer fails to resolve at runtime and the transform
804        // silently never runs. Unregistered inputs are left to the graph.
805        for entry in &storages {
806            for (input_key, type_id, type_name) in entry.record.transform_input_types() {
807                let Some(input) = by_key
808                    .get(input_key.as_str())
809                    .and_then(|id| storages.get(id.index()))
810                else {
811                    continue;
812                };
813                if input.type_id != type_id {
814                    errors.push(ConfigError::new(
815                        entry.key.as_str(),
816                        None,
817                        alloc::format!(
818                            "transform reads input '{input_key}' as {type_name}, \
819                             but that record holds {}",
820                            input.record.type_name()
821                        ),
822                    ));
823                }
824            }
825        }
826
827        // Build dependency graph nodes straight from the records.
828        let graph_nodes: Vec<crate::graph::GraphNode> = storages
829            .iter()
830            .map(|e| {
831                let record = &e.record;
832                let (buffer_type, buffer_capacity) = record.buffer_info();
833                let outbound_links: Vec<String> = record
834                    .outbound_connectors()
835                    .iter()
836                    .map(|link| link.url.to_string())
837                    .collect();
838
839                crate::graph::GraphNode {
840                    key: e.key.as_str().to_string(),
841                    origin: record.record_origin(),
842                    buffer_type,
843                    buffer_capacity,
844                    tap_count: record.consumer_count(),
845                    has_outbound_link: !outbound_links.is_empty(),
846                    outbound_links,
847                    schema: record.schema().cloned(),
848                }
849            })
850            .collect();
851
852        // Build and validate the dependency graph; fold its findings (cycles,
853        // unregistered transform inputs) into the collected errors.
854        #[cfg(feature = "start-order-seed")]
855        let seed = self.start_order_seed;
856        #[cfg(not(feature = "start-order-seed"))]
857        let seed = None;
858        let dependency_graph = match DependencyGraph::build_and_validate_seeded(graph_nodes, seed) {
859            Ok(graph) => graph,
860            Err(e) => {
861                errors.push(ConfigError::new("", None, alloc::format!("{e}")));
862                return Err(DbError::InvalidConfiguration { errors });
863            }
864        };
865
866        // All validation done — report every collected mistake at once. The
867        // runtime binding lives here so a missing one is reported alongside
868        // every other finding instead of short-circuiting them.
869        let runtime = match (self.runtime.take(), errors.is_empty()) {
870            (Some(rt), true) => rt,
871            _ => return Err(DbError::InvalidConfiguration { errors }),
872        };
873
874        // The instance clock: created once and bound to every record before
875        // any task runs, so there is no unstamped write (design 058 §3.3).
876        // Every `RuntimeContext` the instance hands out reads it too.
877        let clock = runtime.new_clock();
878        for entry in &mut storages {
879            entry.record.bind_clock(clock.clone());
880        }
881
882        log_debug!(
883            "Dependency graph built successfully ({} nodes, {} edges, topo order: {:?})",
884            dependency_graph.nodes.len(),
885            dependency_graph.edges.len(),
886            dependency_graph.topo_order
887        );
888
889        let inner = Arc::new(AimDbInner {
890            storages,
891            by_key,
892            dependency_graph,
893            extensions: self.extensions,
894            identity,
895            clock: clock.clone(),
896        });
897
898        #[cfg(feature = "observability")]
899        let profiling_clock = crate::profiling::make_clock(clock);
900
901        let db = Arc::new(AimDb {
902            inner: inner.clone(),
903            runtime: runtime.clone(),
904            #[cfg(feature = "observability")]
905            profiling_clock,
906        });
907
908        // Accumulator for every future the runner will drive.
909        let mut futures_acc: Vec<BoxFuture> = Vec::new();
910
911        log_info!("Collecting futures for {} records", self.spawn_fns.len());
912
913        // Build a lookup map from spawn_fns for topological ordering
914        let mut spawn_fn_map: HashMap<StringKey, SpawnFnType> =
915            self.spawn_fns.into_iter().collect();
916
917        // Execute collectors in topological order — transforms collect after their inputs.
918        // `StringKey: Borrow<str>` with content-based Hash, so the map lookup by
919        // `&str` is O(1) and yields both the interned key and the RecordId.
920        for key_str in inner.dependency_graph.topo_order() {
921            let Some((&key, &id)) = inner.by_key.get_key_value(key_str.as_str()) else {
922                continue;
923            };
924
925            let Some(spawn_fn) = spawn_fn_map.remove(&key) else {
926                continue;
927            };
928
929            futures_acc.extend(spawn_fn(&db, id)?);
930        }
931
932        log_info!("Record future collection complete");
933
934        // AimX remote-access servers are no longer stood up here: register a
935        // session connector (`UdsServer::from_config(...)`) via `with_connector`
936        // instead — it collects below like any other connector, binds its
937        // transport, applies the security policy's writable marking, and drives
938        // the shared session engine. See `with_connector`'s docs.
939
940        // A connector that claims every route for its scheme must be the only
941        // one registered under it (see `ConnectorBuilder::owns_scheme`).
942        // Checked before any `build`, so the error names the misconfiguration
943        // instead of surfacing later as duplicated or misdirected traffic.
944        // Keyless `ConfigError`s: the mistake is the db's, not a record's.
945        let mut duplicate_schemes: Vec<crate::error::ConfigError> = Vec::new();
946        for (i, builder) in self.connector_builders.iter().enumerate() {
947            if !builder.owns_scheme() {
948                continue;
949            }
950            let first = self.connector_builders[..i]
951                .iter()
952                .position(|earlier| earlier.scheme() == builder.scheme());
953            // Only the second registration reports; a third would repeat it.
954            if first.is_some()
955                && !duplicate_schemes
956                    .iter()
957                    .any(|e| e.url.as_deref() == Some(builder.scheme()))
958            {
959                duplicate_schemes.push(crate::error::ConfigError::new(
960                    "",
961                    Some(builder.scheme().into()),
962                    alloc::format!(
963                        "More than one connector registered for scheme '{}'. Routes are \
964                         collected by scheme alone, so each connector would claim all of \
965                         them: every `link_to` would publish twice, and the routes cannot \
966                         be divided between the two. Register one connector for this \
967                         scheme, or give one of them a distinct scheme.",
968                        builder.scheme()
969                    ),
970                ));
971            }
972        }
973        if !duplicate_schemes.is_empty() {
974            return Err(DbError::InvalidConfiguration {
975                errors: duplicate_schemes,
976            });
977        }
978
979        // Collect connector futures. Connector builders return a
980        // `Vec<BoxFuture>` for the runner to drive — there is no connector
981        // object to keep.
982        for builder in self.connector_builders {
983            log_debug!("Building connector for scheme: {}", builder.scheme());
984
985            let connector_futures = builder.build(&db).await?;
986            let n_futures = connector_futures.len();
987            futures_acc.extend(connector_futures);
988
989            log_info!(
990                "Connector '{}' contributed {} future(s)",
991                builder.scheme(),
992                n_futures
993            );
994        }
995
996        // Collect on_start futures (registered by external crates like aimdb-persistence).
997        if !self.start_fns.is_empty() {
998            log_debug!("Collecting {} on_start future(s)", self.start_fns.len());
999
1000            for start_fn in self.start_fns {
1001                futures_acc.push(start_fn(db.runtime_ctx()));
1002            }
1003        }
1004
1005        let db_owned = (*db).clone();
1006
1007        Ok((db_owned, AimDbRunner::new(futures_acc)))
1008    }
1009}
1010
1011impl Default for AimDbBuilder {
1012    fn default() -> Self {
1013        Self::new()
1014    }
1015}
1016
1017/// Producer-consumer database
1018///
1019/// A database instance with type-safe record registration and cross-record
1020/// communication via the Emitter pattern. The runtime is held as a value
1021/// (`Arc<dyn RuntimeOps>`) — records are the only generic surface.
1022///
1023/// See `examples/` for usage.
1024///
1025/// # Examples
1026///
1027/// Illustrative (not compiled: the runtime adapter lives in a downstream
1028/// crate `aimdb-core` cannot depend on):
1029///
1030/// ```rust,ignore
1031/// use aimdb_tokio_adapter::TokioAdapter;
1032///
1033/// let mut builder = AimDbBuilder::new().runtime(Arc::new(TokioAdapter::new()?));
1034/// builder.register_record::<Temperature>(&TemperatureConfig);
1035/// let (db, runner) = builder.build().await?;
1036/// ```
1037#[derive(Clone)]
1038pub struct AimDb {
1039    /// Internal state
1040    inner: Arc<AimDbInner>,
1041
1042    /// Runtime capabilities, held as a value
1043    runtime: Arc<dyn crate::executor::RuntimeOps>,
1044
1045    /// Shared wall clock for stage profiling, built from the runtime at `build()` time.
1046    #[cfg(feature = "observability")]
1047    profiling_clock: crate::profiling::Clock,
1048}
1049
1050// ============================================================================
1051// AimDbRunner — drives every future the builder collected
1052// ============================================================================
1053
1054/// Non-`Clone` runner returned alongside [`AimDb`] from
1055/// [`AimDbBuilder::build()`].
1056///
1057/// Owns the complete set of futures that drive the database (producer
1058/// services, consumer taps, transforms with fan-in forwarders, connectors,
1059/// remote-access supervisor, `on_start` tasks). `run()` consumes `self`,
1060/// drives every future cooperatively via a `FuturesUnordered`, and returns
1061/// only when **every** future has completed — typically never, since
1062/// producer/consumer loops run for the application's lifetime.
1063///
1064/// Cancellation is the application's responsibility — wrap `runner.run()`
1065/// in `tokio::select!` with a shutdown signal, or use a `CancellationToken`
1066/// inside each registered service.
1067pub struct AimDbRunner {
1068    futures: Vec<BoxFuture>,
1069}
1070
1071impl AimDbRunner {
1072    pub(crate) fn new(futures: Vec<BoxFuture>) -> Self {
1073        Self { futures }
1074    }
1075
1076    /// Returns the number of futures the runner will drive. Useful for tests
1077    /// and diagnostic logging.
1078    pub fn future_count(&self) -> usize {
1079        self.futures.len()
1080    }
1081
1082    /// Drives every collected future to completion.
1083    ///
1084    /// Returns when all futures complete (normally: never, while producer and
1085    /// consumer loops are alive). To cancel, wrap this call in `tokio::select!`
1086    /// (or the analogous primitive on Embassy / WASM) with a shutdown signal —
1087    /// when the `select!` arm fires, this future is dropped and every
1088    /// `FuturesUnordered` entry is cancelled with it.
1089    pub async fn run(self) {
1090        use futures_util::stream::{FuturesUnordered, StreamExt};
1091
1092        if self.futures.is_empty() {
1093            return;
1094        }
1095
1096        let mut set: FuturesUnordered<BoxFuture> = self.futures.into_iter().collect();
1097        while set.next().await.is_some() {}
1098    }
1099}
1100
1101impl AimDb {
1102    /// Internal accessor for the inner state
1103    ///
1104    /// Used by adapter crates and internal spawning logic.
1105    #[doc(hidden)]
1106    pub fn inner(&self) -> &Arc<AimDbInner> {
1107        &self.inner
1108    }
1109
1110    /// Returns the extension storage frozen at `build()` time.
1111    ///
1112    /// External crates (e.g. `aimdb-persistence`) retrieve their typed state here
1113    /// to service query calls. The extensions are read-only on the live handle.
1114    pub fn extensions(&self) -> &Extensions {
1115        &self.inner.extensions
1116    }
1117
1118    /// Build info, instance name and UID, checked at `build()`.
1119    pub fn identity(&self) -> &crate::identity::Identity {
1120        &self.inner.identity
1121    }
1122
1123    /// Shared wall clock used by stage profiling (nanoseconds since an arbitrary epoch).
1124    #[cfg(feature = "observability")]
1125    pub(crate) fn profiling_clock(&self) -> &crate::profiling::Clock {
1126        &self.profiling_clock
1127    }
1128
1129    /// Builds a database with a closure-based builder pattern
1130    pub async fn build_with(
1131        rt: Arc<impl crate::executor::RuntimeOps + 'static>,
1132        f: impl FnOnce(&mut AimDbBuilder),
1133    ) -> DbResult<()> {
1134        let mut b = AimDbBuilder::new().runtime(rt);
1135        f(&mut b);
1136        b.run().await
1137    }
1138
1139    /// Produces a value to a specific record by key.
1140    ///
1141    /// Uses O(1) key-based lookup to find the correct record. Sync + fallible —
1142    /// only the lookup can fail; the buffer push itself is infallible.
1143    ///
1144    /// For hot paths, prefer `db.producer::<T>(key)?` once and reuse the
1145    /// returned handle.
1146    ///
1147    /// # Arguments
1148    /// * `key` - The record key (e.g., "sensor.temperature")
1149    /// * `value` - The value to produce
1150    pub fn produce<T>(&self, key: impl AsRef<str>, value: T) -> DbResult<()>
1151    where
1152        T: Send + 'static + Debug + Clone,
1153    {
1154        // Single write path via WriteHandle. For hot paths,
1155        // prefer `db.producer::<T>(key)` once and reuse the returned handle.
1156        let typed_rec = self.inner.get_typed_record_by_key::<T>(key)?;
1157        typed_rec.writer_handle()?.push(value);
1158        Ok(())
1159    }
1160
1161    /// Reads a record's current value without consuming it.
1162    ///
1163    /// Returns `Ok(None)` before the first value, for records without a buffer,
1164    /// or for buffers without a canonical latest value (notably
1165    /// [`SpmcRing`](crate::buffer::BufferCfg::SpmcRing)). Use a subscriber to
1166    /// read a ring's stream instead.
1167    ///
1168    /// Unknown keys and mismatched types return the same errors as
1169    /// [`produce`](Self::produce). This read needs neither serialization nor
1170    /// remote-access registration and is available on both std and no_std.
1171    ///
1172    /// The value comes with the metadata of the write that stored it; read
1173    /// `.value` for the value alone, `.stamp()` for its write time.
1174    pub fn latest<T>(&self, key: impl AsRef<str>) -> DbResult<Option<crate::Stamped<T>>>
1175    where
1176        T: Send + 'static + Debug + Clone,
1177    {
1178        let record = self.inner.get_typed_record_by_key::<T>(key)?;
1179        Ok(record.latest().map(|value| value.into_stamped()))
1180    }
1181
1182    /// Subscribes to a specific record by key
1183    ///
1184    /// Uses O(1) key-based lookup to find the correct record.
1185    ///
1186    /// # Arguments
1187    /// * `key` - The record key (e.g., "sensor.temperature")
1188    pub fn subscribe<T>(&self, key: impl AsRef<str>) -> DbResult<crate::buffer::Reader<T>>
1189    where
1190        T: Send + Sync + 'static + Debug + Clone,
1191    {
1192        let typed_rec = self.inner.get_typed_record_by_key::<T>(key)?;
1193        typed_rec.subscribe()
1194    }
1195
1196    /// Creates a type-safe producer for a specific record by key
1197    ///
1198    /// Returns a `Producer<T>` bound to a specific record key.
1199    ///
1200    /// # Arguments
1201    /// * `key` - The record key (e.g., "sensor.temperature")
1202    pub fn producer<T>(
1203        &self,
1204        key: impl Into<alloc::string::String>,
1205    ) -> DbResult<crate::typed_api::Producer<T>>
1206    where
1207        T: Send + 'static + Debug + Clone,
1208    {
1209        // Pre-resolve the typed record so the returned Producer holds a write
1210        // handle to the record's buffer/snapshot/metadata directly
1211        let key_str: alloc::string::String = key.into();
1212        let typed_rec = self.inner.get_typed_record_by_key::<T>(&key_str)?;
1213        Ok(crate::typed_api::Producer::new(typed_rec.writer_handle()?))
1214    }
1215
1216    /// Creates a type-safe consumer for a specific record by key
1217    ///
1218    /// Returns a `Consumer<T>` bound to a specific record key.
1219    ///
1220    /// # Arguments
1221    /// * `key` - The record key (e.g., "sensor.temperature")
1222    pub fn consumer<T>(
1223        &self,
1224        key: impl Into<alloc::string::String>,
1225    ) -> DbResult<crate::typed_api::Consumer<T>>
1226    where
1227        T: Send + Sync + 'static + Debug + Clone,
1228    {
1229        // Pre-resolve the buffer Arc so the returned Consumer subscribes
1230        // through a direct virtual call. A `.consumer()` without
1231        // a configured buffer surfaces as `MissingConfiguration` here rather
1232        // than panicking later inside `subscribe()`.
1233        let key_str: alloc::string::String = key.into();
1234        let typed_rec = self.inner.get_typed_record_by_key::<T>(&key_str)?;
1235        let buffer = typed_rec.buffer_handle().ok_or_else(|| {
1236            DbError::missing_configuration(alloc::format!("buffer for record '{}'", key_str))
1237        })?;
1238        Ok(crate::typed_api::Consumer::new(buffer))
1239    }
1240
1241    /// Resolve a record key to its RecordId
1242    ///
1243    /// Useful for checking if a record exists before operations.
1244    pub fn resolve_key(&self, key: &str) -> Option<crate::record_id::RecordId> {
1245        self.inner.resolve_str(key)
1246    }
1247
1248    /// Get all record IDs for a specific type
1249    ///
1250    /// Returns a slice of RecordIds for all records of type T.
1251    /// Useful for introspection when multiple records of the same type exist.
1252    pub fn records_of_type<T: 'static>(&self) -> Vec<crate::record_id::RecordId> {
1253        self.inner.records_of_type::<T>()
1254    }
1255
1256    /// Returns an owned `Arc` handle to the runtime capabilities.
1257    ///
1258    /// The runtime holds no clock reading of its own: code that reads time
1259    /// takes [`runtime_ctx`](Self::runtime_ctx), whose clock is the instance's.
1260    pub fn runtime_ops(&self) -> Arc<dyn crate::executor::RuntimeOps> {
1261        self.runtime.clone()
1262    }
1263
1264    /// The instance clock's current reading: time since this instance was
1265    /// built, on the clock that stamps every write. With it, in-process code
1266    /// computes a value's age: `db.now().since(v.stamp())`.
1267    pub fn now(&self) -> crate::clock::Stamp {
1268        self.inner.clock.now()
1269    }
1270
1271    /// Returns a [`RuntimeContext`](crate::RuntimeContext) over this
1272    /// database's runtime — the value handed to services and context-aware
1273    /// (de)serializers.
1274    pub fn runtime_ctx(&self) -> crate::RuntimeContext {
1275        crate::RuntimeContext::with_clock(self.runtime.clone(), self.inner.clock.clone())
1276    }
1277
1278    /// Lists all registered records (std only)
1279    ///
1280    /// Returns metadata for all registered records, useful for remote access introspection.
1281    /// Available only when the `std` feature is enabled.
1282    #[cfg(feature = "remote")]
1283    pub fn list_records(&self) -> Vec<crate::remote::RecordMetadata> {
1284        self.inner.list_records()
1285    }
1286
1287    /// Resets stage profiling counters for every record (feature `observability`).
1288    #[cfg(feature = "observability")]
1289    pub fn reset_stage_profiling(&self) {
1290        for entry in &self.inner.storages {
1291            entry.record.reset_profiling();
1292        }
1293    }
1294
1295    /// Resets buffer introspection counters for every record (feature `observability`).
1296    #[cfg(feature = "observability")]
1297    pub fn reset_buffer_metrics(&self) {
1298        for entry in &self.inner.storages {
1299            entry.record.reset_buffer_metrics();
1300        }
1301    }
1302
1303    /// Try to get record's latest value as JSON by name
1304    ///
1305    /// Convenience wrapper around `AimDbInner::try_latest_as_json()`.
1306    ///
1307    /// # Arguments
1308    /// * `record_name` - The full Rust type name (e.g., "server::Temperature")
1309    ///
1310    /// # Returns
1311    /// `Some(JsonValue)` with the current value, or `None` if the record has no
1312    /// value yet, no buffer, or a buffer with **no canonical latest** — i.e.
1313    /// [`SpmcRing`](crate::buffer::BufferCfg::SpmcRing). A ring is a stream/backlog
1314    /// with no single "current value"; read it via a subscriber or `record.drain`,
1315    /// not a peek (`record.get`). Use [`SingleLatest`](crate::buffer::BufferCfg::SingleLatest)
1316    /// for state you want to read latest-value style.
1317    #[cfg(feature = "remote")]
1318    pub fn try_latest_as_json(
1319        &self,
1320        record_name: &str,
1321    ) -> Option<crate::Stamped<serde_json::Value>> {
1322        self.inner.try_latest_as_json(record_name)
1323    }
1324
1325    /// Try to get a record's latest value as owned JSON bytes.
1326    ///
1327    /// Semantics match [`try_latest_as_json`](Self::try_latest_as_json):
1328    /// buffers without a canonical latest value (notably `SpmcRing`) return
1329    /// `None`. AimX `record.get` retains its per-connection drain fallback for
1330    /// those records.
1331    #[cfg(feature = "remote")]
1332    pub fn try_latest_as_json_bytes(&self, record_name: &str) -> Option<crate::Stamped<Vec<u8>>> {
1333        self.inner.try_latest_as_json_bytes(record_name)
1334    }
1335
1336    /// Sets a record value from JSON (remote access API)
1337    ///
1338    /// Deserializes JSON and produces the value to the record's buffer.
1339    ///
1340    /// **SAFETY:** Enforces "No Producer Override" rule - only works for configuration
1341    /// records without active producers.
1342    ///
1343    /// # Arguments
1344    /// * `record_name` - Full Rust type name
1345    /// * `json_value` - JSON value to set
1346    ///
1347    /// # Returns
1348    /// `Ok(())` on success, error if record not found, has producers, or deserialization fails
1349    #[cfg(feature = "remote")]
1350    pub fn set_record_from_json(
1351        &self,
1352        record_name: &str,
1353        json_value: serde_json::Value,
1354    ) -> DbResult<()> {
1355        self.inner.set_record_from_json(record_name, json_value)
1356    }
1357
1358    /// The inbound router for `scheme`: every link compiled against the
1359    /// connector's `grammar`, keyed links sharing their record's key table.
1360    ///
1361    /// Also returns one [`InboundRouteInfo`](crate::InboundRouteInfo) per
1362    /// route, in the router's order.
1363    ///
1364    /// Rejects every link the grammar or its key cannot compile, naming the
1365    /// record and the resolved topic.
1366    pub(crate) fn inbound_router(
1367        &self,
1368        scheme: &str,
1369        grammar: &'static dyn crate::TopicGrammar,
1370    ) -> DbResult<(crate::router::Router, Vec<crate::InboundRouteInfo>)> {
1371        let mut routes = Vec::new();
1372        let mut infos = Vec::new();
1373        let mut errors = Vec::new();
1374
1375        for (record_index, entry) in self.inner.storages.iter().enumerate() {
1376            for link in entry.record.inbound_connectors() {
1377                if link.url.scheme() != scheme {
1378                    continue;
1379                }
1380                let topic = link.resolve_topic();
1381                match self.inbound_route(entry, link, &topic, grammar) {
1382                    Ok(route) => {
1383                        routes.push(route);
1384                        infos.push(crate::InboundRouteInfo {
1385                            topic: Arc::from(topic),
1386                            type_id: entry.type_id,
1387                            record_index,
1388                            config: crate::transport::ConnectorConfig::from_query(&link.config),
1389                        });
1390                    }
1391                    Err(message) => errors.push(crate::ConfigError::new(
1392                        entry.key.as_str(),
1393                        Some(link.url.to_string()),
1394                        message,
1395                    )),
1396                }
1397            }
1398        }
1399
1400        if !errors.is_empty() {
1401            return Err(DbError::InvalidConfiguration { errors });
1402        }
1403        Ok((crate::router::Router::new(grammar, routes), infos))
1404    }
1405
1406    fn inbound_route(
1407        &self,
1408        entry: &RecordEntry,
1409        link: &crate::connector::InboundConnectorLink,
1410        topic: &str,
1411        grammar: &'static dyn crate::TopicGrammar,
1412    ) -> Result<crate::router::CompiledRoute, String> {
1413        let pattern = crate::TopicPattern::parse(topic).map_err(|e| e.to_string())?;
1414        let filter = grammar.compile(&pattern)?;
1415        let names: Box<[Box<str>]> = pattern.capture_names().map(Box::from).collect();
1416
1417        let key = match (&link.key, &entry.key_table) {
1418            (Some((capture, _)), Some(table)) => {
1419                let capture_number =
1420                    names.iter().position(|n| **n == **capture).ok_or_else(|| {
1421                        alloc::format!("key '{capture}' is not a capture of '{topic}'")
1422                    })?;
1423                Some((table.clone(), capture_number))
1424            }
1425            _ => None,
1426        };
1427
1428        Ok(crate::router::CompiledRoute::pattern(
1429            filter,
1430            names,
1431            key,
1432            link.create_ingest(self),
1433        ))
1434    }
1435
1436    /// The capture value `key` stands for on record `record_key`.
1437    pub fn inbound_key_name(&self, record_key: &str, key: crate::KeyId) -> Option<Arc<str>> {
1438        let id = self.inner.by_key.get(record_key)?;
1439        self.inner
1440            .storages
1441            .get(id.index())?
1442            .key_table
1443            .as_ref()?
1444            .name(key)
1445    }
1446
1447    /// Every outbound link of `scheme`, with its record's index and type.
1448    pub(crate) fn outbound_links<'a>(
1449        &'a self,
1450        scheme: &'a str,
1451    ) -> impl Iterator<Item = (usize, TypeId, &'a crate::connector::ConnectorLink)> + 'a {
1452        self.inner
1453            .storages
1454            .iter()
1455            .enumerate()
1456            .flat_map(move |(i, entry)| {
1457                // i and RecordId must match: connectors get i as `record_index`
1458                debug_assert_eq!(
1459                    self.inner.by_key.get(&entry.key).map(|id| id.index()),
1460                    Some(i),
1461                    "record storage order diverges from RecordId for key {}",
1462                    entry.key.as_str()
1463                );
1464                entry
1465                    .record
1466                    .outbound_connectors()
1467                    .iter()
1468                    .filter(move |link| link.url.scheme() == scheme)
1469                    .map(move |link| (i, entry.type_id, link))
1470            })
1471    }
1472}
1473
1474#[cfg(test)]
1475mod instance_clock_tests {
1476    use crate::executor::test_support::ManualClockRuntimeOps;
1477    use crate::Stamp;
1478    use core::time::Duration;
1479
1480    /// 058 §3.1: one notion of time per instance. Everything an instance hands
1481    /// out reads the clock `build()` created.
1482    #[tokio::test]
1483    async fn every_time_source_of_an_instance_reads_its_clock() {
1484        let ops = ManualClockRuntimeOps::default();
1485        let (db, _runner) = crate::AimDbBuilder::new()
1486            .runtime(alloc::sync::Arc::new(ops.clone()))
1487            .build()
1488            .await
1489            .unwrap();
1490        ops.clock.advance(Duration::from_nanos(4242));
1491
1492        assert_eq!(db.now(), Stamp::from_nanos(4242));
1493        assert_eq!(db.runtime_ctx().time().now(), Stamp::from_nanos(4242));
1494        assert_eq!(db.runtime_ctx().clock().now(), Stamp::from_nanos(4242));
1495        #[cfg(feature = "observability")]
1496        assert_eq!((db.profiling_clock())(), 4242);
1497    }
1498}
1499
1500#[cfg(test)]
1501mod connect_tests {
1502    use crate::connector::ConnectorBuilder;
1503    use crate::{AimDb, AimDbBuilder, DbResult};
1504    use alloc::boxed::Box;
1505    use alloc::vec::Vec;
1506    use core::future::Future;
1507    use core::pin::Pin;
1508
1509    struct Scheme(&'static str);
1510
1511    impl ConnectorBuilder for Scheme {
1512        fn build<'a>(
1513            &'a self,
1514            _db: &'a AimDb,
1515        ) -> Pin<
1516            Box<
1517                dyn Future<
1518                        Output = DbResult<Vec<Pin<Box<dyn Future<Output = ()> + Send + 'static>>>>,
1519                    > + Send
1520                    + 'a,
1521            >,
1522        > {
1523            Box::pin(async { Ok(Vec::new()) })
1524        }
1525        fn scheme(&self) -> &str {
1526            self.0
1527        }
1528    }
1529
1530    #[test]
1531    fn connect_hands_out_one_handle_per_connector() {
1532        let mut a = AimDbBuilder::new();
1533        let mqtt = a.connect(Scheme("mqtt"));
1534        let knx = a.connect(Scheme("knx"));
1535        let other = AimDbBuilder::new().connect(Scheme("mqtt"));
1536
1537        assert_eq!((mqtt.index, knx.index), (0, 1));
1538        assert_eq!(mqtt.builder, knx.builder);
1539        assert_ne!(mqtt.builder, other.builder);
1540        let schemes: Vec<&str> = a.connector_builders.iter().map(|c| c.scheme()).collect();
1541        assert_eq!(schemes, ["mqtt", "knx"]);
1542    }
1543}