aimdb_core/lib.rs
1//! AimDB Core Database Engine
2//!
3//! # aimdb-core
4//!
5//! Type-safe, async in-memory database for data synchronization
6//! across MCU → edge → cloud environments.
7//!
8//! # Architecture
9//!
10//! - **RecordKey/RecordId**: Stable identifiers for multi-instance records
11//! - **Runtime Agnostic**: Works with Tokio (std) or Embassy (embedded)
12//! - **Producer-Consumer**: Built-in typed message passing
13//!
14//! See examples in the repository for usage patterns.
15//!
16//! # A panic is a bug, not an error channel
17//!
18//! Every failure is a [`DbError`]. The crate is compiled under
19//! `deny(clippy::unwrap_used, clippy::expect_used, clippy::panic)` outside its
20//! tests; the sites that remain carry an `allow` with a reason. A dependency
21//! can still panic on its own, and a poisoned lock is recovered from.
22//!
23//! # Where aimdb's own reporting goes
24//!
25//! Two optional destinations, neither on by default: **`tracing`**, the ordinary
26//! choice for a Rust binary, and **`log`**, for a host that cannot be handed a
27//! process-global subscriber — chiefly an FFI layer, which needs its callback's
28//! context pointer to live somewhere a `tracing::Layer` has no room for. Both
29//! may be on at once; both off emits nothing. Events carry the emitting module
30//! as their target (`aimdb_core::builder`) either way.
31//! Every crate in this workspace that reports at all now does so through the
32//! facade, so a destination sees the connectors too. See
33//! [docs/design/050](https://github.com/aimdb-dev/aimdb/blob/main/docs/design/050-log-destination-for-ffi.md)
34//! for filtering and duplicate delivery.
35//!
36//! ## What a `log` destination must guarantee
37//!
38//! Getting one wrong costs a deadlock or memory unsafety, not a bad log line:
39//!
40//! 1. **Called from any thread**, aimdb's runtime thread included.
41//! 2. **Must not unwind** — across a C or C++ boundary that is UB.
42//! 3. **Must not re-enter aimdb on a path that itself logs.** `log` has no
43//! reentrancy guard (`tracing` does), so this recurses without bound.
44//! Getters are fine.
45//! 4. **Must not block on anything a thread might hold while calling into
46//! aimdb** — that is the lock ordering.
47//! 5. **Cannot be uninstalled.** `set_logger` is once per process; a second
48//! call returns `Err` and the first destination keeps receiving.
49
50// A panic here is a bug: two FFI doors sit above this crate, and a consumer's
51// `panic = "abort"` compiles their guard out.
52#![cfg_attr(
53 not(test),
54 deny(clippy::unwrap_used, clippy::expect_used, clippy::panic)
55)]
56#![cfg_attr(not(feature = "std"), no_std)]
57
58extern crate alloc;
59
60// Must precede the other modules: `macro_rules!` visibility is textual.
61#[macro_use]
62mod log;
63mod event_capture;
64
65/// Implementation detail of the `log_*` macros; no stability guarantee.
66///
67/// The macros expand in the *calling* crate, so they can only name paths
68/// reachable from there — this re-export is what saves a facade user from
69/// declaring `log` itself.
70#[doc(hidden)]
71pub mod __private {
72 // `::log`, not `log`: this crate has a private `log` module at its root.
73 #[cfg(feature = "log")]
74 pub use ::log;
75 #[cfg(feature = "tracing")]
76 pub use ::tracing;
77}
78
79// Every type the `log_*!` macros format must implement `defmt::Format` when
80// `defmt` is on (#352); this fails the build if one stops doing so.
81#[cfg(all(feature = "defmt", feature = "connector-session"))]
82const _: () = {
83 fn format<T: defmt::Format + ?Sized>() {}
84 let _ = format::<DbError>;
85 let _ = format::<outbound::SerializeFailure>;
86 let _ = format::<session::TransportError>;
87 let _ = format::<session::CodecError>;
88 let _ = format::<session::AuthError>;
89 let _ = format::<session::FrameFault>;
90 let _ = format::<alloc::string::String>;
91 let _ = format::<alloc::vec::Vec<alloc::string::String>>;
92 let _ = format::<alloc::sync::Arc<str>>;
93};
94
95pub mod buffer;
96pub mod builder;
97pub mod clock;
98#[cfg(feature = "remote")]
99pub mod codec;
100pub mod connector;
101pub mod context;
102mod error;
103pub mod executor;
104pub mod extensions;
105pub mod graph;
106pub mod identity;
107mod inbound_dispatch;
108mod inbound_key;
109mod outbound;
110#[cfg(feature = "observability")]
111pub mod profiling;
112pub mod record_id;
113#[cfg(feature = "remote")]
114pub mod remote;
115mod router;
116#[cfg(feature = "connector-session")]
117pub mod session;
118pub mod signal;
119pub mod stamped;
120pub mod topic_pattern;
121pub mod transform;
122pub mod transport;
123pub mod typed_api;
124pub mod typed_record;
125
126// Public API exports
127pub use context::RuntimeContext;
128pub use error::{ConfigError, DbError, DbErrorKind, DbResult};
129pub use extensions::Extensions;
130pub use log::{LogDebug, LogDisplay};
131
132// Runtime capability surface: the runtime travels as `Arc<dyn RuntimeOps>`,
133// the one trait an adapter implements.
134pub use executor::{BoxFuture, ExecutorError, ExecutorResult, LogLevel, RuntimeOps};
135
136// Write timestamps (design 058): the instance clock and the value envelope.
137pub use clock::{InstanceClock, Stamp};
138pub use stamped::{Stamped, WriteMetadata};
139
140// Producer-Consumer Pattern exports
141#[cfg(feature = "remote")]
142pub use buffer::JsonReader;
143pub use buffer::Reader;
144pub use buffer::TryProduceError;
145pub use builder::{AimDb, AimDbBuilder};
146pub use connector::{ConnectorBuilder, ConnectorHandle};
147pub use transport::{ConnectorConfig, PublishError};
148pub use typed_api::{
149 Consumer, Detached, InboundConnectorBuilder, InboundLink, InboundLinkBuilder, Input,
150 OutboundConnectorBuilder, OutboundLink, OutboundLinkBuilder, Output, Producer, RecordRegistrar,
151 StageKind,
152};
153#[cfg(feature = "remote")]
154pub use typed_record::JsonRecordAccess;
155pub use typed_record::{AnyRecord, AnyRecordExt, TypedRecord};
156
157// JSON codec (feature `remote`, no_std + alloc compatible)
158#[cfg(feature = "remote")]
159pub use codec::{JsonCodec, RemoteSerialize, SerdeJsonCodec};
160
161// Record-key leaf/entity derivation, shared by record metadata and the
162// connectors that surface the `entity` field.
163#[cfg(feature = "remote")]
164pub use remote::topic_leaf;
165
166// connector-session contracts (feature `connector-session`, no_std + alloc
167// compatible). See docs/design/remote-access-via-connectors.md.
168#[cfg(feature = "connector-session")]
169pub use session::{
170 is_wildcard, pattern_contains, topic_matches, AuthError, BoxFut, BoxStream, CodecError,
171 Connection, Dialer, Dispatch, EnvelopeCodec, Inbound, Listener, Outbound, Payload, PeerInfo,
172 RpcError, SessionCtx, SessionLimits, SubUpdate, TransportError, TransportResult,
173};
174
175// Signal gauge handle (always available; inert without `observability`)
176pub use signal::SignalGaugeHandle;
177
178// Stage profiling exports (feature-gated)
179#[cfg(feature = "observability")]
180pub use profiling::{
181 RecordProfilingMetrics, SignalGauge, SignalStats, SignalStatsInfo, StageMetrics,
182 StageProfilingInfo,
183};
184
185// Connector Infrastructure exports
186pub use connector::TopicResolverFn;
187pub use connector::{ConnectorLink, ConnectorUrl, LinkAddress, SerializeError};
188pub use connector::{IngestFactoryFn, IngestFn};
189pub use connector::{TopicBuf, TopicOverflow, TopicWriter};
190
191// Router exports for connector implementations
192pub use inbound_dispatch::{InboundDispatch, InboundRouteInfo};
193pub use outbound::{
194 OutboundMessage, OutboundPayload, OutboundRoutes, RouteId, RouteInfo, RouteStats,
195};
196
197// Topic grammar for connectors with wildcard subscriptions
198pub use topic_pattern::{
199 ExactGrammar, PatternError, PatternPart, Spans, TopicFilter, TopicGrammar, TopicMatch,
200 TopicPattern, MAX_CAPTURES,
201};
202
203// Keys assigned to capture values of keyed inbound links
204pub use inbound_key::KeyId;
205
206// Record identification exports
207pub use record_id::{RecordId, RecordKey, StringKey};
208
209// Graph exports (dependency graph for record topology)
210pub use graph::{DependencyGraph, EdgeType, GraphEdge, GraphNode, RecordOrigin};
211
212// Transform API exports
213pub use transform::{JoinBuilder, JoinEventRx, JoinPipeline, JoinTrigger};
214pub use transform::{TransformBuilder, TransformPipeline};