diff --git a/aimdb-core/src/session/client.rs b/aimdb-core/src/session/client.rs index 82bfa719..ebc732ae 100644 --- a/aimdb-core/src/session/client.rs +++ b/aimdb-core/src/session/client.rs @@ -1064,677 +1064,4 @@ async fn inbound_pump(handle: ClientHandle, inbound: crate::InboundDispatch, id: } #[cfg(test)] -mod tests { - use super::*; - use crate::session::{CodecError, PeerInfo, TransportResult}; - use core::future::pending; - - /// Sink connection: swallows every frame and never yields one, i.e. a peer - /// that keeps the link open and answers nothing. - #[derive(Default)] - struct SilentPeer { - peer: PeerInfo, - } - - impl Connection for SilentPeer { - fn recv(&mut self) -> BoxFut<'_, TransportResult>>> { - Box::pin(pending()) - } - fn send<'a>(&'a mut self, _frame: &'a [u8]) -> BoxFut<'a, TransportResult<()>> { - Box::pin(async { Ok(()) }) - } - fn peer(&self) -> &PeerInfo { - &self.peer - } - } - - /// Frames are never inspected in these tests — only the pending-call - /// bookkeeping is. - struct NullCodec; - - impl EnvelopeCodec for NullCodec { - fn decode(&self, _frame: &[u8]) -> Result { - Err(CodecError::Malformed) - } - fn encode(&self, _msg: Outbound<'_>, _out: &mut Vec) -> Result<(), CodecError> { - Ok(()) - } - fn encode_inbound(&self, _msg: Inbound, _out: &mut Vec) -> Result<(), CodecError> { - Ok(()) - } - fn decode_outbound<'a>(&self, _frame: &'a [u8]) -> Result, CodecError> { - Err(CodecError::Malformed) - } - } - - /// A handle whose channel nobody drains — an engine still dialing, or - /// sleeping between redials. `cap` is [`ClientConfig::max_offline_queue`]. - /// The prune receiver comes back too: dropping it would close the signal - /// channel and silently no-op every [`ClientHandle::request_prune`]. - fn test_handle_capped(cap: usize) -> (ClientHandle, Receiver, Receiver<()>) { - let (cmd_tx, cmd_rx) = async_channel::bounded(cap.max(1)); - let (prune_tx, prune_rx) = async_channel::bounded(1); - ( - ClientHandle { - cmd_tx, - prune_tx, - next_id: Arc::new(AtomicUsize::new(1)), - inline_envelopes: true, - }, - cmd_rx, - prune_rx, - ) - } - - fn test_handle() -> (ClientHandle, Receiver, Receiver<()>) { - test_handle_capped(256) - } - - /// Poll a call once — enough to queue its command — then abandon it, which - /// is what a lost timeout race does to the future. - async fn abandon_call(handle: &ClientHandle, method: &'static str) { - let call = handle.call(method, Payload::from(&b"x"[..])); - assert!( - tokio::time::timeout(core::time::Duration::ZERO, call) - .await - .is_err(), - "the call must not resolve" - ); - } - - /// The caller half of the reclaim path: abandoning a call queues a - /// `CancelCall` naming exactly that call, so the engine never has to guess - /// which entry died. - #[tokio::test] - async fn abandoning_a_call_queues_its_cancellation() { - let (handle, cmd_rx, _prune_rx) = test_handle(); - abandon_call(&handle, "one").await; - - match cmd_rx.try_recv() { - Ok(ClientCmd::Call { id: 1, .. }) => {} - _ => panic!("the call must be queued first"), - } - match cmd_rx.try_recv() { - Ok(ClientCmd::CancelCall { id: 1 }) => {} - _ => panic!("abandoning the call must queue its cancellation"), - } - assert!(cmd_rx.is_empty(), "no other command is emitted"); - } - - /// A call that resolves normally must not also queue a cancellation — the - /// engine already dropped its entry when it routed the reply. - #[tokio::test] - async fn a_resolved_call_queues_no_cancellation() { - let (handle, cmd_rx, _prune_rx) = test_handle(); - let call = handle.call("one", Payload::from(&b"x"[..])); - let answer = async { - // Take the reply channel out of the queued command and answer it. - match cmd_rx.recv().await { - Ok(ClientCmd::Call { reply, .. }) => { - let _ = reply.send(Ok(Payload::from(&b"ok"[..]))); - } - _ => panic!("the call must be queued"), - } - }; - let (reply, ()) = futures_util::future::join(call, answer).await; - assert_eq!(&*reply.expect("the call resolves"), b"ok"); - assert!( - cmd_rx.is_empty(), - "a resolved call must not queue a cancellation" - ); - } - - /// Regression for the *concurrent* timeout batch: every call is issued and - /// tracked while its receiver is live, then all of them are abandoned at - /// once, with keepalive disabled and no later call to trigger a sweep. - /// - /// Each entry the engine frees drops its reply sender, which the (retained) - /// receiver observes as `Canceled` — so this asserts the table actually - /// empties rather than that some reclaim path merely ran. Pre-fix all 1000 - /// entries stayed until the connection ended. - #[tokio::test] - async fn a_concurrent_batch_of_cancellations_frees_every_entry() { - const BATCH: u64 = 1_000; - let (cmd_tx, cmd_rx) = async_channel::unbounded::(); - let config = ClientConfig { - reconnect: false, - // The point of the test: nothing but the cancellations can reclaim. - keepalive_interval: None, - ..Default::default() - }; - let ctx = - crate::RuntimeContext::new(Arc::new(crate::executor::test_support::NoopRuntimeOps)); - // Never signalled: this asserts the by-id path reclaims on its own. - let (_prune_tx, prune_rx) = async_channel::bounded::<()>(1); - let engine = drive_connection( - Box::new(SilentPeer::default()), - &NullCodec, - &cmd_rx, - &prune_rx, - &config, - &ctx, - ); - - let exercise = async { - // All in flight at once: every receiver is alive as its call is - // tracked, so nothing is reclaimable until the batch is abandoned. - let mut replies = Vec::new(); - for id in 1..=BATCH { - let (reply, rx) = oneshot::channel(); - cmd_tx - .try_send(ClientCmd::Call { - id, - method: String::from("hang"), - params: Payload::from(&b"x"[..]), - reply, - }) - .expect("the channel is unbounded"); - replies.push(rx); - } - // Then the whole batch times out. - for id in 1..=BATCH { - cmd_tx - .try_send(ClientCmd::CancelCall { id }) - .expect("the channel is unbounded"); - } - for (i, rx) in replies.into_iter().enumerate() { - assert!( - rx.await.is_err(), - "call {} was still held by the engine", - i + 1 - ); - } - }; - - futures_util::pin_mut!(engine); - futures_util::pin_mut!(exercise); - match futures_util::future::select(engine, exercise).await { - futures_util::future::Either::Left(_) => panic!("the engine ended early"), - futures_util::future::Either::Right(((), _)) => {} - } - } - - /// The id counter refuses rather than wraps at its ceiling: a wrapped id - /// would re-issue one a live subscription still holds, and the engine would - /// demux that subscription's updates into the wrong sink. Both allocating - /// call sites fail, and neither reaches the engine — so no pending entry is - /// ever created under an id that would be mis-routed. - #[tokio::test] - async fn exhausted_ids_are_refused_not_wrapped() { - let (cmd_tx, cmd_rx) = async_channel::bounded(256); - let (prune_tx, _prune_rx) = async_channel::bounded(1); - let handle = ClientHandle { - cmd_tx, - prune_tx, - next_id: Arc::new(AtomicUsize::new(usize::MAX)), - inline_envelopes: true, - }; - - // Bounded at zero: the refusal happens before the id is queued, so it - // resolves on the first poll. A wrapping counter would instead queue the - // call and await a reply forever — the timeout turns that regression - // into a failure rather than a hang. - let refused = tokio::time::timeout( - core::time::Duration::ZERO, - handle.call("one", Payload::from(&b"x"[..])), - ) - .await - .expect("a refused call must not reach the engine and await a reply"); - assert!( - matches!(refused, Err(RpcError::Internal)), - "a call at the id ceiling must be refused" - ); - assert!( - handle.subscribe("tele").is_err(), - "a subscription at the id ceiling must be refused" - ); - assert!( - cmd_rx.is_empty(), - "a refused allocation must not reach the engine" - ); - } - - /// Evict-oldest puts a cancellation on the same lossy footing as a write, - /// but dropping one silently strands its pending entry until the connection - /// ends — so the eviction has to be noticed. Nothing drains the queue here: - /// the saturated state a pending dial or a backoff sleep produces. - #[tokio::test] - async fn an_evicted_cancellation_raises_the_prune_signal() { - let (handle, cmd_rx, prune_rx) = test_handle_capped(1); - - handle - .enqueue(ClientCmd::CancelCall { id: 1 }) - .expect("the engine is still running"); - assert!(prune_rx.is_empty(), "nothing has been evicted yet"); - - // Fills the single slot, displacing the cancellation. - handle - .write("tele", Payload::from(&b"x"[..])) - .expect("the engine is still running"); - - assert_eq!(cmd_rx.len(), 1, "the cap still holds"); - assert_eq!( - prune_rx.len(), - 1, - "an evicted cancellation must fall back to a sweep" - ); - } - - /// The negative control: eviction is the documented, caller-visible cost of - /// the bound for ordinary commands. Signalling on every one would drag an - /// `O(N)` sweep into steady-state backpressure. - #[tokio::test] - async fn an_evicted_write_raises_no_prune_signal() { - let (handle, _cmd_rx, prune_rx) = test_handle_capped(1); - - for topic in ["one", "two"] { - handle - .write(topic, Payload::from(&b"x"[..])) - .expect("the engine is still running"); - } - - assert!( - prune_rx.is_empty(), - "an evicted write is expected loss, not a leak" - ); - } - - /// A cancellation is bookkeeping; a queued `Write` is work the caller asked - /// for. Cap 2, so the write and the call itself both fit and the - /// cancellation is the only command that finds the queue full. - #[tokio::test] - async fn a_cancellation_never_evicts_a_queued_write() { - let (handle, cmd_rx, prune_rx) = test_handle_capped(2); - - handle - .write("tele", Payload::from(&b"x"[..])) - .expect("the engine is still running"); - abandon_call(&handle, "hang").await; - - assert_eq!(cmd_rx.len(), 2, "the cap still holds"); - match cmd_rx.try_recv() { - Ok(ClientCmd::Write { topic, .. }) => assert_eq!(topic, "tele"), - _ => panic!("the caller's write must survive the cancellation"), - } - match cmd_rx.try_recv() { - Ok(ClientCmd::Call { id: 1, .. }) => {} - _ => panic!("the call itself must still be queued"), - } - assert_eq!( - prune_rx.len(), - 1, - "the cancellation it could not queue must fall back to a sweep" - ); - } - - /// The reclaim itself: an abandoned entry goes, a live one stays. Identity - /// is the dropped receiver, which is why the sweep can stand in for a - /// cancellation that never arrived. - #[test] - fn the_sweep_frees_abandoned_entries_and_keeps_live_ones() { - let mut pending: PendingCalls = HashMap::new(); - let (abandoned, rx) = oneshot::channel(); - let (live, _live_rx) = oneshot::channel(); - pending.insert(1, abandoned); - pending.insert(2, live); - drop(rx); // the caller's future went away - - sweep_abandoned(&mut pending); - - assert!( - !pending.contains_key(&1), - "the abandoned call must be freed" - ); - assert!( - pending.contains_key(&2), - "a caller still awaiting its reply must not be dropped" - ); - } - - /// End to end at capacity 1 against a peer that answers nothing: the exact - /// loss the bound can inflict. The engine files a call while its caller - /// still waits, the caller then abandons it — the cancellation lands in the - /// drained queue — and a write evicts that cancellation. The engine still - /// reclaims: keepalive off and no later command, so the signal is the only - /// thing that can wake the sweep. - /// - /// Consuming the signal *is* the sweep running (one match arm), and - /// [`the_sweep_frees_abandoned_entries_and_keeps_live_ones`] pins what it - /// then does. The table is engine-local, and it cannot be watched from a - /// retained receiver either: an entry whose receiver is retained is exactly - /// the entry the sweep must keep. The timeout turns "never woke" into a - /// failure rather than a hang. - #[tokio::test] - async fn an_evicted_cancellation_is_still_reclaimed() { - use core::future::Future; - - let (handle, cmd_rx, prune_rx) = test_handle_capped(1); - let config = ClientConfig { - reconnect: false, - // Nothing but the signal may reclaim. - keepalive_interval: None, - ..Default::default() - }; - let ctx = - crate::RuntimeContext::new(Arc::new(crate::executor::test_support::NoopRuntimeOps)); - let engine = drive_connection( - Box::new(SilentPeer::default()), - &NullCodec, - &cmd_rx, - &prune_rx, - &config, - &ctx, - ); - - let exercise = async { - // Queue the call, then let the engine file it *while the caller - // still waits* — a receiver already dropped when the command is - // read is discarded on arrival and never reaches the table. - let mut call = Box::pin(handle.call("hang", Payload::from(&b"x"[..]))); - core::future::poll_fn(|cx| { - assert!( - call.as_mut().poll(cx).is_pending(), - "the call must not resolve" - ); - core::task::Poll::Ready(()) - }) - .await; - tokio::task::yield_now().await; - assert!(cmd_rx.is_empty(), "the engine must have filed the call"); - - // Abandon it: the queue is drained, so the cancellation lands. No - // yield before the write — the engine must not get the chance to - // remove the entry by id. - drop(call); - assert_eq!(cmd_rx.len(), 1, "the cancellation must be queued"); - assert!(prune_rx.is_empty(), "nothing has fallen back to a sweep"); - handle - .write("tele", Payload::from(&b"x"[..])) - .expect("the engine is still running"); - assert_eq!(prune_rx.len(), 1, "the eviction must have been noticed"); - - // The wake-up is the point: the engine is parked on a silent peer - // with keepalive off, so only the signal itself can reach it. - tokio::time::timeout(core::time::Duration::from_secs(5), async { - while !prune_rx.is_empty() { - tokio::task::yield_now().await; - } - }) - .await - .expect("the signal must wake the engine and be consumed"); - }; - - futures_util::pin_mut!(engine); - futures_util::pin_mut!(exercise); - match futures_util::future::select(engine, exercise).await { - futures_util::future::Either::Left(_) => panic!("the engine ended early"), - futures_util::future::Either::Right(((), _)) => {} - } - } - - /// The cap is a hard bound: nothing drains this channel, as during a pending - /// dial or a backoff sleep. - #[tokio::test] - async fn the_command_queue_is_bounded() { - let (handle, cmd_rx, _prune_rx) = test_handle_capped(2); - - for topic in ["one", "two", "three", "four"] { - handle - .write(topic, Payload::from(&b"x"[..])) - .expect("the engine is still running"); - } - - assert_eq!(cmd_rx.len(), 2, "the backlog must not exceed the cap"); - // Oldest-first: the two most recent writes are the ones kept. - for expected in ["three", "four"] { - match cmd_rx.try_recv() { - Ok(ClientCmd::Write { topic, .. }) => assert_eq!(topic, expected), - _ => panic!("the newest writes must survive eviction"), - } - } - } - - /// `usize::MAX` was the old "unbounded" sentinel; preallocated, it would abort - /// in the allocator, so it has to degrade to the ceiling instead. - #[tokio::test] - async fn an_unbounded_cap_degrades_to_the_ceiling() { - struct UndialableRemote; - impl Dialer for UndialableRemote { - fn connect(&self) -> BoxFut<'_, TransportResult>> { - Box::pin(async { Err(TransportError::Closed) }) - } - } - - let config = ClientConfig { - max_offline_queue: usize::MAX, - ..Default::default() - }; - let ctx = - crate::RuntimeContext::new(Arc::new(crate::executor::test_support::NoopRuntimeOps)); - let (handle, _engine) = run_client(UndialableRemote, NullCodec, config, ctx); - - handle - .write("t", Payload::from(&b"x"[..])) - .expect("the engine is still running"); - } - - /// A zero cap is clamped, not honored: every command reaches the engine - /// through this channel, so a zero-capacity one could never deliver. - #[tokio::test] - async fn a_zero_cap_is_clamped_to_one() { - let (handle, cmd_rx, _prune_rx) = test_handle_capped(0); - let (reply, rx) = oneshot::channel(); - - handle - .enqueue(ClientCmd::Call { - id: 1, - method: String::from("one"), - params: Payload::from(&b"x"[..]), - reply, - }) - .expect("the engine is still running"); - handle - .write("later", Payload::from(&b"x"[..])) - .expect("the engine is still running"); - - assert_eq!(cmd_rx.len(), 1, "a clamped cap still holds exactly one"); - assert!(rx.await.is_err(), "and the evicted caller learns it"); - } - - /// The cap is the channel's own, so it holds across cloned handles without an - /// admission lock: a full channel evicts rather than admitting a second sender. - #[tokio::test] - async fn cloned_handles_cannot_exceed_the_cap() { - let (handle, cmd_rx, _prune_rx) = test_handle_capped(1); - let other = handle.clone(); - - handle - .write("first", Payload::from(&b"x"[..])) - .expect("the engine is still running"); - other - .write("second", Payload::from(&b"x"[..])) - .expect("the engine is still running"); - - assert_eq!(cmd_rx.len(), 1, "clones share one bounded channel"); - match cmd_rx.try_recv() { - Ok(ClientCmd::Write { topic, .. }) => assert_eq!(topic, "second"), - _ => panic!("oldest-first eviction must hold across clones"), - } - } - - /// A trimmed command is not silently lost: it carried the only sender of its - /// reply channel, so the caller resolves rather than awaiting a reply the - /// engine will never send. - #[tokio::test] - async fn a_trimmed_call_fails_its_caller() { - let (handle, _cmd_rx, _prune_rx) = test_handle_capped(1); - let (reply, rx) = oneshot::channel(); - handle - .enqueue(ClientCmd::Call { - id: 1, - method: String::from("one"), - params: Payload::from(&b"x"[..]), - reply, - }) - .expect("the engine is still running"); - - // At cap 1 the next command displaces it. - handle - .write("later", Payload::from(&b"x"[..])) - .expect("the engine is still running"); - - assert!( - rx.await.is_err(), - "a trimmed call must not leave its caller waiting" - ); - } - - type SubSinks = HashMap>>; - type SubCursors = HashMap; - - /// One sink and its cursor, for driving [`deliver`] directly. - fn test_sink() -> (SubSinks, SubCursors, Receiver>) { - let (tx, rx) = async_channel::bounded(SUBSCRIBE_CHANNEL_CAP); - let mut subs = HashMap::new(); - subs.insert(String::from("1"), tx); - (subs, HashMap::new(), rx) - } - - fn deliver_event(subs: &mut SubSinks, last_seq: &mut SubCursors, seq: u64) { - deliver( - subs, - last_seq, - "1", - seq, - SubUpdate::new(Payload::from(&b"x"[..]), crate::Stamp::from_nanos(0)), - Delivery::Event, - ); - } - - /// `seq` arrives off the wire unvalidated, so the ceiling is reachable by a - /// peer. Computing the gap as `prev + 1` panicked in debug on the *next* - /// frame, and wrapped to a nonsense gap in release. - #[tokio::test] - async fn a_saturated_sequence_does_not_overflow() { - let (mut subs, mut last_seq, rx) = test_sink(); - - deliver_event(&mut subs, &mut last_seq, u64::MAX); - deliver_event(&mut subs, &mut last_seq, 5); - - let skips: Vec = core::iter::from_fn(|| rx.try_recv().ok()) - .map(|u| u.unwrap().skipped) - .collect(); - assert_eq!(skips.len(), 2, "both frames must be delivered"); - assert_eq!(skips[1], 0, "a saturated cursor cannot manufacture a gap"); - } - - /// A repeated or reordered `seq` is delivered but must not rewind the cursor: - /// a lower cursor makes the *next* valid frame look like a jump, reporting a - /// loss that never happened. - #[tokio::test] - async fn a_rewound_sequence_does_not_invent_a_gap() { - let (mut subs, mut last_seq, rx) = test_sink(); - - for seq in [1, 3, 2, 4] { - deliver_event(&mut subs, &mut last_seq, seq); - } - - let skips: Vec = core::iter::from_fn(|| rx.try_recv().ok()) - .map(|u| u.unwrap().skipped) - .collect(); - assert_eq!( - skips, - alloc::vec![0, 1, 0, 0], - "only the real gap (2 missing between 1 and 3) may be reported" - ); - assert_eq!(last_seq.get("1"), Some(&4)); - } - - /// A slow subscriber whose sink is already full of updates must still see - /// the terminal error, not buffered values followed by a bare EOF. - #[tokio::test] - async fn a_terminal_error_survives_a_full_sink() { - let (mut subs, mut last_seq, rx) = test_sink(); - - for seq in 1..=(SUBSCRIBE_CHANNEL_CAP as u64 + 10) { - deliver_event(&mut subs, &mut last_seq, seq); - } - end_sub(&mut subs, &mut last_seq, "1", RpcError::Protocol); - - let items: Vec<_> = core::iter::from_fn(|| rx.try_recv().ok()).collect(); - assert_eq!(items.len(), SUBSCRIBE_CHANNEL_CAP); - assert!(items[..items.len() - 1].iter().all(Result::is_ok)); - assert!(matches!(items.last(), Some(Err(RpcError::Protocol)))); - assert!(rx.is_closed(), "the sink is dropped after the error"); - } - - /// The mirror's loss contract (see [`inbound_pump`]): a server-reported gap - /// is stepped over, not treated as a fault. The update *carrying* `skipped` - /// is itself produced into the local record — it is current state, which is - /// all a mirror promises — and delivery continues past it. - #[tokio::test] - async fn a_mirror_gap_still_routes_and_keeps_mirroring() { - let seen: Arc>>> = Arc::new(spin::Mutex::new(Vec::new())); - let recorder = seen.clone(); - let ingest: crate::connector::IngestFn = Arc::new(move |_ctx, _m, bytes: &[u8]| { - recorder.lock().push(bytes.to_vec()); - Ok(crate::IngestOutcome::current()) - }); - let route = crate::router::CompiledRoute::exact("tele", ingest); - let router = crate::router::Router::new(&crate::ExactGrammar, alloc::vec![route]); - let ctx = - crate::RuntimeContext::new(Arc::new(crate::executor::test_support::NoopRuntimeOps)); - let inbound = crate::InboundDispatch::from_parts(router, ctx); - let (handle, cmd_rx, _prune_rx) = test_handle(); - - let pump = inbound_pump(handle, inbound, Arc::from("tele")); - let remote = async { - // The pump subscribes on its first poll; take its sink and play a - // gapped update followed by a clean one. - let events = match cmd_rx.recv().await { - Ok(ClientCmd::Subscribe { events, .. }) => events, - _ => panic!("the pump must subscribe"), - }; - for (data, skipped) in [(&b"gapped"[..], 7u64), (&b"after"[..], 0)] { - events - .send(Ok(SubUpdate::new( - Payload::from(data), - crate::Stamp::from_nanos(0), - ) - .with_skipped(skipped))) - .await - .expect("the pump holds the receiver"); - } - // Dropping the sink ends the stream, so the pump returns. - drop(events); - }; - #[cfg(feature = "std")] - let gap_seen = Arc::new(core::sync::atomic::AtomicUsize::new(0)); - #[cfg(feature = "std")] - let pump = crate::session::events::capture::future( - { - let seen = gap_seen.clone(); - Arc::new(move |event| match event { - SessionEvent::MirrorGap { topic, skipped } => { - assert_eq!((*topic, *skipped), ("tele", 7)); - seen.fetch_add(1, Ordering::Relaxed); - } - other => panic!("unexpected event: {other:?}"), - }) - }, - pump, - ); - futures_util::future::join(pump, remote).await; - #[cfg(feature = "std")] - assert_eq!(gap_seen.load(Ordering::Relaxed), 1); - - let seen = seen.lock(); - assert_eq!(seen.len(), 2, "the gap must not drop or end the mirror"); - assert_eq!( - seen[0].as_slice(), - b"gapped", - "the update reporting the gap must still be produced" - ); - assert_eq!(seen[1].as_slice(), b"after", "mirroring must continue"); - } -} +mod tests; diff --git a/aimdb-core/src/session/client/tests.rs b/aimdb-core/src/session/client/tests.rs new file mode 100644 index 00000000..b9fe3a2a --- /dev/null +++ b/aimdb-core/src/session/client/tests.rs @@ -0,0 +1,668 @@ +use super::*; +use crate::session::{CodecError, PeerInfo, TransportResult}; +use core::future::pending; + +/// Sink connection: swallows every frame and never yields one, i.e. a peer +/// that keeps the link open and answers nothing. +#[derive(Default)] +struct SilentPeer { + peer: PeerInfo, +} + +impl Connection for SilentPeer { + fn recv(&mut self) -> BoxFut<'_, TransportResult>>> { + Box::pin(pending()) + } + fn send<'a>(&'a mut self, _frame: &'a [u8]) -> BoxFut<'a, TransportResult<()>> { + Box::pin(async { Ok(()) }) + } + fn peer(&self) -> &PeerInfo { + &self.peer + } +} + +/// Frames are never inspected in these tests — only the pending-call +/// bookkeeping is. +struct NullCodec; + +impl EnvelopeCodec for NullCodec { + fn decode(&self, _frame: &[u8]) -> Result { + Err(CodecError::Malformed) + } + fn encode(&self, _msg: Outbound<'_>, _out: &mut Vec) -> Result<(), CodecError> { + Ok(()) + } + fn encode_inbound(&self, _msg: Inbound, _out: &mut Vec) -> Result<(), CodecError> { + Ok(()) + } + fn decode_outbound<'a>(&self, _frame: &'a [u8]) -> Result, CodecError> { + Err(CodecError::Malformed) + } +} + +/// A handle whose channel nobody drains — an engine still dialing, or +/// sleeping between redials. `cap` is [`ClientConfig::max_offline_queue`]. +/// The prune receiver comes back too: dropping it would close the signal +/// channel and silently no-op every [`ClientHandle::request_prune`]. +fn test_handle_capped(cap: usize) -> (ClientHandle, Receiver, Receiver<()>) { + let (cmd_tx, cmd_rx) = async_channel::bounded(cap.max(1)); + let (prune_tx, prune_rx) = async_channel::bounded(1); + ( + ClientHandle { + cmd_tx, + prune_tx, + next_id: Arc::new(AtomicUsize::new(1)), + inline_envelopes: true, + }, + cmd_rx, + prune_rx, + ) +} + +fn test_handle() -> (ClientHandle, Receiver, Receiver<()>) { + test_handle_capped(256) +} + +/// Poll a call once — enough to queue its command — then abandon it, which +/// is what a lost timeout race does to the future. +async fn abandon_call(handle: &ClientHandle, method: &'static str) { + let call = handle.call(method, Payload::from(&b"x"[..])); + assert!( + tokio::time::timeout(core::time::Duration::ZERO, call) + .await + .is_err(), + "the call must not resolve" + ); +} + +/// The caller half of the reclaim path: abandoning a call queues a +/// `CancelCall` naming exactly that call, so the engine never has to guess +/// which entry died. +#[tokio::test] +async fn abandoning_a_call_queues_its_cancellation() { + let (handle, cmd_rx, _prune_rx) = test_handle(); + abandon_call(&handle, "one").await; + + match cmd_rx.try_recv() { + Ok(ClientCmd::Call { id: 1, .. }) => {} + _ => panic!("the call must be queued first"), + } + match cmd_rx.try_recv() { + Ok(ClientCmd::CancelCall { id: 1 }) => {} + _ => panic!("abandoning the call must queue its cancellation"), + } + assert!(cmd_rx.is_empty(), "no other command is emitted"); +} + +/// A call that resolves normally must not also queue a cancellation — the +/// engine already dropped its entry when it routed the reply. +#[tokio::test] +async fn a_resolved_call_queues_no_cancellation() { + let (handle, cmd_rx, _prune_rx) = test_handle(); + let call = handle.call("one", Payload::from(&b"x"[..])); + let answer = async { + // Take the reply channel out of the queued command and answer it. + match cmd_rx.recv().await { + Ok(ClientCmd::Call { reply, .. }) => { + let _ = reply.send(Ok(Payload::from(&b"ok"[..]))); + } + _ => panic!("the call must be queued"), + } + }; + let (reply, ()) = futures_util::future::join(call, answer).await; + assert_eq!(&*reply.expect("the call resolves"), b"ok"); + assert!( + cmd_rx.is_empty(), + "a resolved call must not queue a cancellation" + ); +} + +/// Regression for the *concurrent* timeout batch: every call is issued and +/// tracked while its receiver is live, then all of them are abandoned at +/// once, with keepalive disabled and no later call to trigger a sweep. +/// +/// Each entry the engine frees drops its reply sender, which the (retained) +/// receiver observes as `Canceled` — so this asserts the table actually +/// empties rather than that some reclaim path merely ran. Pre-fix all 1000 +/// entries stayed until the connection ended. +#[tokio::test] +async fn a_concurrent_batch_of_cancellations_frees_every_entry() { + const BATCH: u64 = 1_000; + let (cmd_tx, cmd_rx) = async_channel::unbounded::(); + let config = ClientConfig { + reconnect: false, + // The point of the test: nothing but the cancellations can reclaim. + keepalive_interval: None, + ..Default::default() + }; + let ctx = crate::RuntimeContext::new(Arc::new(crate::executor::test_support::NoopRuntimeOps)); + // Never signalled: this asserts the by-id path reclaims on its own. + let (_prune_tx, prune_rx) = async_channel::bounded::<()>(1); + let engine = drive_connection( + Box::new(SilentPeer::default()), + &NullCodec, + &cmd_rx, + &prune_rx, + &config, + &ctx, + ); + + let exercise = async { + // All in flight at once: every receiver is alive as its call is + // tracked, so nothing is reclaimable until the batch is abandoned. + let mut replies = Vec::new(); + for id in 1..=BATCH { + let (reply, rx) = oneshot::channel(); + cmd_tx + .try_send(ClientCmd::Call { + id, + method: String::from("hang"), + params: Payload::from(&b"x"[..]), + reply, + }) + .expect("the channel is unbounded"); + replies.push(rx); + } + // Then the whole batch times out. + for id in 1..=BATCH { + cmd_tx + .try_send(ClientCmd::CancelCall { id }) + .expect("the channel is unbounded"); + } + for (i, rx) in replies.into_iter().enumerate() { + assert!( + rx.await.is_err(), + "call {} was still held by the engine", + i + 1 + ); + } + }; + + futures_util::pin_mut!(engine); + futures_util::pin_mut!(exercise); + match futures_util::future::select(engine, exercise).await { + futures_util::future::Either::Left(_) => panic!("the engine ended early"), + futures_util::future::Either::Right(((), _)) => {} + } +} + +/// The id counter refuses rather than wraps at its ceiling: a wrapped id +/// would re-issue one a live subscription still holds, and the engine would +/// demux that subscription's updates into the wrong sink. Both allocating +/// call sites fail, and neither reaches the engine — so no pending entry is +/// ever created under an id that would be mis-routed. +#[tokio::test] +async fn exhausted_ids_are_refused_not_wrapped() { + let (cmd_tx, cmd_rx) = async_channel::bounded(256); + let (prune_tx, _prune_rx) = async_channel::bounded(1); + let handle = ClientHandle { + cmd_tx, + prune_tx, + next_id: Arc::new(AtomicUsize::new(usize::MAX)), + inline_envelopes: true, + }; + + // Bounded at zero: the refusal happens before the id is queued, so it + // resolves on the first poll. A wrapping counter would instead queue the + // call and await a reply forever — the timeout turns that regression + // into a failure rather than a hang. + let refused = tokio::time::timeout( + core::time::Duration::ZERO, + handle.call("one", Payload::from(&b"x"[..])), + ) + .await + .expect("a refused call must not reach the engine and await a reply"); + assert!( + matches!(refused, Err(RpcError::Internal)), + "a call at the id ceiling must be refused" + ); + assert!( + handle.subscribe("tele").is_err(), + "a subscription at the id ceiling must be refused" + ); + assert!( + cmd_rx.is_empty(), + "a refused allocation must not reach the engine" + ); +} + +/// Evict-oldest puts a cancellation on the same lossy footing as a write, +/// but dropping one silently strands its pending entry until the connection +/// ends — so the eviction has to be noticed. Nothing drains the queue here: +/// the saturated state a pending dial or a backoff sleep produces. +#[tokio::test] +async fn an_evicted_cancellation_raises_the_prune_signal() { + let (handle, cmd_rx, prune_rx) = test_handle_capped(1); + + handle + .enqueue(ClientCmd::CancelCall { id: 1 }) + .expect("the engine is still running"); + assert!(prune_rx.is_empty(), "nothing has been evicted yet"); + + // Fills the single slot, displacing the cancellation. + handle + .write("tele", Payload::from(&b"x"[..])) + .expect("the engine is still running"); + + assert_eq!(cmd_rx.len(), 1, "the cap still holds"); + assert_eq!( + prune_rx.len(), + 1, + "an evicted cancellation must fall back to a sweep" + ); +} + +/// The negative control: eviction is the documented, caller-visible cost of +/// the bound for ordinary commands. Signalling on every one would drag an +/// `O(N)` sweep into steady-state backpressure. +#[tokio::test] +async fn an_evicted_write_raises_no_prune_signal() { + let (handle, _cmd_rx, prune_rx) = test_handle_capped(1); + + for topic in ["one", "two"] { + handle + .write(topic, Payload::from(&b"x"[..])) + .expect("the engine is still running"); + } + + assert!( + prune_rx.is_empty(), + "an evicted write is expected loss, not a leak" + ); +} + +/// A cancellation is bookkeeping; a queued `Write` is work the caller asked +/// for. Cap 2, so the write and the call itself both fit and the +/// cancellation is the only command that finds the queue full. +#[tokio::test] +async fn a_cancellation_never_evicts_a_queued_write() { + let (handle, cmd_rx, prune_rx) = test_handle_capped(2); + + handle + .write("tele", Payload::from(&b"x"[..])) + .expect("the engine is still running"); + abandon_call(&handle, "hang").await; + + assert_eq!(cmd_rx.len(), 2, "the cap still holds"); + match cmd_rx.try_recv() { + Ok(ClientCmd::Write { topic, .. }) => assert_eq!(topic, "tele"), + _ => panic!("the caller's write must survive the cancellation"), + } + match cmd_rx.try_recv() { + Ok(ClientCmd::Call { id: 1, .. }) => {} + _ => panic!("the call itself must still be queued"), + } + assert_eq!( + prune_rx.len(), + 1, + "the cancellation it could not queue must fall back to a sweep" + ); +} + +/// The reclaim itself: an abandoned entry goes, a live one stays. Identity +/// is the dropped receiver, which is why the sweep can stand in for a +/// cancellation that never arrived. +#[test] +fn the_sweep_frees_abandoned_entries_and_keeps_live_ones() { + let mut pending: PendingCalls = HashMap::new(); + let (abandoned, rx) = oneshot::channel(); + let (live, _live_rx) = oneshot::channel(); + pending.insert(1, abandoned); + pending.insert(2, live); + drop(rx); // the caller's future went away + + sweep_abandoned(&mut pending); + + assert!( + !pending.contains_key(&1), + "the abandoned call must be freed" + ); + assert!( + pending.contains_key(&2), + "a caller still awaiting its reply must not be dropped" + ); +} + +/// End to end at capacity 1 against a peer that answers nothing: the exact +/// loss the bound can inflict. The engine files a call while its caller +/// still waits, the caller then abandons it — the cancellation lands in the +/// drained queue — and a write evicts that cancellation. The engine still +/// reclaims: keepalive off and no later command, so the signal is the only +/// thing that can wake the sweep. +/// +/// Consuming the signal *is* the sweep running (one match arm), and +/// [`the_sweep_frees_abandoned_entries_and_keeps_live_ones`] pins what it +/// then does. The table is engine-local, and it cannot be watched from a +/// retained receiver either: an entry whose receiver is retained is exactly +/// the entry the sweep must keep. The timeout turns "never woke" into a +/// failure rather than a hang. +#[tokio::test] +async fn an_evicted_cancellation_is_still_reclaimed() { + use core::future::Future; + + let (handle, cmd_rx, prune_rx) = test_handle_capped(1); + let config = ClientConfig { + reconnect: false, + // Nothing but the signal may reclaim. + keepalive_interval: None, + ..Default::default() + }; + let ctx = crate::RuntimeContext::new(Arc::new(crate::executor::test_support::NoopRuntimeOps)); + let engine = drive_connection( + Box::new(SilentPeer::default()), + &NullCodec, + &cmd_rx, + &prune_rx, + &config, + &ctx, + ); + + let exercise = async { + // Queue the call, then let the engine file it *while the caller + // still waits* — a receiver already dropped when the command is + // read is discarded on arrival and never reaches the table. + let mut call = Box::pin(handle.call("hang", Payload::from(&b"x"[..]))); + core::future::poll_fn(|cx| { + assert!( + call.as_mut().poll(cx).is_pending(), + "the call must not resolve" + ); + core::task::Poll::Ready(()) + }) + .await; + tokio::task::yield_now().await; + assert!(cmd_rx.is_empty(), "the engine must have filed the call"); + + // Abandon it: the queue is drained, so the cancellation lands. No + // yield before the write — the engine must not get the chance to + // remove the entry by id. + drop(call); + assert_eq!(cmd_rx.len(), 1, "the cancellation must be queued"); + assert!(prune_rx.is_empty(), "nothing has fallen back to a sweep"); + handle + .write("tele", Payload::from(&b"x"[..])) + .expect("the engine is still running"); + assert_eq!(prune_rx.len(), 1, "the eviction must have been noticed"); + + // The wake-up is the point: the engine is parked on a silent peer + // with keepalive off, so only the signal itself can reach it. + tokio::time::timeout(core::time::Duration::from_secs(5), async { + while !prune_rx.is_empty() { + tokio::task::yield_now().await; + } + }) + .await + .expect("the signal must wake the engine and be consumed"); + }; + + futures_util::pin_mut!(engine); + futures_util::pin_mut!(exercise); + match futures_util::future::select(engine, exercise).await { + futures_util::future::Either::Left(_) => panic!("the engine ended early"), + futures_util::future::Either::Right(((), _)) => {} + } +} + +/// The cap is a hard bound: nothing drains this channel, as during a pending +/// dial or a backoff sleep. +#[tokio::test] +async fn the_command_queue_is_bounded() { + let (handle, cmd_rx, _prune_rx) = test_handle_capped(2); + + for topic in ["one", "two", "three", "four"] { + handle + .write(topic, Payload::from(&b"x"[..])) + .expect("the engine is still running"); + } + + assert_eq!(cmd_rx.len(), 2, "the backlog must not exceed the cap"); + // Oldest-first: the two most recent writes are the ones kept. + for expected in ["three", "four"] { + match cmd_rx.try_recv() { + Ok(ClientCmd::Write { topic, .. }) => assert_eq!(topic, expected), + _ => panic!("the newest writes must survive eviction"), + } + } +} + +/// `usize::MAX` was the old "unbounded" sentinel; preallocated, it would abort +/// in the allocator, so it has to degrade to the ceiling instead. +#[tokio::test] +async fn an_unbounded_cap_degrades_to_the_ceiling() { + struct UndialableRemote; + impl Dialer for UndialableRemote { + fn connect(&self) -> BoxFut<'_, TransportResult>> { + Box::pin(async { Err(TransportError::Closed) }) + } + } + + let config = ClientConfig { + max_offline_queue: usize::MAX, + ..Default::default() + }; + let ctx = crate::RuntimeContext::new(Arc::new(crate::executor::test_support::NoopRuntimeOps)); + let (handle, _engine) = run_client(UndialableRemote, NullCodec, config, ctx); + + handle + .write("t", Payload::from(&b"x"[..])) + .expect("the engine is still running"); +} + +/// A zero cap is clamped, not honored: every command reaches the engine +/// through this channel, so a zero-capacity one could never deliver. +#[tokio::test] +async fn a_zero_cap_is_clamped_to_one() { + let (handle, cmd_rx, _prune_rx) = test_handle_capped(0); + let (reply, rx) = oneshot::channel(); + + handle + .enqueue(ClientCmd::Call { + id: 1, + method: String::from("one"), + params: Payload::from(&b"x"[..]), + reply, + }) + .expect("the engine is still running"); + handle + .write("later", Payload::from(&b"x"[..])) + .expect("the engine is still running"); + + assert_eq!(cmd_rx.len(), 1, "a clamped cap still holds exactly one"); + assert!(rx.await.is_err(), "and the evicted caller learns it"); +} + +/// The cap is the channel's own, so it holds across cloned handles without an +/// admission lock: a full channel evicts rather than admitting a second sender. +#[tokio::test] +async fn cloned_handles_cannot_exceed_the_cap() { + let (handle, cmd_rx, _prune_rx) = test_handle_capped(1); + let other = handle.clone(); + + handle + .write("first", Payload::from(&b"x"[..])) + .expect("the engine is still running"); + other + .write("second", Payload::from(&b"x"[..])) + .expect("the engine is still running"); + + assert_eq!(cmd_rx.len(), 1, "clones share one bounded channel"); + match cmd_rx.try_recv() { + Ok(ClientCmd::Write { topic, .. }) => assert_eq!(topic, "second"), + _ => panic!("oldest-first eviction must hold across clones"), + } +} + +/// A trimmed command is not silently lost: it carried the only sender of its +/// reply channel, so the caller resolves rather than awaiting a reply the +/// engine will never send. +#[tokio::test] +async fn a_trimmed_call_fails_its_caller() { + let (handle, _cmd_rx, _prune_rx) = test_handle_capped(1); + let (reply, rx) = oneshot::channel(); + handle + .enqueue(ClientCmd::Call { + id: 1, + method: String::from("one"), + params: Payload::from(&b"x"[..]), + reply, + }) + .expect("the engine is still running"); + + // At cap 1 the next command displaces it. + handle + .write("later", Payload::from(&b"x"[..])) + .expect("the engine is still running"); + + assert!( + rx.await.is_err(), + "a trimmed call must not leave its caller waiting" + ); +} + +type SubSinks = HashMap>>; +type SubCursors = HashMap; + +/// One sink and its cursor, for driving [`deliver`] directly. +fn test_sink() -> (SubSinks, SubCursors, Receiver>) { + let (tx, rx) = async_channel::bounded(SUBSCRIBE_CHANNEL_CAP); + let mut subs = HashMap::new(); + subs.insert(String::from("1"), tx); + (subs, HashMap::new(), rx) +} + +fn deliver_event(subs: &mut SubSinks, last_seq: &mut SubCursors, seq: u64) { + deliver( + subs, + last_seq, + "1", + seq, + SubUpdate::new(Payload::from(&b"x"[..]), crate::Stamp::from_nanos(0)), + Delivery::Event, + ); +} + +/// `seq` arrives off the wire unvalidated, so the ceiling is reachable by a +/// peer. Computing the gap as `prev + 1` panicked in debug on the *next* +/// frame, and wrapped to a nonsense gap in release. +#[tokio::test] +async fn a_saturated_sequence_does_not_overflow() { + let (mut subs, mut last_seq, rx) = test_sink(); + + deliver_event(&mut subs, &mut last_seq, u64::MAX); + deliver_event(&mut subs, &mut last_seq, 5); + + let skips: Vec = core::iter::from_fn(|| rx.try_recv().ok()) + .map(|u| u.unwrap().skipped) + .collect(); + assert_eq!(skips.len(), 2, "both frames must be delivered"); + assert_eq!(skips[1], 0, "a saturated cursor cannot manufacture a gap"); +} + +/// A repeated or reordered `seq` is delivered but must not rewind the cursor: +/// a lower cursor makes the *next* valid frame look like a jump, reporting a +/// loss that never happened. +#[tokio::test] +async fn a_rewound_sequence_does_not_invent_a_gap() { + let (mut subs, mut last_seq, rx) = test_sink(); + + for seq in [1, 3, 2, 4] { + deliver_event(&mut subs, &mut last_seq, seq); + } + + let skips: Vec = core::iter::from_fn(|| rx.try_recv().ok()) + .map(|u| u.unwrap().skipped) + .collect(); + assert_eq!( + skips, + alloc::vec![0, 1, 0, 0], + "only the real gap (2 missing between 1 and 3) may be reported" + ); + assert_eq!(last_seq.get("1"), Some(&4)); +} + +/// A slow subscriber whose sink is already full of updates must still see +/// the terminal error, not buffered values followed by a bare EOF. +#[tokio::test] +async fn a_terminal_error_survives_a_full_sink() { + let (mut subs, mut last_seq, rx) = test_sink(); + + for seq in 1..=(SUBSCRIBE_CHANNEL_CAP as u64 + 10) { + deliver_event(&mut subs, &mut last_seq, seq); + } + end_sub(&mut subs, &mut last_seq, "1", RpcError::Protocol); + + let items: Vec<_> = core::iter::from_fn(|| rx.try_recv().ok()).collect(); + assert_eq!(items.len(), SUBSCRIBE_CHANNEL_CAP); + assert!(items[..items.len() - 1].iter().all(Result::is_ok)); + assert!(matches!(items.last(), Some(Err(RpcError::Protocol)))); + assert!(rx.is_closed(), "the sink is dropped after the error"); +} + +/// The mirror's loss contract (see [`inbound_pump`]): a server-reported gap +/// is stepped over, not treated as a fault. The update *carrying* `skipped` +/// is itself produced into the local record — it is current state, which is +/// all a mirror promises — and delivery continues past it. +#[tokio::test] +async fn a_mirror_gap_still_routes_and_keeps_mirroring() { + let seen: Arc>>> = Arc::new(spin::Mutex::new(Vec::new())); + let recorder = seen.clone(); + let ingest: crate::connector::IngestFn = Arc::new(move |_ctx, _m, bytes: &[u8]| { + recorder.lock().push(bytes.to_vec()); + Ok(crate::IngestOutcome::current()) + }); + let route = crate::router::CompiledRoute::exact("tele", ingest); + let router = crate::router::Router::new(&crate::ExactGrammar, alloc::vec![route]); + let ctx = crate::RuntimeContext::new(Arc::new(crate::executor::test_support::NoopRuntimeOps)); + let inbound = crate::InboundDispatch::from_parts(router, ctx); + let (handle, cmd_rx, _prune_rx) = test_handle(); + + let pump = inbound_pump(handle, inbound, Arc::from("tele")); + let remote = async { + // The pump subscribes on its first poll; take its sink and play a + // gapped update followed by a clean one. + let events = match cmd_rx.recv().await { + Ok(ClientCmd::Subscribe { events, .. }) => events, + _ => panic!("the pump must subscribe"), + }; + for (data, skipped) in [(&b"gapped"[..], 7u64), (&b"after"[..], 0)] { + events + .send(Ok(SubUpdate::new( + Payload::from(data), + crate::Stamp::from_nanos(0), + ) + .with_skipped(skipped))) + .await + .expect("the pump holds the receiver"); + } + // Dropping the sink ends the stream, so the pump returns. + drop(events); + }; + #[cfg(feature = "std")] + let gap_seen = Arc::new(core::sync::atomic::AtomicUsize::new(0)); + #[cfg(feature = "std")] + let pump = crate::session::events::capture::future( + { + let seen = gap_seen.clone(); + Arc::new(move |event| match event { + SessionEvent::MirrorGap { topic, skipped } => { + assert_eq!((*topic, *skipped), ("tele", 7)); + seen.fetch_add(1, Ordering::Relaxed); + } + other => panic!("unexpected event: {other:?}"), + }) + }, + pump, + ); + futures_util::future::join(pump, remote).await; + #[cfg(feature = "std")] + assert_eq!(gap_seen.load(Ordering::Relaxed), 1); + + let seen = seen.lock(); + assert_eq!(seen.len(), 2, "the gap must not drop or end the mirror"); + assert_eq!( + seen[0].as_slice(), + b"gapped", + "the update reporting the gap must still be produced" + ); + assert_eq!(seen[1].as_slice(), b"after", "mirroring must continue"); +} diff --git a/aimdb-core/src/typed_api.rs b/aimdb-core/src/typed_api.rs deleted file mode 100644 index 3315d56d..00000000 --- a/aimdb-core/src/typed_api.rs +++ /dev/null @@ -1,4088 +0,0 @@ -//! Type-safe Producer-Consumer API -//! -//! Provides the complete typed API for producer-consumer patterns including: -//! - `Producer` - Type-safe value production -//! - `Consumer` - Type-safe value consumption -//! - `RecordRegistrar` - Fluent record configuration API -//! - `RecordT` trait - Self-registering records -//! -//! # Producer Example -//! -//! ```no_run -//! # use aimdb_core::{Producer, RuntimeContext}; -//! # #[derive(Clone, Debug)] struct Temperature { celsius: f32 } -//! # async fn read_sensor() -> Temperature { Temperature { celsius: 21.0 } } -//! async fn temperature_producer( -//! ctx: RuntimeContext, -//! producer: Producer, -//! ) { -//! loop { -//! let temp = read_sensor().await; -//! producer.produce(temp); -//! ctx.time().sleep_secs(1).await; -//! } -//! } -//! ``` -//! -//! # Consumer Example -//! -//! ```no_run -//! # use aimdb_core::{Consumer, RuntimeContext}; -//! # #[derive(Clone, Debug)] struct Temperature { celsius: f32 } -//! async fn temperature_monitor( -//! ctx: RuntimeContext, -//! consumer: Consumer, -//! ) { -//! let mut rx = consumer.subscribe(); -//! // Each value comes with the metadata of the write that stored it. -//! while let Ok(temp) = rx.recv().await { -//! ctx.log().info(&format!( -//! "Temp: {:.1}°C, written at {:?}", -//! temp.value.celsius, -//! temp.stamp() -//! )); -//! } -//! } -//! ``` -//! -//! # Record Registration Example -//! -//! Illustrative (not compiled: `.buffer()` comes from your runtime adapter's -//! registrar extension trait, which `aimdb-core` cannot depend on): -//! -//! ```rust,ignore -//! let record_1 = aimdb_core::Name::::new("sensors.outdoor"); -//! builder.configure(record_1, |reg| { -//! reg.buffer(cfg) -//! .source(temperature_producer) -//! .tap(temperature_monitor) -//! .link_to("mqtt://sensors/temp") -//! .with_serializer(|_ctx, t| serde_json::to_vec(t)) -//! .finish(); -//! }); -//! ``` - -use core::fmt::Debug; -use core::future::Future; -use core::marker::PhantomData; - -use alloc::{ - boxed::Box, - string::{String, ToString}, - sync::Arc, - vec::Vec, -}; - -use crate::buffer::{DynBuffer, TryProduceError, WriteHandle}; -use crate::typed_record::TypedRecord; -use crate::AimDb; - -// ============================================================================ -// Producer - Type-safe value production -// ============================================================================ - -/// Type-safe producer for a specific record type -/// -/// `Producer` provides scoped access to produce values of type `T` only. -/// This follows the principle of least privilege - services only get access -/// to what they need, not the entire database. -/// -/// # Type Parameters -/// * `T` - The record type this producer can emit -/// -/// Pre-binds the record's buffer, latest-snapshot slot, and metadata tracker -/// (via an internal `Arc>`), so `produce()` is a single -/// virtual call rather than a `HashMap` lookup + downcast on each invocation -///. -/// -/// # Benefits -/// -/// - **Type Safety**: Compile-time guarantee of correct type -/// - **Testability**: Easy to mock for testing -/// - **Clear Intent**: Function signature shows what it produces -/// - **Decoupling**: No access to other record types -/// - **Security**: Cannot misuse database for unintended operations -pub struct Producer { - /// Pre-resolved write handle to the record's buffer/snapshot/metadata. - write: Arc>, - /// Stage profiling state (set by the spawn machinery for `.source()` stages). - #[cfg(feature = "observability")] - profiling: Option>, - // `fn() -> T` carries T without forcing Producer's Send/Sync to depend on T. - // T is only a type-system marker here — it is never stored or referenced. - _phantom: PhantomData T>, -} - -impl Producer -where - T: Send + 'static + Debug + Clone, -{ - /// Create a new producer bound to a pre-resolved write handle. - pub(crate) fn new(write: Arc>) -> Self { - Self { - write, - #[cfg(feature = "observability")] - profiling: None, - _phantom: PhantomData, - } - } - - /// Attaches stage profiling state. Internal — called by the spawn machinery. - #[cfg(feature = "observability")] - pub(crate) fn set_profiling( - &mut self, - metrics: Arc, - clock: crate::profiling::Clock, - ) { - self.profiling = Some(Arc::new(crate::profiling::ProducerProfilingState::new( - metrics, clock, - ))); - } - - /// Push a value. Infallible — overwrite-on-overflow buffers cannot reject. - /// Use this for fire-and-forget telemetry. - /// - /// Forwards the value to the record's buffer, the latest-snapshot slot, - /// and the metadata tracker in a single synchronous call. - /// - /// # Example - /// - /// ```no_run - /// # use aimdb_core::{Producer, RuntimeContext}; - /// # #[derive(Clone, Debug)] struct Telemetry { celsius: f32 } - /// # async fn read_sensor() -> Telemetry { Telemetry { celsius: 21.0 } } - /// async fn sensor_loop(ctx: RuntimeContext, producer: Producer) { - /// loop { - /// producer.produce(read_sensor().await); - /// ctx.time().sleep_secs(1).await; - /// } - /// } - /// ``` - pub fn produce(&self, value: T) { - #[cfg(feature = "observability")] - if let Some(state) = &self.profiling { - state.record_produce(); - } - self.write.push(value); - } - - /// Lets a write handle report that it rejected a value. - /// - /// All current buffers (`SpmcRing`, `SingleLatest`, `Mailbox`) overwrite - /// existing values when full and return `Ok(())`. Use - /// [`produce`](Self::produce) for them. A future buffer that refuses a - /// write when full can return the value through [`TryProduceError::Full`]. - /// A buffer that detects closure can return it through - /// [`TryProduceError::Closed`]. - /// - /// # Example - /// - /// ```no_run - /// # use aimdb_core::{Producer, TryProduceError}; - /// # #[derive(Clone, Debug)] struct Command { id: u32 } - /// fn send_command(producer: &Producer, cmd: Command) { - /// match producer.try_produce(cmd) { - /// Ok(()) => {} - /// Err(TryProduceError::Full(_)) => { /* backpressure: retry later */ } - /// Err(TryProduceError::Closed(_)) => { /* record shut down */ } - /// } - /// } - /// ``` - pub fn try_produce(&self, value: T) -> Result<(), TryProduceError> { - self.write.try_push(value) - } -} - -impl Clone for Producer { - fn clone(&self) -> Self { - Self { - write: self.write.clone(), - #[cfg(feature = "observability")] - profiling: self.profiling.clone(), - _phantom: PhantomData, - } - } -} - -// ============================================================================ -// Consumer - Type-safe value consumption -// ============================================================================ - -/// Type-safe consumer for a specific record type -/// -/// `Consumer` provides scoped access to subscribe to values of type `T` only. -/// This follows the principle of least privilege - services only get access -/// to what they need, not the entire database. -/// -/// # Type Parameters -/// * `T` - The record type this consumer can subscribe to -/// -/// # Benefits -/// -/// - **Type Safety**: Compile-time guarantee of correct type -/// - **Testability**: Easy to mock for testing -/// - **Clear Intent**: Function signature shows what it consumes -/// - **Decoupling**: No access to other record types -/// - **Security**: Cannot misuse database for unintended operations -pub struct Consumer { - /// Pre-resolved buffer handle to the record's buffer. - buffer: Arc>>, - /// Stage profiling state (set by the spawn machinery for `.tap()` / `.link_to()`). - #[cfg(feature = "observability")] - profiling: Option<(Arc, crate::profiling::Clock)>, - // See Producer: `fn() -> T` keeps Send/Sync independent of T. - _phantom: PhantomData T>, -} - -impl Consumer -where - T: Send + Sync + 'static + Debug + Clone, -{ - /// Create a new consumer bound to a pre-resolved buffer handle. - pub(crate) fn new(buffer: Arc>>) -> Self { - Self { - buffer, - #[cfg(feature = "observability")] - profiling: None, - _phantom: PhantomData, - } - } - - /// Attaches stage profiling state. Internal — called by the spawn machinery. - #[cfg(feature = "observability")] - pub(crate) fn set_profiling( - &mut self, - metrics: Arc, - clock: crate::profiling::Clock, - ) { - self.profiling = Some((metrics, clock)); - } - - /// Subscribe to updates for this record type. - /// - /// Returns a [`Reader`](crate::buffer::Reader) that yields values as they - /// are produced. Its `recv().await` is allocation-free. - /// Infallible — the buffer is pre-resolved at `Consumer` construction. - pub fn subscribe(&self) -> crate::buffer::Reader { - let reader = self.buffer.subscribe_boxed(); - #[cfg(feature = "observability")] - if let Some((metrics, clock)) = &self.profiling { - return crate::buffer::Reader::new(Box::new( - crate::profiling::ProfilingBufferReader::new( - reader, - metrics.clone(), - clock.clone(), - ), - )); - } - crate::buffer::Reader::new(reader) - } -} - -impl Clone for Consumer { - fn clone(&self) -> Self { - Self { - buffer: self.buffer.clone(), - #[cfg(feature = "observability")] - profiling: self.profiling.clone(), - _phantom: PhantomData, - } - } -} - -// ============================================================================ -// Outbound routes -// ============================================================================ - -/// Type alias for the unified typed serializer captured by [`TypedRoute`] -/// -/// Raw and context-aware serializers collapse into this shape at `finish()`; -/// the raw variant simply ignores the threaded context. -type FusedSerializeFn = Arc< - dyn Fn(&crate::RuntimeContext, &T) -> Result, crate::connector::SerializeError> - + Send - + Sync, ->; - -/// Builds a link's `Consumer` from the live database, once per route. -type ConsumerFactoryFn = Arc Consumer + Send + Sync>; - -/// Optional allocation-free serializer captured beside [`FusedSerializeFn`]. -/// -/// The callback writes into the `OutboundRoutes` scratch buffer. Returning -/// `BufferTooSmall` selects the owned serializer for that value; other failures -/// retain the existing skip-and-log behavior. -type FusedSerializeIntoFn = Arc< - dyn Fn(&crate::RuntimeContext, &T, &mut [u8]) -> Result - + Send - + Sync, ->; - -/// An outbound link's topic writer and the capacity it writes into. -type TopicWriterCfg = (usize, Arc>); - -/// Runs `writer` for `value` into `out`. `Ok(true)`: publish to what `out` -/// holds; `Ok(false)`: to the link's default topic; `Err`: the topic did not -/// fit and the value is skipped, whatever the writer returned. -fn write_topic + ?Sized>( - writer: &W, - value: &T, - out: &mut crate::connector::TopicBuf<'_>, -) -> Result { - match writer.write_topic(value, out) { - Ok(written) if !out.overflowed() => Ok(written), - _ => Err(crate::connector::TopicOverflow), - } -} - -/// Serializes one outbound value: into `scratch` through -/// `with_serializer_into` when the link has one, else (or when the value does -/// not fit) through the owned serializer. -fn serialize_outbound( - serialize: &FusedSerializeFn, - serialize_into: Option<&FusedSerializeIntoFn>, - ctx: &crate::RuntimeContext, - value: &T, - scratch: &mut [u8], -) -> Result { - use crate::connector::SerializeError; - use crate::outbound::{SerializeFailure, StagedPayload}; - - let Some(serialize_into) = serialize_into else { - return serialize(ctx, value) - .map(StagedPayload::Owned) - .map_err(SerializeFailure::Owned); - }; - match serialize_into(ctx, value, scratch) { - Ok(len) if len <= scratch.len() => Ok(StagedPayload::Scratch(len)), - Ok(len) => Err(SerializeFailure::InvalidLength { - len, - capacity: scratch.len(), - }), - Err(SerializeError::BufferTooSmall) => serialize(ctx, value) - .map(StagedPayload::Owned) - .map_err(SerializeFailure::Fallback), - Err(e) => Err(SerializeFailure::Into(e)), - } -} - -/// One outbound link's per-route state inside -/// [`OutboundRoutes`](crate::OutboundRoutes): reader, topic writer and -/// serializers, all typed. -struct TypedRoute { - reader: crate::buffer::Reader, - writer: Option>>, - serialize: FusedSerializeFn, - serialize_into: Option>, -} - -impl crate::outbound::PollRoute for TypedRoute { - fn poll_route( - &mut self, - cx: &mut core::task::Context<'_>, - ctx: &crate::RuntimeContext, - topic: &mut [u8], - payload: &mut [u8], - ) -> core::task::Poll { - use crate::outbound::RouteOutcome; - use core::task::Poll; - - let sample = match self.reader.poll_recv(cx) { - Poll::Pending => return Poll::Pending, - Poll::Ready(Ok(sample)) => sample, - Poll::Ready(Err(crate::DbError::BufferLagged { lag_count, .. })) => { - return Poll::Ready(RouteOutcome::Lagged(lag_count)); - } - Poll::Ready(Err(e)) => return Poll::Ready(RouteOutcome::Closed(e)), - }; - - let topic_len = match &self.writer { - None => None, - Some(writer) => { - let mut out = crate::connector::TopicBuf::new(topic); - match write_topic(&**writer, &sample.value, &mut out) { - Ok(written) => written.then_some(out.len()), - Err(_) => return Poll::Ready(RouteOutcome::TopicOverflow), - } - } - }; - - let serialized = serialize_outbound( - &self.serialize, - self.serialize_into.as_ref(), - ctx, - &sample.value, - payload, - ); - Poll::Ready(match serialized { - Ok(payload) => RouteOutcome::Staged { - topic_len, - payload, - metadata: *sample.metadata(), - }, - Err(failure) => RouteOutcome::SerializeFailed(failure), - }) - } -} - -// ============================================================================ -// RecordRegistrar - Fluent registration API -// ============================================================================ - -/// Type alias for typed context-aware serializer callbacks -/// -/// Stays typed until registration fuses it with the consumer — no per-message -/// erasure. -type TypedContextSerializerFn = Arc< - dyn Fn(crate::RuntimeContext, &T) -> Result, crate::connector::SerializeError> - + Send - + Sync - + 'static, ->; - -/// Typed into-slice serializer stored by [`OutboundLinkBuilder`]. -type TypedContextSerializerIntoFn = Arc< - dyn Fn(crate::RuntimeContext, &T, &mut [u8]) -> Result - + Send - + Sync - + 'static, ->; - -/// Kind of execution stage, used to address per-stage profiling metrics and to -/// remember which stage `RecordRegistrar::with_name` should rename. -#[doc(hidden)] -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub enum StageKind { - /// A `.source()` producer callback. - Source, - /// A `.tap()` observer callback. - Tap, - /// An outbound `.link_to()` connector. - Link, - /// A `.transform()` callback (reserved; not yet instrumented). - Transform, -} - -/// Registrar for configuring a typed record -/// -/// Provides a fluent API for registering producer and consumer functions. -/// -/// `S` is the record's [`SchemaState`](crate::SchemaState): `configure` -/// hands out [`Declared`](crate::Declared) for a key that declares a data -/// contract (`Key`, `#[record_key(contract = T)]`) and -/// [`Undeclared`](crate::Undeclared) otherwise. Contract-only verbs -/// (`linked_to`, `publish`, `observe`, …) are implemented only for -/// `Declared`, so using one on a `Name` record does not compile. -/// Everything else works in both states; extension traits implement for any -/// `S: SchemaState`. -pub struct RecordRegistrar< - 'a, - T: Send + Sync + 'static + Debug + Clone, - S: crate::SchemaState = crate::Undeclared, -> { - /// The typed record being configured - pub(crate) rec: &'a mut TypedRecord, - /// Connector builders indexed by scheme - pub(crate) connector_builders: &'a [Box], - /// The builder's id, checked against - /// [`ConnectorHandle`](crate::ConnectorHandle)s on links. - pub(crate) builder_id: u32, - /// The record key for this record - pub(crate) record_key: String, - pub(crate) key_link_address: Option, - /// Extension storage from the builder — allows external crates (e.g. - /// `aimdb-persistence`) to retrieve typed state inside `.persist()`. - pub(crate) extensions: &'a crate::extensions::Extensions, - /// The most recently registered stage, so `.with_name()` knows what to name. - /// Tracked even when the `observability` feature is off (then it's just unused). - #[cfg_attr(not(feature = "observability"), allow(dead_code))] - pub(crate) last_stage: Option<(StageKind, usize)>, - pub(crate) _schema: core::marker::PhantomData S>, -} - -impl<'a, T, S: crate::SchemaState> RecordRegistrar<'a, T, S> -where - T: Send + Sync + 'static + Debug + Clone, -{ - /// Returns a reference to the builder's extension storage. - /// - /// External crates call this inside their `.persist()` (or similar) extension - /// methods to retrieve typed state that was stored via - /// `builder.extensions_mut().insert(...)` before `configure()` was called. - pub fn extensions(&self) -> &crate::extensions::Extensions { - self.extensions - } - - /// Returns the key this record is registered under. - /// - /// Extension crates use it to name per-record state; `aimdb-persistence` - /// stores a record's history under this key. - pub fn record_key(&self) -> &str { - &self.record_key - } - - /// Assigns a human-readable name to the stage registered immediately before - /// this call (the most recent `.source()`, `.tap()`, or `.link_to()`). - /// - /// The name shows up in stage profiling output. This method is always - /// available; when the `observability` feature is disabled it is a no-op. - pub fn with_name(&mut self, name: &str) -> &mut Self { - #[cfg(feature = "observability")] - if let Some((kind, idx)) = self.last_stage { - self.rec.profiling_mut().set_stage_name(kind, idx, name); - } - #[cfg(not(feature = "observability"))] - let _ = name; - self - } - - /// Registers a signal gauge on this record and returns a handle to feed it. - /// - /// Values pushed via [`SignalGaugeHandle::update`](crate::SignalGaugeHandle::update) - /// fold into per-record last/min/max/mean statistics that surface on - /// `record.list` / `record.get` and stage profiling. This is the core hook - /// behind `aimdb-data-contracts`' `Observable::observe()`. - /// - /// Always available, mirroring [`with_name`](Self::with_name): when the - /// `observability` feature is disabled it returns an inert handle whose - /// `update` is a no-op, so callers never `#[cfg]` on core's features. - pub fn signal_gauge( - &mut self, - name: &'static str, - unit: &'static str, - ) -> crate::signal::SignalGaugeHandle { - #[cfg(feature = "observability")] - { - let stats = self.rec.profiling_mut().push_signal_gauge(name, unit); - crate::signal::SignalGaugeHandle::live(stats) - } - #[cfg(not(feature = "observability"))] - { - let _ = (name, unit); - crate::signal::SignalGaugeHandle::inert() - } - } - - /// Sets the data-contract schema this record carries, reported in the - /// dependency graph (`graph.nodes`) and in `record.list`. - /// - /// Only `configure` calls this, from the key's [`TypedKey::SCHEMA`](crate::TypedKey::SCHEMA): - /// the key is the one source of a record's schema (063). Setting the same - /// schema again does nothing; a different one fails `build()`. - #[cfg(test)] - pub(crate) fn schema(&mut self, name: &str, version: u32) -> &mut Self { - self.rec.set_schema(name, version); - self - } - - /// Registers a producer service for this record type. - /// - /// The closure receives the [`RuntimeContext`](crate::RuntimeContext) - /// (time + logging capabilities) and a pre-resolved [`Producer`]; it is - /// collected at `build()` time and driven by the `AimDbRunner`. - pub fn source(&mut self, f: F) -> &mut Self - where - F: FnOnce(crate::RuntimeContext, crate::Producer) -> Fut + Send + 'static, - Fut: Future + Send + 'static, - { - self.rec.set_producer(f); - #[cfg(feature = "observability")] - { - let (idx, _) = self.rec.profiling_mut().push_source(); - self.last_stage = Some((StageKind::Source, idx)); - } - #[cfg(not(feature = "observability"))] - { - self.last_stage = Some((StageKind::Source, 0)); - } - self - } - - /// Register a side-effect observer that taps into the data stream. - /// - /// The closure receives the [`RuntimeContext`](crate::RuntimeContext) and a - /// pre-resolved [`Consumer`]; it is collected at `build()` time and - /// driven by the `AimDbRunner`. Multiple taps per record are allowed. - pub fn tap(&mut self, f: F) -> &mut Self - where - F: FnOnce(crate::RuntimeContext, crate::Consumer) -> Fut + Send + 'static, - Fut: Future + Send + 'static, - T: Sync, - { - self.rec.add_consumer(f); - #[cfg(feature = "observability")] - { - let (idx, _) = self.rec.profiling_mut().push_tap(); - self.last_stage = Some((StageKind::Tap, idx)); - } - #[cfg(not(feature = "observability"))] - { - self.last_stage = Some((StageKind::Tap, 0)); - } - self - } - - /// Configures a buffer for this record (low-level API) - /// - /// **Note:** This is the foundational API used by runtime adapter implementations. - /// Most users should use the higher-level `buffer()` method provided by runtime - /// adapter extension traits (e.g., `TokioRecordRegistrarExt::buffer()`) which - /// accept `BufferCfg` and construct the appropriate buffer type automatically. - /// - /// This method accepts a boxed buffer trait object and is used by: - /// - Runtime adapter implementations to provide convenient wrappers - /// - Advanced use cases requiring custom buffer implementations - /// - /// **Note:** For metadata tracking in std mode, call `buffer_with_cfg()` instead, - /// or call `buffer_cfg()` separately to set the configuration. - pub fn buffer_raw( - &mut self, - buffer: Box>>, - ) -> &mut Self { - self.rec.set_buffer(buffer); - self - } - - /// Configures a buffer with metadata tracking - pub fn buffer_with_cfg( - &mut self, - buffer: Box>>, - cfg: crate::buffer::BufferCfg, - ) -> &mut Self { - self.rec.set_buffer(buffer); - self.rec.set_buffer_cfg(cfg); - self - } - - /// Sets the buffer configuration for metadata tracking - pub fn buffer_cfg(&mut self, cfg: crate::buffer::BufferCfg) -> &mut Self { - self.rec.set_buffer_cfg(cfg); - self - } - - /// Installs the JSON codec for this record (feature `remote`) - /// - /// Enables `record.latest()?.as_json()` and the AimX `record.get` / `set` / - /// `subscribe` protocol. Requires `T: RemoteSerialize` - /// (blanket-impl'd for every `Serialize + DeserializeOwned` type). Works on - /// no_std + alloc. - #[cfg(feature = "remote")] - pub fn with_remote_access(&mut self) -> &mut Self - where - T: crate::codec::RemoteSerialize + 'static, - { - self.rec.with_remote_access(); - self - } - - /// Register a single-input reactive transform. - /// - /// Conflicts with `.source()` and other `.transform()`s are recorded and - /// reported from `build()`. - /// - /// # Type Parameters - /// * `I` - The input record type to subscribe to - /// - /// # Arguments - /// * `input_key` - The record key to subscribe to as input - /// * `build_fn` - Closure that configures the transform pipeline via `TransformBuilder` - pub fn transform(&mut self, input_key: K, build_fn: F) -> &mut Self - where - K: crate::record_id::TypedKey, - F: FnOnce( - crate::transform::TransformBuilder, - ) -> crate::transform::TransformPipeline, - { - let input_key_str = input_key.as_str().to_string(); - let builder = crate::transform::TransformBuilder::::new(input_key_str); - let pipeline = build_fn(builder); - let descriptor = pipeline.into_descriptor(); - self.rec.set_transform(descriptor); - #[cfg(feature = "observability")] - { - let (idx, _) = self.rec.profiling_mut().push_transform(); - self.last_stage = Some((StageKind::Transform, idx)); - } - #[cfg(not(feature = "observability"))] - { - self.last_stage = Some((StageKind::Transform, 0)); - } - self - } - - /// Multi-input reactive transform (join). - /// - /// Derives this record from multiple input records. Available on every - /// runtime. Conflicts with `.source()` and other `.transform()`s are - /// recorded and reported from `build()`. - pub fn transform_join(&mut self, build_fn: F) -> &mut Self - where - F: FnOnce(crate::transform::JoinBuilder) -> crate::transform::JoinPipeline, - { - let builder = crate::transform::JoinBuilder::::new(); - let pipeline = build_fn(builder); - let descriptor = pipeline.into_descriptor(); - self.rec.set_transform(descriptor); - #[cfg(feature = "observability")] - { - let (idx, _) = self.rec.profiling_mut().push_transform(); - self.last_stage = Some((StageKind::Transform, idx)); - } - #[cfg(not(feature = "observability"))] - { - self.last_stage = Some((StageKind::Transform, 0)); - } - self - } - /// Builds a link using the address declared on this record's typed key. - /// A missing address is reported by `build()`. - pub fn link_to_key(&mut self) -> OutboundConnectorBuilder<'_, 'a, T, S> { - let address = self.key_link_address.clone().unwrap_or_default(); - self.link_to(&address) - } - /// Builds a link using the address declared on this record's typed key. - /// A missing address is reported by `build()`. - pub fn link_from_key(&mut self) -> InboundConnectorBuilder<'_, 'a, T, S> { - let address = self.key_link_address.clone().unwrap_or_default(); - self.link_from(&address) - } - - /// Link TO external system (outbound: AimDB → External) - /// - /// Subscribes to buffer updates and publishes them to an external system. - pub fn link_to(&mut self, url: &str) -> OutboundConnectorBuilder<'_, 'a, T, S> { - OutboundLink::new(url).attach(self) - } - - /// Link FROM external system (inbound: External → AimDB) - /// - /// Subscribes to an external data source and produces values into this record's buffer. - pub fn link_from(&mut self, url: &str) -> InboundConnectorBuilder<'_, 'a, T, S> { - InboundLink::new(url).attach(self) - } - - /// Wires `input` as a writer of this record. - /// - /// Takes anything implementing [`Input`], such as an [`InboundLink`]. - /// Conflicting writers are reported by `build()`, exactly as for - /// `.source()` and `.link_from()`; several inbound links on one record - /// are allowed (fan-in). - pub fn input(&mut self, input: impl Input) -> &mut Self { - input.wire(self); - self - } - - /// Wires `output` as a reader of this record. - /// - /// Takes anything implementing [`Output`], such as an - /// [`OutboundLink`]. A following [`with_name`](Self::with_name) names the - /// stage the output registered, as after `.link_to(..).finish()`. - pub fn output(&mut self, output: impl Output) -> &mut Self { - output.wire(self); - self - } -} - -// ============================================================================ -// Input / Output - what `.input()` and `.output()` accept -// ============================================================================ - -/// Something that can write into a `T` record, passed to -/// [`RecordRegistrar::input`]. -/// -/// [`InboundLink`] implements it. `wire` receives the full registrar, so an -/// input may call `.source()`, `.link_from()`, `.buffer()` or anything else a -/// `configure` closure can; inputs are expected to only add a writer. -/// -/// Two conventions make wiring mistakes compile errors: -/// -/// - **An input yields an event, and records are built with `From`.** A -/// device input implements `Input` for every `T: From`, so one -/// input type serves every contract that can be built from its event. -/// - **A device channel is an owned value that is not `Clone`.** A board -/// hands out its channels once, and an input takes one by value, so wiring -/// one device into two records is `use of moved value`. -/// -/// ``` -/// use aimdb_core::{Input, RecordRegistrar}; -/// use core::fmt::Debug; -/// -/// /// Produces 0, 1, 2 into any record built from an `i32`. -/// struct Counter; -/// -/// impl Input for Counter -/// where -/// T: From + Send + Sync + 'static + Debug + Clone, -/// { -/// fn wire(self, reg: &mut RecordRegistrar<'_, T, S>) { -/// reg.source(|_ctx, producer| async move { -/// for i in 0..3 { -/// producer.produce(T::from(i)); -/// } -/// }); -/// } -/// } -/// ``` -/// -/// A channel used for a second record does not compile: -/// -/// ```compile_fail,E0382 -/// # use aimdb_core::{Input, RecordRegistrar}; -/// # use core::fmt::Debug; -/// /// A device channel, handed out once by the board. Not `Clone`. -/// struct Channel; -/// -/// /// An input on one channel. -/// struct Sensor(Channel); -/// -/// impl Input for Sensor -/// where -/// T: From + Send + Sync + 'static + Debug + Clone, -/// { -/// fn wire(self, reg: &mut RecordRegistrar<'_, T, S>) { -/// reg.source(|_ctx, producer| async move { producer.produce(T::from(0)) }); -/// } -/// } -/// -/// #[derive(Clone, Debug)] -/// struct Level(u8); -/// -/// impl From for Level { -/// fn from(raw: u8) -> Self { -/// Level(raw) -/// } -/// } -/// -/// fn wire( -/// first: &mut RecordRegistrar<'_, Level>, -/// second: &mut RecordRegistrar<'_, Level>, -/// channel: Channel, -/// ) { -/// first.input(Sensor(channel)); -/// second.input(Sensor(channel)); // use of moved value: `channel` -/// } -/// ``` -#[diagnostic::on_unimplemented( - message = "`{Self}` cannot be the input of a `{T}` record", - label = "not an input for `{T}`", - note = "an input implements `Input<{T}>`; device inputs usually do so for every `T: From`" -)] -pub trait Input { - /// Registers this input's writer on the record. - fn wire(self, reg: &mut RecordRegistrar<'_, T, S>); -} - -/// Something that can read from a `T` record, passed to -/// [`RecordRegistrar::output`]. -/// -/// [`OutboundLink`] implements it. Like [`Input`], `wire` receives the -/// full registrar. -#[diagnostic::on_unimplemented( - message = "`{Self}` cannot be an output of a `{T}` record", - label = "not an output for `{T}`" -)] -pub trait Output { - /// Registers this output's reader on the record. - fn wire(self, reg: &mut RecordRegistrar<'_, T, S>); -} - -impl Input for InboundLink -where - T: Send + Sync + 'static + Debug + Clone, -{ - fn wire(self, reg: &mut RecordRegistrar<'_, T, S>) { - reg.push_inbound(self); - } -} - -impl Output for OutboundLink -where - T: Send + Sync + 'static + Debug + Clone, -{ - fn wire(self, reg: &mut RecordRegistrar<'_, T, S>) { - reg.push_outbound(self); - } -} - -/// A contract link is an input only of a record whose key declares the -/// contract: `subscribe(..)` on a `Name` record does not compile. -impl Input for ContractInboundLink -where - T: Send + Sync + 'static + Debug + Clone, -{ - fn wire(self, reg: &mut RecordRegistrar<'_, T, S>) { - reg.push_inbound(self.attach(Detached)); - } -} - -/// A contract link is an output only of a record whose key declares the -/// contract: `publish(..)` on a `Name` record does not compile. -impl Output for ContractOutboundLink -where - T: Send + Sync + 'static + Debug + Clone, -{ - fn wire(self, reg: &mut RecordRegistrar<'_, T, S>) { - reg.push_outbound(self.attach(Detached)); - } -} - -// ============================================================================ -// Link builders - Fluent connector link configuration -// ============================================================================ - -/// Marks a link builder that is not attached to a record yet. -/// -/// See [`OutboundLink`] and [`InboundLink`]. -#[derive(Debug, Clone, Copy, Default)] -pub struct Detached; - -/// Marks a detached link that carries a data contract: what -/// `aimdb-data-contracts`' `publish` / `subscribe` return. -/// -/// It takes every option a [`Detached`] link takes, but is an -/// [`Input`] / [`Output`] only of a record whose key declares the contract -/// ([`ContractDeclared`](crate::ContractDeclared)). -#[derive(Debug, Clone, Copy, Default)] -pub struct DetachedContract; - -/// Outbound link builder attached to a record: what -/// [`RecordRegistrar::link_to`] returns. -/// -/// `'r` is the borrow of the registrar taken by `link_to()`; `'a` is the -/// registrar's own borrow of the record being configured. -pub type OutboundConnectorBuilder<'r, 'a, T, S = crate::Undeclared> = - OutboundLinkBuilder>; - -/// Outbound link not attached to a record yet, built with -/// [`OutboundLink::new`] and registered by [`RecordRegistrar::output`]. -pub type OutboundLink = OutboundLinkBuilder; - -/// Outbound link carrying a data contract, built by -/// [`OutboundLink::into_contract`]: an [`Output`] only of a record whose key -/// declares the contract. -pub type ContractOutboundLink = OutboundLinkBuilder; - -type OutboundWireFinalizer = - Arc) -> Result, String> + Send + Sync>; - -/// Builder for configuring outbound connector links (AimDB → External) -/// -/// `R` is what the builder is attached to. [`RecordRegistrar::link_to`] -/// returns the attached form, [`OutboundConnectorBuilder`], which -/// [`finish()`](OutboundLinkBuilder::finish) registers on its record. -/// [`OutboundLink::new`] builds the detached form, [`OutboundLink`], before -/// any record exists; [`RecordRegistrar::output`] registers it, and checks -/// it then, not when it is built. Both register the same link: -/// -/// ```rust,ignore -/// reg.link_to("mqtt://out").with_serializer(ser).finish(); -/// reg.output(OutboundLink::new("mqtt://out").with_serializer(ser)); -/// ``` -/// -/// The option methods below, and the connector crates' extension traits, -/// work on both forms. -#[must_use = "a link does nothing until it is passed to `.output()` or finished with `.finish()`"] -pub struct OutboundLinkBuilder { - wire: crate::link_wire::WireOptions, - wire_codec: Option, - wire_finalizer: Option>, - at: R, - url: String, - connector: Option, - config: Vec<(String, String)>, - context_serializer: Option>, - context_serializer_into: Option<(usize, TypedContextSerializerIntoFn)>, - topic_writer: Option>, -} - -impl OutboundLinkBuilder -where - T: Send + Sync + 'static + Debug + Clone, -{ - /// Starts an outbound link to `address` on a connector registered with - /// [`AimDbBuilder::connect`](crate::AimDbBuilder::connect). - /// - /// `address` is the part after `scheme://`; the connector supplies the - /// scheme. A full URL (as a `#[link_address]` key gives) is accepted if - /// its scheme is the connector's. A different scheme, or a handle from - /// another builder, is reported by `build()` once the link is passed to - /// [`RecordRegistrar::output`]. - pub fn on(connector: crate::ConnectorHandle, address: &str) -> Self { - Self { - connector: Some(connector), - ..Self::new(address) - } - } - - /// Starts an outbound link to `url` that is not attached to a record yet. - pub fn new(url: &str) -> Self { - Self { - at: Detached, - wire: Default::default(), - wire_codec: None, - wire_finalizer: None, - url: url.to_string(), - connector: None, - config: Vec::new(), - context_serializer: None, - context_serializer_into: None, - topic_writer: None, - } - } - - /// Marks this link as carrying a data contract, so it wires only into a - /// record whose key declares the contract. `aimdb-data-contracts`' - /// `publish` calls this; the link's options are unchanged. - pub fn into_contract(self) -> ContractOutboundLink { - self.attach(DetachedContract) - } -} - -impl OutboundLinkBuilder -where - T: Send + Sync + 'static + Debug + Clone, -{ - fn attach(self, at: R) -> OutboundLinkBuilder { - OutboundLinkBuilder { - at, - wire: self.wire, - wire_codec: self.wire_codec, - wire_finalizer: self.wire_finalizer, - url: self.url, - connector: self.connector, - config: self.config, - context_serializer: self.context_serializer, - context_serializer_into: self.context_serializer_into, - topic_writer: self.topic_writer, - } - } -} - -impl OutboundLinkBuilder -where - T: Send + Sync + 'static + Debug + Clone, -{ - #[doc(hidden)] - pub fn wire_options(&self) -> crate::link_wire::WireOptions { - self.wire - } - #[doc(hidden)] - pub fn with_wire_options(mut self, options: crate::link_wire::WireOptions) -> Self { - self.wire = options; - self - } - #[doc(hidden)] - pub fn wire_codec_info(&self) -> Option { - self.wire_codec - } - #[doc(hidden)] - pub fn with_wire_codec_info(mut self, info: Option) -> Self { - self.wire_codec = info; - self - } - #[doc(hidden)] - pub fn with_wire_finalizer(mut self, replace: bool, finalize: F) -> Self - where - F: Fn(OutboundLink) -> Result, String> + Send + Sync + 'static, - { - if replace || self.wire_finalizer.is_none() { - self.wire_finalizer = Some(Arc::new(finalize)); - } - self - } - - fn detach(self) -> (R, OutboundLink) { - let link = OutboundLinkBuilder { - at: Detached, - wire: self.wire, - wire_codec: self.wire_codec, - wire_finalizer: self.wire_finalizer, - url: self.url, - connector: self.connector, - config: self.config, - context_serializer: self.context_serializer, - context_serializer_into: self.context_serializer_into, - topic_writer: self.topic_writer, - }; - (self.at, link) - } - - /// Adds a configuration option to the connector - pub fn with_config(mut self, key: &str, value: &str) -> Self { - self.config.push((key.to_string(), value.to_string())); - self - } - - /// Drops any recorded [`WIRE_FORMAT_KEY`](crate::connector::WIRE_FORMAT_KEY): - /// a newly installed codec closure has no known format until a codec verb - /// records one. - fn clear_wire_format(mut self) -> Self { - self.wire_codec = None; - self.config - .retain(|(key, _)| key != crate::connector::WIRE_FORMAT_KEY); - self - } - - /// Sets the serialization callback - /// - /// The closure receives the [`RuntimeContext`](crate::RuntimeContext) for - /// platform-independent timestamps and logging, plus the typed value being - /// serialized. Ignore the context parameter (`|_ctx, value| …`) when it is - /// not needed. Removes any recorded - /// [`WIRE_FORMAT_KEY`](crate::connector::WIRE_FORMAT_KEY). - pub fn with_serializer(mut self, f: F) -> Self - where - F: Fn(crate::RuntimeContext, &T) -> Result, crate::connector::SerializeError> - + Send - + Sync - + 'static, - { - self.context_serializer = Some(Arc::new(f)); - self.clear_wire_format() - } - - /// Adds an into-slice fast path beside the required owned serializer. - /// - /// One zero-initialized scratch buffer of `capacity` bytes is allocated when - /// each route pump starts, then reused for every message. A successful - /// callback returns the initialized prefix length. The framework validates - /// that length before borrowing the prefix. `BufferTooSmall` falls back to - /// [`with_serializer`](Self::with_serializer) for that value; any other - /// codec error is logged and the value is skipped. - /// - /// This method is an optimization only: callers must still install the - /// owned serializer so oversized and legacy values retain their old behavior. - /// Removes any recorded [`WIRE_FORMAT_KEY`](crate::connector::WIRE_FORMAT_KEY). - pub fn with_serializer_into(mut self, capacity: usize, f: F) -> Self - where - F: Fn( - crate::RuntimeContext, - &T, - &mut [u8], - ) -> Result - + Send - + Sync - + 'static, - { - self.context_serializer_into = Some((capacity, Arc::new(f))); - self.clear_wire_format() - } - - /// Removes a previously installed into-slice serializer. - /// - /// Higher-level builder extensions use this when replacing a bounded - /// serialization strategy with an owned-only one. Clearing the fast path - /// prevents the old scratch serializer from emitting a different wire - /// format beside the replacement owned serializer. - pub fn clear_serializer_into(mut self) -> Self { - self.context_serializer_into = None; - self - } - - /// Sets the operation timeout in milliseconds (the connector interprets - /// it; passed as the `timeout_ms` option — see - /// `ConnectorConfig::from_query`) - /// - /// Protocol-specific knobs (e.g. MQTT QoS/retain) are provided by the - /// connector crates as extension traits over this builder, or generically - /// via [`with_config`](Self::with_config). - pub fn with_timeout_ms(mut self, timeout_ms: u32) -> Self { - self.config - .push(("timeout_ms".to_string(), timeout_ms.to_string())); - self - } - - /// Sets a [`TopicWriter`](crate::connector::TopicWriter) that writes each - /// value's destination. - /// - /// `capacity` is the longest topic the writer produces, in bytes. A value - /// whose topic does not fit is skipped and logged. For a closure, use - /// [`with_topic_fn`](Self::with_topic_fn). - pub fn with_topic_writer(mut self, capacity: usize, writer: W) -> Self - where - W: crate::connector::TopicWriter + 'static, - { - self.topic_writer = Some((capacity, Arc::new(writer))); - self - } - - /// Sets a closure that writes each value's destination; see - /// [`with_topic_writer`](Self::with_topic_writer). - /// - /// ```rust,ignore - /// .with_topic_fn(32, |v, out| { - /// write!(out, "sensors/{}/{}", v.site, v.id)?; - /// Ok(true) - /// }) - /// ``` - pub fn with_topic_fn(self, capacity: usize, f: F) -> Self - where - F: Fn( - &T, - &mut crate::connector::TopicBuf<'_>, - ) -> Result - + Send - + Sync - + 'static, - { - self.with_topic_writer(capacity, f) - } -} - -impl<'r, 'a, T, S: crate::SchemaState> OutboundLinkBuilder> -where - T: Send + Sync + 'static + Debug + Clone, -{ - /// Finalizes the connector registration - /// - /// Configuration mistakes — an invalid URL, a missing serializer, or an - /// unregistered scheme — are recorded instead of panicking: the link is - /// **not** registered and `build()` reports every finding via - /// `DbError::InvalidConfiguration`. The registrar is returned either way - /// so chained configuration keeps compiling; the failed `build()` is the - /// single error surface. - /// - /// The buffer requirement is validated by `build()` (calling `.buffer()` - /// after `.link_to()` is fine). - pub fn finish(self) -> &'r mut RecordRegistrar<'a, T, S> { - let (registrar, link) = self.detach(); - registrar.push_outbound(link); - registrar - } -} - -// ============================================================================ -// InboundLinkBuilder - Fluent inbound connector configuration -// ============================================================================ - -/// The producer an inbound ingest factory writes to. Factories run during -/// build() after every record is registered and validated, so a failed lookup -/// is an aimdb bug, not a user mistake. -#[allow( - clippy::panic, - reason = "the factory returns no Result and this lookup was validated at build() time" -)] -fn inbound_producer(db: &AimDb, record_key: &str) -> Producer -where - T: Send + Sync + 'static + Debug + Clone, -{ - let writer = db - .inner() - .get_typed_record_by_key_raw::(record_key) - .and_then(|rec| rec.writer_handle()) - .unwrap_or_else(|e| { - panic!( - "ingest factory: no producer for record '{record_key}' ({e:?}) — \ - this is a bug in aimdb-core" - ) - }); - Producer::::new(writer) -} - -/// Fused ingest factory: resolves the typed producer once at route-collection -/// time; per message the returned closure runs deserialize + produce with no -/// erasure crossing. -fn ingest_factory( - record_key: String, - deser: TypedMatchDeserializerFn, -) -> crate::connector::IngestFactoryFn -where - T: Send + Sync + 'static + Debug + Clone, -{ - Arc::new(move |db: &AimDb| { - let producer = inbound_producer::(db, &record_key); - let deser = deser.clone(); - Arc::new( - move |ctx: &crate::RuntimeContext, m: &crate::TopicMatch<'_>, payload: &[u8]| { - let admitted = deser(ctx, m, payload)?; - producer.produce(admitted.value); - Ok(admitted.outcome) - }, - ) as crate::connector::IngestFn - }) -} - -/// Type alias for typed context-aware deserializer callbacks -/// -/// Stays typed until registration fuses it with the producer — no -/// per-message erasure. -type TypedContextDeserializerFn = Arc< - dyn Fn(crate::RuntimeContext, &[u8]) -> Result, crate::IngestError> - + Send - + Sync - + 'static, ->; - -/// Like [`TypedContextDeserializerFn`], also receiving the topic match. -type TypedMatchDeserializerFn = Arc< - dyn Fn( - &crate::RuntimeContext, - &crate::TopicMatch<'_>, - &[u8], - ) -> Result, crate::IngestError> - + Send - + Sync - + 'static, ->; - -type InboundWireFinalizer = - Arc) -> Result, String> + Send + Sync>; - -/// Inbound link builder attached to a record: what -/// [`RecordRegistrar::link_from`] returns. -/// -/// `'r` is the borrow of the registrar taken by `link_from()`; `'a` is the -/// registrar's own borrow of the record being configured. -pub type InboundConnectorBuilder<'r, 'a, T, S = crate::Undeclared> = - InboundLinkBuilder>; - -/// Inbound link not attached to a record yet, built with -/// [`InboundLink::new`] and registered by [`RecordRegistrar::input`]. -pub type InboundLink = InboundLinkBuilder; - -/// Inbound link carrying a data contract, built by -/// [`InboundLink::into_contract`]: an [`Input`] only of a record whose key -/// declares the contract. -pub type ContractInboundLink = InboundLinkBuilder; - -/// Builder for configuring inbound connector links (External → AimDB) -/// -/// `R` is what the builder is attached to. [`RecordRegistrar::link_from`] -/// returns the attached form, [`InboundConnectorBuilder`], which -/// [`finish()`](InboundLinkBuilder::finish) registers on its record. -/// [`InboundLink::new`] builds the detached form, [`InboundLink`], before -/// any record exists; [`RecordRegistrar::input`] registers it, and checks -/// it then, not when it is built. Both register the same link: -/// -/// ```rust,ignore -/// reg.link_from("mqtt://in").with_deserializer(de).finish(); -/// reg.input(InboundLink::new("mqtt://in").with_deserializer(de)); -/// ``` -/// -/// The option methods below, and the connector crates' extension traits, -/// work on both forms. -#[must_use = "a link does nothing until it is passed to `.input()` or finished with `.finish()`"] -pub struct InboundLinkBuilder { - wire: crate::link_wire::WireOptions, - wire_codec: Option, - wire_finalizer: Option>, - at: R, - url: String, - connector: Option, - config: Vec<(String, String)>, - context_deserializer: Option>, - match_deserializer: Option>, - upgrade_versions: Vec, - key: Option<(String, u16)>, - topic_resolver: Option, -} - -impl InboundLinkBuilder -where - T: Send + Sync + 'static + Debug + Clone, -{ - /// Starts an inbound link from `address` on a connector registered with - /// [`AimDbBuilder::connect`](crate::AimDbBuilder::connect). - /// - /// `address` is the part after `scheme://`; the connector supplies the - /// scheme. A full URL (as a `#[link_address]` key gives) is accepted if - /// its scheme is the connector's. A different scheme, or a handle from - /// another builder, is reported by `build()` once the link is passed to - /// [`RecordRegistrar::input`]. - pub fn on(connector: crate::ConnectorHandle, address: &str) -> Self { - Self { - connector: Some(connector), - ..Self::new(address) - } - } - - /// Starts an inbound link from `url` that is not attached to a record yet. - pub fn new(url: &str) -> Self { - Self { - at: Detached, - wire: Default::default(), - wire_codec: None, - wire_finalizer: None, - url: url.to_string(), - connector: None, - config: Vec::new(), - context_deserializer: None, - match_deserializer: None, - upgrade_versions: Vec::new(), - key: None, - topic_resolver: None, - } - } - - /// Marks this link as carrying a data contract, so it wires only into a - /// record whose key declares the contract. `aimdb-data-contracts`' - /// `subscribe` calls this; the link's options are unchanged. - pub fn into_contract(self) -> ContractInboundLink { - self.attach(DetachedContract) - } -} - -impl InboundLinkBuilder -where - T: Send + Sync + 'static + Debug + Clone, -{ - fn attach(self, at: R) -> InboundLinkBuilder { - InboundLinkBuilder { - at, - wire: self.wire, - wire_codec: self.wire_codec, - wire_finalizer: self.wire_finalizer, - url: self.url, - connector: self.connector, - config: self.config, - context_deserializer: self.context_deserializer, - match_deserializer: self.match_deserializer, - upgrade_versions: self.upgrade_versions, - key: self.key, - topic_resolver: self.topic_resolver, - } - } -} - -impl InboundLinkBuilder -where - T: Send + Sync + 'static + Debug + Clone, -{ - #[doc(hidden)] - pub fn wire_options(&self) -> crate::link_wire::WireOptions { - self.wire - } - #[doc(hidden)] - pub fn with_wire_options(mut self, options: crate::link_wire::WireOptions) -> Self { - self.wire = options; - self - } - #[doc(hidden)] - pub fn wire_codec_info(&self) -> Option { - self.wire_codec - } - #[doc(hidden)] - pub fn with_wire_codec_info(mut self, info: Option) -> Self { - self.wire_codec = info; - self - } - #[doc(hidden)] - pub fn with_wire_finalizer(mut self, replace: bool, finalize: F) -> Self - where - F: Fn(InboundLink) -> Result, String> + Send + Sync + 'static, - { - if replace || self.wire_finalizer.is_none() { - self.wire_finalizer = Some(Arc::new(finalize)); - } - self - } - - fn detach(self) -> (R, InboundLink) { - let link = InboundLinkBuilder { - at: Detached, - wire: self.wire, - wire_codec: self.wire_codec, - wire_finalizer: self.wire_finalizer, - url: self.url, - connector: self.connector, - config: self.config, - context_deserializer: self.context_deserializer, - match_deserializer: self.match_deserializer, - upgrade_versions: self.upgrade_versions, - key: self.key, - topic_resolver: self.topic_resolver, - }; - (self.at, link) - } - - /// Adds a configuration option to the connector - pub fn with_config(mut self, key: &str, value: &str) -> Self { - self.config.push((key.to_string(), value.to_string())); - self - } - - /// Drops any recorded [`WIRE_FORMAT_KEY`](crate::connector::WIRE_FORMAT_KEY): - /// a newly installed codec closure has no known format until a codec verb - /// records one. - fn clear_wire_format(mut self) -> Self { - self.wire_codec = None; - self.config - .retain(|(key, _)| key != crate::connector::WIRE_FORMAT_KEY); - self - } - - /// Sets the deserialization callback - /// - /// The closure receives the [`RuntimeContext`](crate::RuntimeContext) for - /// platform-independent timestamps and logging, plus the raw bytes from - /// the external system. Ignore the context parameter (`|_ctx, data| …`) - /// when it is not needed. Removes any recorded - /// [`WIRE_FORMAT_KEY`](crate::connector::WIRE_FORMAT_KEY). - pub fn with_deserializer(mut self, f: F) -> Self - where - F: Fn(crate::RuntimeContext, &[u8]) -> Result - + Send - + Sync - + 'static, - { - self.context_deserializer = Some(Arc::new(move |ctx, bytes| { - f(ctx, bytes).map(crate::IngestValue::current) - })); - self.upgrade_versions.clear(); - self.clear_wire_format() - } - - /// Like [`with_deserializer`](Self::with_deserializer), also receiving the - /// topic the message arrived on, its captures and its key. The context is - /// borrowed, so no reference count changes per message. Removes any - /// recorded [`WIRE_FORMAT_KEY`](crate::connector::WIRE_FORMAT_KEY). - pub fn with_match_deserializer(mut self, f: F) -> Self - where - F: Fn( - &crate::RuntimeContext, - &crate::TopicMatch<'_>, - &[u8], - ) -> Result - + Send - + Sync - + 'static, - { - self.match_deserializer = Some(Arc::new(move |ctx, m, bytes| { - f(ctx, m, bytes).map(crate::IngestValue::current) - })); - self.upgrade_versions.clear(); - self.clear_wire_format() - } - - /// Installs contract admission with success metadata and declared source - /// versions. Counters are allocated once at registration. Like the match - /// deserializer, this borrows the context and receives wildcard captures. - pub fn with_admitting_deserializer(mut self, versions: &[u32], f: F) -> Self - where - F: Fn( - &crate::RuntimeContext, - &crate::TopicMatch<'_>, - &[u8], - ) -> Result, crate::IngestError> - + Send - + Sync - + 'static, - { - self.match_deserializer = Some(Arc::new(f)); - self.upgrade_versions = versions.to_vec(); - self.clear_wire_format() - } - - /// Clear both inbound callback slots before installing a complete strategy. - #[doc(hidden)] - pub fn clear_deserializers(mut self) -> Self { - self.context_deserializer = None; - self.match_deserializer = None; - self - } - - /// Assigns each value of capture `name` a [`KeyId`](crate::KeyId), up to - /// `capacity` values per record. Messages with a value beyond that are - /// dropped. A value keeps its key even if its payload fails to - /// deserialize, and keys are never freed, so anyone who can publish under - /// the pattern can fill the table. - pub fn key(mut self, name: &str, capacity: u16) -> Self { - self.key = Some((name.to_string(), capacity)); - self - } - - /// Sets the operation timeout in milliseconds (the connector interprets - /// it; passed as the `timeout_ms` option — see - /// `ConnectorConfig::from_query`) - /// - /// Protocol-specific knobs (e.g. MQTT subscribe QoS) are provided by the - /// connector crates as extension traits over this builder, or generically - /// via [`with_config`](Self::with_config). - pub fn with_timeout_ms(mut self, timeout_ms: u32) -> Self { - self.config - .push(("timeout_ms".to_string(), timeout_ms.to_string())); - self - } - - /// Sets a dynamic topic resolver for late-binding scenarios - /// - /// The resolver is called once at connector startup to determine - /// the subscription topic. Return `None` to use the default - /// static topic from the URL. - /// - /// # Use Cases - /// - /// - Topics determined from smart contracts at runtime - /// - Service discovery integration - /// - Environment-specific topic configuration - pub fn with_topic_resolver(mut self, resolver: F) -> Self - where - F: Fn() -> Option + Send + Sync + 'static, - { - self.topic_resolver = Some(Arc::new(resolver)); - self - } -} - -impl<'r, 'a, T, S: crate::SchemaState> InboundLinkBuilder> -where - T: Send + Sync + 'static + Debug + Clone, -{ - /// Finalizes the inbound connector registration - /// - /// Configuration mistakes — an invalid URL, a missing deserializer, an - /// unregistered scheme, or a conflict with `.source()`/`.transform()` - /// (local producer + inbound connector would race as last-writer-wins) — - /// are recorded instead of panicking: the link is **not** registered and - /// `build()` reports every finding via `DbError::InvalidConfiguration`. - /// The registrar is returned either way so chained configuration keeps - /// compiling; the failed `build()` is the single error surface. - /// - /// The buffer requirement is validated by `build()` (calling `.buffer()` - /// after `.link_from()` is fine). - pub fn finish(self) -> &'r mut RecordRegistrar<'a, T, S> { - let (registrar, link) = self.detach(); - registrar.push_inbound(link); - registrar - } -} - -// ============================================================================ -// Link registration - the one validation path for attached and detached links -// ============================================================================ - -/// The wire state a detached link of either direction carries into -/// registration. -trait WireLink: Sized { - fn wire_url(&self) -> &str; - fn wire_parts( - &mut self, - ) -> ( - &mut crate::link_wire::WireOptions, - &mut Vec<(String, String)>, - ); - #[allow(clippy::type_complexity)] - fn take_wire_finalizer( - &mut self, - ) -> Option Result + Send + Sync>>; -} - -macro_rules! wire_link { - ($link:ident) => { - impl WireLink for $link { - fn wire_url(&self) -> &str { - &self.url - } - fn wire_parts( - &mut self, - ) -> ( - &mut crate::link_wire::WireOptions, - &mut Vec<(String, String)>, - ) { - (&mut self.wire, &mut self.config) - } - fn take_wire_finalizer( - &mut self, - ) -> Option Result + Send + Sync>> { - self.wire_finalizer.take() - } - } - }; -} -wire_link!(OutboundLink); -wire_link!(InboundLink); - -impl<'a, T, S: crate::SchemaState> RecordRegistrar<'a, T, S> -where - T: Send + Sync + 'static + Debug + Clone, -{ - /// Resolves the carrier and runs the link's wire finalizer: the one path - /// for both directions. Records a config error and returns `None` if the - /// link is refused. - fn finalize_wire(&mut self, mut link: L) -> Option { - let url = link.wire_url().to_string(); - let finalized = (|| { - let (wire, config) = link.wire_parts(); - wire.take_carrier(config)?; - if let Some(finalize) = link.take_wire_finalizer() { - link = finalize(link)?; - } else if link.wire_parts().0.carrier == crate::EnvelopeCarrier::Inline { - return Err( - "inline envelopes require with_envelope or with_versioned_codec".into(), - ); - } - let (wire, config) = link.wire_parts(); - wire.record_carrier(config); - Ok::(link) - })(); - match finalized { - Ok(link) => Some(link), - Err(message) => { - self.rec.push_config_error(crate::ConfigError::new( - self.record_key.clone(), - Some(url), - message, - )); - None - } - } - } - - /// Validates and registers an outbound link, or records why not. - fn push_outbound(&mut self, link: OutboundLink) { - let Some(mut link) = self.finalize_wire(link) else { - return; - }; - - use crate::connector::{ConnectorLink, LinkAddress}; - use crate::error::ConfigError; - - let record_key = self.record_key.clone(); - - if let Some(handle) = link.connector { - match crate::connector::resolve_link_url( - self.builder_id, - self.connector_builders, - handle, - &link.url, - ) { - Ok(url) => link.url = url, - Err(message) => { - self.rec.push_config_error(ConfigError::new( - record_key, - Some(link.url), - message, - )); - return; - } - } - } - - let Ok(url) = LinkAddress::parse(&link.url) else { - self.rec.push_config_error(ConfigError::new( - record_key, - Some(link.url), - "Invalid connector URL", - )); - return; - }; - - let url_string = url.to_string(); - let scheme = url.scheme().to_string(); - - if url.resource_id().contains(['{', '}']) { - self.rec.push_config_error(ConfigError::new( - record_key, - Some(link.url), - "Outbound topics cannot contain '{' or '}'", - )); - return; - } - - // Adapt the stored serializer to the fused calling convention. Stays - // typed: fused with the consumer below, no `Box` per message - //. - let serialize: FusedSerializeFn = if let Some(ser) = link.context_serializer { - Arc::new(move |ctx: &crate::RuntimeContext, value: &T| ser(ctx.clone(), value)) - } else { - self.rec.push_config_error(ConfigError::new( - record_key, - Some(link.url), - "Outbound connector requires a serializer. Call .with_serializer()", - )); - return; - }; - - let serialize_into: Option<(usize, FusedSerializeIntoFn)> = - link.context_serializer_into.map(|(capacity, ser)| { - let adapted: FusedSerializeIntoFn = Arc::new( - move |ctx: &crate::RuntimeContext, value: &T, out: &mut [u8]| { - ser(ctx.clone(), value, out) - }, - ); - (capacity, adapted) - }); - - // Validation: Check that connector builder is registered - let has_connector = self.connector_builders.iter().any(|b| b.scheme() == scheme); - - if !has_connector { - self.rec.push_config_error(ConfigError::new( - record_key, - Some(url_string), - alloc::format!( - "No connector registered for scheme '{scheme}'. Register via .with_connector()" - ), - )); - return; - } - - // Register the link as a profiling stage (so `.with_name()` can name it - // and the consumer it creates can be timed). - #[cfg(feature = "observability")] - let link_metrics = { - let (idx, metrics) = self.rec.profiling_mut().push_link(); - self.last_stage = Some((StageKind::Link, idx)); - metrics - }; - #[cfg(not(feature = "observability"))] - { - self.last_stage = Some((StageKind::Link, 0)); - } - - // Resolves the record and builds a `Consumer` bound to its buffer - // handle, once per route (not per message) — same pattern as the - // build-time path in `TypedRecord::collect_consumer_futures`. - // - // The factories run during build() after every record is registered - // and validated (including the linked-records-need-a-buffer check), - // so failures here are aimdb bugs, not user mistakes. - #[allow( - clippy::panic, - reason = "the factory returns no Result and these lookups were validated at build() time" - )] - let make_consumer: ConsumerFactoryFn = { - let record_key = self.record_key.clone(); - Arc::new(move |db: &AimDb| { - let typed_rec = db - .inner() - .get_typed_record_by_key_raw::(&record_key) - .unwrap_or_else(|e| { - panic!( - "outbound link: record '{record_key}' lookup failed ({e:?}) — \ - this is a bug in aimdb-core" - ) - }); - let buffer = typed_rec.buffer_handle().unwrap_or_else(|| { - panic!( - "outbound link: record '{record_key}' has no buffer despite \ - build()-time validation — this is a bug in aimdb-core" - ) - }); - - #[allow(unused_mut)] - let mut consumer = Consumer::::new(buffer); - #[cfg(feature = "observability")] - consumer.set_profiling(link_metrics.clone(), db.profiling_clock().clone()); - consumer - }) - }; - - let topic_writer = link.topic_writer; - let has_topic_writer = topic_writer.is_some(); - - // Renders the record's current value through this link's topic writer - // and serializer, for late-join snapshots (`OutboundLatest`). - let latest_fn: crate::outbound::LatestFn = { - let record_key = self.record_key.clone(); - let topic_writer = topic_writer.clone(); - let serialize = serialize.clone(); - let serialize_into = serialize_into.clone(); - Arc::new( - move |db: &AimDb, - ctx: &crate::RuntimeContext, - accept: &dyn Fn(Option<&str>) -> bool| { - let sample = db - .inner() - .get_typed_record_by_key_raw::(&record_key) - .ok()? - .latest()? - .into_stamped(); - - let topic = match &topic_writer { - None => None, - Some((capacity, writer)) => { - let mut buf = alloc::vec![0u8; *capacity]; - let mut out = crate::connector::TopicBuf::new(&mut buf); - let written = write_topic(&**writer, &sample.value, &mut out).ok()?; - let len = out.len(); - // `TopicBuf` only ever holds whole `&str`s. - written - .then(|| String::from_utf8(buf[..len].to_vec()).ok()) - .flatten() - } - }; - // Serialize only for a topic the caller wants. - if !accept(topic.as_deref()) { - return None; - } - - let mut scratch = alloc::vec![0u8; serialize_into.as_ref().map_or(0, |(capacity, _)| *capacity)]; - let payload = match serialize_outbound( - &serialize, - serialize_into.as_ref().map(|(_, f)| f), - ctx, - &sample.value, - &mut scratch, - ) - .ok()? - { - crate::outbound::StagedPayload::Scratch(len) => scratch[..len].to_vec(), - crate::outbound::StagedPayload::Owned(bytes) => bytes, - }; - - Some(crate::outbound::Rendered { - topic, - payload, - metadata: *sample.metadata(), - }) - }, - ) - }; - - // Subscribed when `OutboundRoutes` is built. - let route_factory: crate::outbound::RouteFactoryFn = { - Arc::new(move |db: &AimDb| { - let (topic_capacity, writer) = match &topic_writer { - Some((capacity, writer)) => (*capacity, Some(writer.clone())), - None => (0, None), - }; - crate::outbound::RouteParts { - route: Box::new(TypedRoute { - reader: make_consumer(db).subscribe(), - writer, - serialize: serialize.clone(), - serialize_into: serialize_into.as_ref().map(|(_, f)| f.clone()), - }), - topic_capacity, - payload_capacity: serialize_into.as_ref().map_or(0, |(capacity, _)| *capacity), - } - }) - }; - - // Named `out`, not `link`: `out.config = link.config` must read the - // user's link, not the new one. - let mut out = ConnectorLink::new(url, route_factory, latest_fn, has_topic_writer); - out.config = link.config; - - // Routes are built later, when a connector builds its `OutboundRoutes`. - self.rec.add_outbound_connector(out); - } - - /// Validates and registers an inbound link, or records why not. - fn push_inbound(&mut self, link: InboundLink) { - let Some(mut link) = self.finalize_wire(link) else { - return; - }; - - match self.inbound_link(&mut link) { - Ok(inbound) => self.rec.add_inbound_connector(inbound), - Err(message) => { - let key = self.record_key.clone(); - let error = crate::error::ConfigError::new(key, Some(link.url), message); - self.rec.push_config_error(error); - } - } - } - - /// The link `push_inbound()` registers, or why it is rejected. - /// - /// The buffer requirement and mutual exclusion with local producers - /// (.source()/.transform()) are validated by `build()`: `.buffer()` may - /// legitimately be called after `.link_from()`. - fn inbound_link( - &self, - link: &mut InboundLink, - ) -> Result { - use crate::connector::{InboundConnectorLink, LinkAddress}; - - if let Some(handle) = link.connector { - link.url = crate::connector::resolve_link_url( - self.builder_id, - self.connector_builders, - handle, - &link.url, - )?; - } - let url = LinkAddress::parse(&link.url).map_err(|_| "Invalid connector URL")?; - let record_key = self.record_key.clone(); - - let deser: TypedMatchDeserializerFn = match ( - link.context_deserializer.take(), - link.match_deserializer.take(), - ) { - (Some(deser), None) => Arc::new(move |ctx, _m, bytes| deser(ctx.clone(), bytes)), - (None, Some(deser)) => deser, - (Some(_), Some(_)) => { - return Err( - "Set either .with_deserializer() or .with_match_deserializer(), not both" - .into(), - ) - } - (None, None) => { - return Err("Inbound connector requires a deserializer. Call \ - .with_deserializer() or .with_match_deserializer()" - .into()) - } - }; - - // The `{…}` syntax; the connector checks the rest. - let pattern = crate::TopicPattern::parse(url.resource_id()).map_err(|e| e.to_string())?; - - let key = match link.key.take() { - None => None, - Some((capture, capacity)) => { - let Some(capacity) = core::num::NonZeroU16::new(capacity) else { - return Err(alloc::format!( - "key '{capture}' needs a capacity of at least 1" - )); - }; - if !pattern.capture_names().any(|n| n == capture) { - return Err(alloc::format!( - "key '{capture}' is not a capture of the topic" - )); - } - let links = self.rec.inbound_connectors(); - if let Some((_, other)) = links.iter().find_map(|l| l.key.as_ref()) { - if *other != capacity { - return Err(alloc::format!( - "key '{capture}' has capacity {capacity}, another keyed link of \ - this record has {other}" - )); - } - } - Some((capture, capacity)) - } - }; - - let scheme = url.scheme(); - if !self.connector_builders.iter().any(|b| b.scheme() == scheme) { - return Err(alloc::format!( - "No connector registered for scheme '{scheme}'. Register via .with_connector()" - )); - } - - // Named `inbound`, not `link`, for the same reason as in `push_outbound`. - let mut inbound = InboundConnectorLink::new(url, ingest_factory(record_key, deser)) - .with_upgrade_versions(&link.upgrade_versions); - inbound.config = core::mem::take(&mut link.config); - inbound.key = key; - inbound.topic_resolver = link.topic_resolver.take(); - Ok(inbound) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::{connector::SerializeError, DbResult}; - use core::pin::Pin; - - #[cfg(not(feature = "std"))] - use alloc::vec; - - #[allow(dead_code)] - #[derive(Clone, Debug)] - struct TestRecord { - value: i32, - } - - #[test] - fn test_link_address_simple() { - use crate::connector::LinkAddress; - let addr = LinkAddress::parse("mqtt://sensors").unwrap(); - assert_eq!(addr.scheme(), "mqtt"); - assert_eq!(addr.resource_id(), "sensors"); - } - - #[test] - fn test_link_address_multi_level() { - use crate::connector::LinkAddress; - let addr = LinkAddress::parse("mqtt://sensors/temperature").unwrap(); - assert_eq!(addr.resource_id(), "sensors/temperature"); - } - - #[test] - fn test_link_address_deep() { - use crate::connector::LinkAddress; - let addr = LinkAddress::parse("mqtt://factory/floor1/sensors/temp").unwrap(); - assert_eq!(addr.resource_id(), "factory/floor1/sensors/temp"); - } - - // ==================================================================== - // Test infrastructure for InboundLinkBuilder deserializer tests - // ==================================================================== - - /// Minimal mock runtime for context tests — the builder only needs the - /// dyn-safe `RuntimeOps` surface, supplied by the shared test stub. - use crate::executor::test_support::NoopRuntimeOps as MockRuntime; - - /// Minimal mock buffer so `has_buffer()` returns true - struct MockBuffer; - - impl crate::buffer::DynBuffer> for MockBuffer { - fn push(&self, _value: crate::Stamped) {} - fn subscribe_boxed( - &self, - ) -> Box> + Send> { - unimplemented!("not needed for deserializer tests") - } - fn as_any(&self) -> &dyn core::any::Any { - self - } - } - - /// Mock connector builder that reports a given scheme - struct MockConnectorBuilder { - scheme: String, - } - - impl crate::connector::ConnectorBuilder for MockConnectorBuilder { - fn build<'a>( - &'a self, - _db: &'a crate::AimDb, - ) -> Pin< - Box< - dyn Future< - Output = DbResult + Send + 'static>>>>, - > + Send - + 'a, - >, - > { - unimplemented!("not needed for deserializer tests") - } - fn scheme(&self) -> &str { - &self.scheme - } - } - - /// Helper: build a RecordRegistrar wired to a TypedRecord with a buffer and a - /// mock connector builder for the given scheme. - fn make_registrar<'a>( - rec: &'a mut crate::typed_record::TypedRecord, - builders: &'a [Box], - extensions: &'a crate::extensions::Extensions, - ) -> RecordRegistrar<'a, TestRecord> { - RecordRegistrar { - rec, - connector_builders: builders, - builder_id: TEST_BUILDER, - record_key: "test::Record".to_string(), - key_link_address: None, - extensions, - last_stage: None, - _schema: core::marker::PhantomData, - } - } - - // ==================================================================== - // Inbound link registration tests (fused ingest) - // ==================================================================== - - #[test] - fn inbound_finish_registers_fused_link() { - let mut rec = crate::typed_record::TypedRecord::::new(); - rec.set_buffer(Box::new(MockBuffer)); - - let builders: Vec> = - vec![Box::new(MockConnectorBuilder { - scheme: "mqtt".to_string(), - })]; - let extensions = crate::extensions::Extensions::new(); - - let mut reg = make_registrar(&mut rec, &builders, &extensions); - - reg.link_from("mqtt://broker/topic") - .with_deserializer(|_ctx, bytes: &[u8]| { - Ok(TestRecord { - value: bytes.len() as i32, - }) - }) - .finish(); - - assert_eq!(rec.inbound_connectors().len(), 1); - assert_eq!(rec.inbound_connectors()[0].resolve_topic(), "broker/topic"); - assert!(drain_errors(&mut rec).is_empty()); - } - - /// Drains the configuration errors a registrar/setter recorded on `rec`. - fn drain_errors( - rec: &mut crate::typed_record::TypedRecord, - ) -> Vec { - use crate::typed_record::AnyRecord; - rec.drain_config_errors() - } - - #[test] - fn inbound_finish_without_deserializer_records_error() { - let mut rec = crate::typed_record::TypedRecord::::new(); - rec.set_buffer(Box::new(MockBuffer)); - - let builders: Vec> = - vec![Box::new(MockConnectorBuilder { - scheme: "mqtt".to_string(), - })]; - let extensions = crate::extensions::Extensions::new(); - - let mut reg = make_registrar(&mut rec, &builders, &extensions); - - // No deserializer set — error recorded, link not registered - reg.link_from("mqtt://broker/topic").finish(); - - assert!(rec.inbound_connectors().is_empty()); - let errors = drain_errors(&mut rec); - assert_eq!(errors.len(), 1); - assert!(errors[0] - .message - .contains("Inbound connector requires a deserializer")); - assert_eq!(errors[0].record_key, "test::Record"); - assert_eq!(errors[0].url.as_deref(), Some("mqtt://broker/topic")); - } - - // ==================================================================== - // Topic patterns and keys on inbound links - // ==================================================================== - - /// Runs `configure` against a fresh registrar with an `mqtt` connector - /// and returns the record's links and recorded errors. - fn register( - configure: impl FnOnce(&mut RecordRegistrar<'_, TestRecord>), - ) -> ( - Vec, - Vec, - ) { - let mut rec = crate::typed_record::TypedRecord::::new(); - rec.set_buffer(Box::new(MockBuffer)); - let builders: Vec> = - vec![Box::new(MockConnectorBuilder { - scheme: "mqtt".to_string(), - })]; - let extensions = crate::extensions::Extensions::new(); - configure(&mut make_registrar(&mut rec, &builders, &extensions)); - (rec.inbound_connectors().to_vec(), drain_errors(&mut rec)) - } - - fn match_deser( - _ctx: &crate::RuntimeContext, - m: &crate::TopicMatch<'_>, - _bytes: &[u8], - ) -> Result { - Ok(TestRecord { - value: m.topic().len() as i32, - }) - } - - #[test] - fn inbound_finish_registers_match_link_with_key() { - let (links, errors) = register(|reg| { - reg.link_from("mqtt://s/{device}/t") - .key("device", 16) - .with_match_deserializer(match_deser) - .finish(); - }); - assert!(errors.is_empty(), "{errors:?}"); - let (capture, capacity) = links[0].key.clone().unwrap(); - assert_eq!((capture.as_str(), capacity.get()), ("device", 16)); - } - - #[test] - fn inbound_finish_rejects_both_deserializers() { - let (links, errors) = register(|reg| { - reg.link_from("mqtt://s/{device}/t") - .with_deserializer(|_ctx, _bytes: &[u8]| Ok(TestRecord { value: 0 })) - .with_match_deserializer(match_deser) - .finish(); - }); - assert!(links.is_empty()); - assert!(errors[0].message.contains("not both"), "{:?}", errors[0]); - } - - #[test] - fn inbound_finish_rejects_invalid_pattern_syntax() { - for topic in [ - "s/{d", - "s/{}", - "s/{d-1}", - "{d}/{d}", - "{a}/{b}/{c}/{d}/{e}/{f}/{g}/{h}/{i}", - ] { - let url = alloc::format!("mqtt://{topic}"); - let (links, errors) = register(|reg| { - reg.link_from(&url) - .with_deserializer(|_ctx, _bytes: &[u8]| Ok(TestRecord { value: 0 })) - .finish(); - }); - assert!(links.is_empty(), "{topic}"); - assert_eq!(errors.len(), 1, "{topic}"); - assert_eq!(errors[0].record_key, "test::Record"); - assert_eq!(errors[0].url.as_deref(), Some(url.as_str())); - } - } - - #[test] - fn inbound_finish_rejects_bad_keys() { - for (topic, key, capacity, needle) in [ - ("s/{d}/t", "device", 4, "not a capture"), - ("s/{d}/t", "d", 0, "at least 1"), - ] { - let (links, errors) = register(|reg| { - reg.link_from(&alloc::format!("mqtt://{topic}")) - .key(key, capacity) - .with_match_deserializer(match_deser) - .finish(); - }); - assert!(links.is_empty()); - assert!(errors[0].message.contains(needle), "{:?}", errors[0]); - } - } - - #[test] - fn keyed_links_of_one_record_share_a_capacity() { - let (links, errors) = register(|reg| { - reg.link_from("mqtt://temp/{d}") - .key("d", 8) - .with_match_deserializer(match_deser) - .finish(); - reg.link_from("mqtt://hum/{id}") - .key("id", 8) - .with_match_deserializer(match_deser) - .finish(); - reg.link_from("mqtt://co2/{id}") - .key("id", 16) - .with_match_deserializer(match_deser) - .finish(); - }); - assert_eq!(links.len(), 2); - assert_eq!(errors.len(), 1); - assert!(errors[0].message.contains("has 8"), "{:?}", errors[0]); - } - - #[test] - fn outbound_finish_rejects_patterns() { - let mut rec = crate::typed_record::TypedRecord::::new(); - rec.set_buffer(Box::new(MockBuffer)); - let builders: Vec> = - vec![Box::new(MockConnectorBuilder { - scheme: "mqtt".to_string(), - })]; - let extensions = crate::extensions::Extensions::new(); - let mut reg = make_registrar(&mut rec, &builders, &extensions); - - reg.link_to("mqtt://out/{device}") - .with_serializer(|_ctx, r: &TestRecord| Ok(r.value.to_le_bytes().to_vec())) - .finish(); - - assert!(rec.outbound_connectors().is_empty()); - let errors = drain_errors(&mut rec); - assert!(errors[0].message.contains("cannot contain '{' or '}'")); - } - - // ==================================================================== - // Outbound link registration tests (fused source) - // ==================================================================== - - #[test] - fn outbound_finish_registers_fused_link() { - let mut rec = crate::typed_record::TypedRecord::::new(); - rec.set_buffer(Box::new(MockBuffer)); - - let builders: Vec> = - vec![Box::new(MockConnectorBuilder { - scheme: "mqtt".to_string(), - })]; - let extensions = crate::extensions::Extensions::new(); - - let mut reg = make_registrar(&mut rec, &builders, &extensions); - - reg.link_to("mqtt://broker/topic") - .with_serializer(|_ctx, record: &TestRecord| Ok(record.value.to_le_bytes().to_vec())) - .finish(); - - assert_eq!(rec.outbound_connectors().len(), 1); - assert_eq!( - rec.outbound_connectors()[0].url.resource_id(), - "broker/topic" - ); - assert!(drain_errors(&mut rec).is_empty()); - } - - /// A detached link keeps its options when registered: `push_outbound` / - /// `push_inbound` must copy the config from the user's link, not from - /// the link they build. - #[test] - fn detached_links_keep_their_config() { - let mut rec = crate::typed_record::TypedRecord::::new(); - rec.set_buffer(Box::new(MockBuffer)); - let builders: Vec> = - vec![Box::new(MockConnectorBuilder { - scheme: "mqtt".to_string(), - })]; - let extensions = crate::extensions::Extensions::new(); - let mut reg = make_registrar(&mut rec, &builders, &extensions); - - reg.push_outbound( - OutboundLink::new("mqtt://out") - .with_config("qos", "1") - .with_serializer(|_ctx, r: &TestRecord| Ok(r.value.to_le_bytes().to_vec())), - ); - reg.push_inbound( - InboundLink::new("mqtt://in") - .with_config("qos", "2") - .with_deserializer(|_ctx, _bytes: &[u8]| Ok(TestRecord { value: 0 })), - ); - - let qos = |config: &[(String, String)]| { - config - .iter() - .find(|(k, _)| k == "qos") - .map(|(_, v)| v.clone()) - }; - assert_eq!( - qos(&rec.outbound_connectors()[0].config).as_deref(), - Some("1") - ); - assert_eq!( - qos(&rec.inbound_connectors()[0].config).as_deref(), - Some("2") - ); - assert!(drain_errors(&mut rec).is_empty()); - } - - #[test] - fn envelope_config_is_consumed_by_core_and_never_reaches_connectors() { - use crate::link_wire::ENVELOPE_KEY; - let mut rec = crate::typed_record::TypedRecord::::new(); - rec.set_buffer(Box::new(MockBuffer)); - let builders: Vec> = - vec![Box::new(MockConnectorBuilder { - scheme: "mqtt".to_string(), - })]; - let extensions = crate::extensions::Extensions::new(); - let mut reg = make_registrar(&mut rec, &builders, &extensions); - - reg.push_outbound( - OutboundLink::new("mqtt://out") - .with_config(ENVELOPE_KEY, "inline") - .with_config("qos", "1") - .with_config(ENVELOPE_KEY, "bound") - .with_serializer(|_ctx, r: &TestRecord| Ok(r.value.to_le_bytes().to_vec())), - ); - reg.push_inbound( - InboundLink::new("mqtt://in") - .with_config(ENVELOPE_KEY, "bound") - .with_config("qos", "2") - .with_deserializer(|_ctx, _bytes: &[u8]| Ok(TestRecord { value: 0 })), - ); - // Still read first: the last entry wins, and inline needs a finalizer. - reg.push_inbound( - InboundLink::new("mqtt://inline") - .with_config(ENVELOPE_KEY, "inline") - .with_deserializer(|_ctx, _bytes: &[u8]| Ok(TestRecord { value: 0 })), - ); - - let expected = [("qos".to_string(), "1".to_string())]; - assert_eq!(rec.outbound_connectors()[0].config, expected); - let expected = [("qos".to_string(), "2".to_string())]; - assert_eq!(rec.inbound_connectors()[0].config, expected); - assert_eq!(rec.inbound_connectors().len(), 1); - let errors = drain_errors(&mut rec); - assert_eq!(errors.len(), 1); - assert!(errors[0].message.contains("inline envelopes require")); - } - - // ==================================================================== - // Detached links via .input() / .output() - // ==================================================================== - - /// Runs `wire` on a fresh buffered `TestRecord` with an `mqtt` connector - /// registered, and returns the record. - fn registered( - wire: impl FnOnce(&mut RecordRegistrar<'_, TestRecord>), - ) -> crate::typed_record::TypedRecord { - let mut rec = crate::typed_record::TypedRecord::::new(); - rec.set_buffer(Box::new(MockBuffer)); - let builders: Vec> = - vec![Box::new(MockConnectorBuilder { - scheme: "mqtt".to_string(), - })]; - let extensions = crate::extensions::Extensions::new(); - wire(&mut make_registrar(&mut rec, &builders, &extensions)); - rec - } - - fn ser(_ctx: crate::RuntimeContext, r: &TestRecord) -> Result, SerializeError> { - Ok(r.value.to_le_bytes().to_vec()) - } - - fn de(_ctx: crate::RuntimeContext, _bytes: &[u8]) -> Result { - Ok(TestRecord { value: 0 }) - } - - fn match_de( - _ctx: &crate::RuntimeContext, - _m: &crate::TopicMatch<'_>, - _bytes: &[u8], - ) -> Result { - Ok(TestRecord { value: 0 }) - } - - /// The same options, applied to an attached or a detached builder. - fn outbound_options( - b: OutboundLinkBuilder, - ) -> OutboundLinkBuilder { - b.with_config("qos", "1") - .with_serializer(ser) - .with_config(crate::connector::WIRE_FORMAT_KEY, "le") - .with_timeout_ms(50) - } - - fn inbound_options( - b: InboundLinkBuilder, - ) -> InboundLinkBuilder { - b.with_config("qos", "1") - .with_match_deserializer(match_de) - .with_config(crate::connector::WIRE_FORMAT_KEY, "le") - .key("d", 4) - .with_topic_resolver(|| None) - } - - #[test] - fn detached_inbound_link_registers_like_link_from() { - let mut attached = registered(|reg| { - inbound_options(reg.link_from("mqtt://temp/{d}")).finish(); - }); - let mut detached = registered(|reg| { - reg.input(inbound_options(InboundLink::new("mqtt://temp/{d}"))); - }); - - let (a, d) = (attached.inbound_connectors(), detached.inbound_connectors()); - assert_eq!((a.len(), d.len()), (1, 1)); - assert_eq!(a[0].url.to_string(), d[0].url.to_string()); - assert_eq!(a[0].config, d[0].config); - assert!(d[0].config.iter().any(|(k, v)| k == "qos" && v == "1")); - assert_eq!(a[0].key, d[0].key); - assert!(d[0].key.is_some()); - assert!(a[0].topic_resolver.is_some() && d[0].topic_resolver.is_some()); - assert!(drain_errors(&mut attached).is_empty()); - assert!(drain_errors(&mut detached).is_empty()); - } - - #[test] - fn detached_outbound_links_register_like_link_to() { - let mut attached = registered(|reg| { - outbound_options(reg.link_to("mqtt://out")).finish(); - reg.with_name("out"); - }); - let mut detached = registered(|reg| { - reg.output(outbound_options(OutboundLink::new("mqtt://out"))) - .with_name("out"); - }); - - let (a, d) = ( - attached.outbound_connectors(), - detached.outbound_connectors(), - ); - assert_eq!((a.len(), d.len()), (1, 1)); - assert_eq!(a[0].url.to_string(), d[0].url.to_string()); - assert_eq!(a[0].config, d[0].config); - assert!(d[0] - .config - .iter() - .any(|(k, v)| k == "timeout_ms" && v == "50")); - - #[cfg(feature = "observability")] - for rec in [&attached, &detached] { - let links = rec.profiling().links(); - assert_eq!(links.len(), 1, "one profiling stage per link"); - assert_eq!(links[0].name.as_deref(), Some("out")); - } - assert!(drain_errors(&mut attached).is_empty()); - assert!(drain_errors(&mut detached).is_empty()); - } - - #[test] - fn detached_links_record_the_same_errors_as_attached_ones() { - /// Links registered and errors recorded (url, message). - type Outcome = (usize, Vec<(Option, String)>); - fn outcome(mut rec: crate::typed_record::TypedRecord) -> Outcome { - let links = rec.outbound_connectors().len() + rec.inbound_connectors().len(); - let errors = drain_errors(&mut rec) - .into_iter() - .map(|e| (e.url, e.message)) - .collect(); - (links, errors) - } - - // Each case runs once through `link_to`/`link_from` + `finish()` - // and once through `.output()`/`.input()`; `$b` is the builder. - macro_rules! same_errors { - (out $url:expr, |$b:ident| $opts:expr, $msg:expr) => {{ - let attached = outcome(registered(|reg| { - let $b = reg.link_to($url); - $opts.finish(); - })); - let detached = outcome(registered(|reg| { - let $b = OutboundLink::new($url); - reg.output($opts); - })); - assert_eq!(attached, detached, "outbound {}", $url); - assert_eq!(detached.0, 0, "nothing registered for {}", $url); - assert_eq!(detached.1.len(), 1, "one error for {}", $url); - assert!(detached.1[0].1.contains($msg), "{:?}", detached.1); - }}; - (in $url:expr, |$b:ident| $opts:expr, $msg:expr) => {{ - let attached = outcome(registered(|reg| { - let $b = reg.link_from($url); - $opts.finish(); - })); - let detached = outcome(registered(|reg| { - let $b = InboundLink::new($url); - reg.input($opts); - })); - assert_eq!(attached, detached, "inbound {}", $url); - assert_eq!(detached.0, 0, "nothing registered for {}", $url); - assert_eq!(detached.1.len(), 1, "one error for {}", $url); - assert!(detached.1[0].1.contains($msg), "{:?}", detached.1); - }}; - } - - same_errors!(out "no-scheme", |b| b.with_serializer(ser), "Invalid connector URL"); - same_errors!(out "mqtt://a/{x}", |b| b.with_serializer(ser), "cannot contain"); - same_errors!(out "mqtt://a", |b| b, "requires a serializer"); - same_errors!(out "kafka://a", |b| b.with_serializer(ser), "No connector registered"); - - same_errors!(in "no-scheme", |b| b.with_deserializer(de), "Invalid connector URL"); - same_errors!(in "mqtt://a", |b| b, "requires a deserializer"); - same_errors!( - in "mqtt://a", - |b| b.with_deserializer(de).with_match_deserializer(match_de), - "not both" - ); - same_errors!(in "kafka://a", |b| b.with_deserializer(de), "No connector registered"); - same_errors!( - in "mqtt://t/{d}", - |b| b.with_deserializer(de).key("x", 2), - "is not a capture" - ); - same_errors!( - in "mqtt://t/{d}", - |b| b.with_deserializer(de).key("d", 0), - "at least 1" - ); - } - - impl From for TestRecord { - fn from(value: i32) -> Self { - TestRecord { value } - } - } - - /// A custom input, generic over every record type it can produce. - struct Counter; - - impl Input for Counter - where - T: From + Send + Sync + 'static + Debug + Clone, - { - fn wire(self, reg: &mut RecordRegistrar<'_, T, S>) { - reg.source(|_ctx, producer| async move { - for i in 0..3 { - producer.produce(T::from(i)); - } - }); - } - } - - #[test] - fn custom_input_wires_a_source() { - let mut rec = registered(|reg| { - reg.input(Counter); - }); - assert!(rec.has_producer()); - assert!(drain_errors(&mut rec).is_empty()); - } - - // ==================================================================== - // Links through a connector handle: `OutboundLink::on` / `InboundLink::on` - // ==================================================================== - - /// The builder id `make_registrar` uses; real builders start at 1. - const TEST_BUILDER: u32 = 0; - - /// Runs `wire` on a fresh buffered `TestRecord` with connectors - /// `[mqtt, knx]`, so a handle with index 1 really selects `knx`. - fn registered_mqtt_knx( - wire: impl FnOnce(&mut RecordRegistrar<'_, TestRecord>), - ) -> crate::typed_record::TypedRecord { - let mut rec = crate::typed_record::TypedRecord::::new(); - rec.set_buffer(Box::new(MockBuffer)); - let builders: Vec> = vec![ - Box::new(MockConnectorBuilder { - scheme: "mqtt".to_string(), - }), - Box::new(MockConnectorBuilder { - scheme: "knx".to_string(), - }), - ]; - let extensions = crate::extensions::Extensions::new(); - wire(&mut make_registrar(&mut rec, &builders, &extensions)); - rec - } - - fn handle(builder: u32, index: u16) -> crate::ConnectorHandle { - crate::ConnectorHandle { builder, index } - } - - #[test] - fn handle_links_take_the_connector_scheme() { - let (mqtt, knx) = (handle(TEST_BUILDER, 0), handle(TEST_BUILDER, 1)); - let mut rec = registered_mqtt_knx(|reg| { - reg.input(InboundLink::on(knx, "1/0/7").with_deserializer(de)) - .output(OutboundLink::on(knx, "1/2/3").with_serializer(ser)) - // A full URL, as a `#[link_address]` key gives, when it matches. - .output(OutboundLink::on(mqtt, "mqtt://sensors/temp").with_serializer(ser)); - }); - - assert!(drain_errors(&mut rec).is_empty()); - assert_eq!(rec.inbound_connectors()[0].url.to_string(), "knx://1/0/7"); - let out: Vec = rec - .outbound_connectors() - .iter() - .map(|l| l.url.to_string()) - .collect(); - assert_eq!(out, ["knx://1/2/3", "mqtt://sensors/temp"]); - } - - #[test] - fn handle_links_reject_wrong_scheme_and_foreign_handles() { - let (mqtt, knx) = (handle(TEST_BUILDER, 0), handle(TEST_BUILDER, 1)); - let foreign = handle(TEST_BUILDER + 1, 0); - let out_of_range = handle(TEST_BUILDER, 7); - let mut rec = registered_mqtt_knx(|reg| { - reg.output(OutboundLink::on(mqtt, "knx://1/2/3").with_serializer(ser)) - .input(InboundLink::on(knx, "mqtt://x").with_deserializer(de)) - .output(OutboundLink::on(foreign, "a").with_serializer(ser)) - .input(InboundLink::on(foreign, "a").with_deserializer(de)) - .output(OutboundLink::on(out_of_range, "a").with_serializer(ser)); - }); - - assert!(rec.outbound_connectors().is_empty()); - assert!(rec.inbound_connectors().is_empty()); - let errors: Vec<(Option, String)> = drain_errors(&mut rec) - .into_iter() - .map(|e| (e.url, e.message)) - .collect(); - let foreign_msg = "Connector handle belongs to a different AimDbBuilder"; - let expected = [ - ( - "knx://1/2/3", - "Address scheme 'knx' does not match the connector's scheme 'mqtt'", - ), - ( - "mqtt://x", - "Address scheme 'mqtt' does not match the connector's scheme 'knx'", - ), - ("a", foreign_msg), - ("a", foreign_msg), - ("a", foreign_msg), - ]; - let expected: Vec<(Option, String)> = expected - .iter() - .map(|(url, msg)| (Some(url.to_string()), msg.to_string())) - .collect(); - assert_eq!(errors, expected); - } - - /// The target shape from #390, through `build()`: links on a handle - /// build; the same links on another builder's handle fail it. - #[tokio::test] - async fn handle_links_build_and_foreign_handles_fail_it() { - let mut other = crate::AimDbBuilder::new(); - let foreign = other.connect(NoopConnectorBuilder); - - for (use_foreign, expect_ok) in [(false, true), (true, false)] { - let key_temp_indoor_1 = crate::Name::::new("temp.indoor"); - let mut builder = crate::AimDbBuilder::new().runtime(Arc::new(MockRuntime)); - let mqtt = builder.connect(NoopConnectorBuilder); - let on = if use_foreign { foreign } else { mqtt }; - builder.configure(key_temp_indoor_1, move |reg| { - reg.buffer_raw(Box::new(MockBuffer)) - .input(InboundLink::on(on, "commands/temp/indoor").with_deserializer(de)) - .output(OutboundLink::on(on, "sensors/temp/indoor").with_serializer(ser)); - }); - let result = builder.build().await; - if expect_ok { - let (db, _runner) = result.expect("handle links build"); - let inbound = - crate::InboundDispatch::new(&db, "mqtt", &Plus).expect("routes compile"); - assert_eq!(inbound.subscriptions()[0].as_ref(), "commands/temp/indoor"); - } else { - let errors = config_errors(result); - assert_eq!(errors.len(), 2, "got: {errors:?}"); - assert!(errors.iter().all(|e| e.record_key == "temp.indoor" - && e.message == "Connector handle belongs to a different AimDbBuilder")); - } - } - } - - /// A connector registered with `connect` serves links exactly like one - /// registered with `with_connector`. - #[tokio::test] - async fn connected_connector_serves_links() { - let key_rec_in_2 = crate::Name::::new("rec.in"); - let mut builder = crate::AimDbBuilder::new().runtime(Arc::new(MockRuntime)); - let _mqtt = builder.connect(NoopConnectorBuilder); - builder.configure(key_rec_in_2, |reg| { - reg.buffer_raw(Box::new(MockBuffer)) - .input(InboundLink::new("mqtt://a").with_deserializer(de)); - }); - let (db, _runner) = builder.build().await.expect("builds"); - let inbound = crate::InboundDispatch::new(&db, "mqtt", &Plus).expect("routes compile"); - assert_eq!(inbound.route_count(), 1); - } - - /// Two inbound links on one record are fan-in, through `.input()` as - /// through `.link_from()`. - #[tokio::test] - async fn two_inbound_inputs_fan_in() { - let key_rec_in_3 = crate::Name::::new("rec.in"); - let mut builder = crate::AimDbBuilder::new() - .runtime(Arc::new(MockRuntime)) - .with_connector(NoopConnectorBuilder); - builder.configure(key_rec_in_3, |reg| { - reg.buffer_raw(Box::new(MockBuffer)) - .input(InboundLink::new("mqtt://a").with_deserializer(de)) - .input(InboundLink::new("mqtt://b").with_deserializer(de)); - }); - let (db, _runner) = builder.build().await.expect("fan-in builds"); - let inbound = crate::InboundDispatch::new(&db, "mqtt", &Plus).expect("routes compile"); - assert_eq!(inbound.route_count(), 2); - } - - #[tokio::test] - async fn input_source_and_link_conflict() { - let key_rec_in_4 = crate::Name::::new("rec.in"); - let mut builder = crate::AimDbBuilder::new() - .runtime(Arc::new(MockRuntime)) - .with_connector(NoopConnectorBuilder); - builder.configure(key_rec_in_4, |reg| { - reg.buffer_raw(Box::new(MockBuffer)) - .input(Counter) - .input(InboundLink::new("mqtt://a").with_deserializer(de)); - }); - let errors = config_errors(builder.build().await); - assert_eq!(errors.len(), 1, "got: {errors:?}"); - assert_eq!(errors[0].record_key, "rec.in"); - assert!( - errors[0] - .message - .contains("conflicting writers: record has source + inbound link"), - "got: {}", - errors[0].message - ); - } - - #[test] - fn outbound_finish_without_serializer_records_error() { - let mut rec = crate::typed_record::TypedRecord::::new(); - rec.set_buffer(Box::new(MockBuffer)); - - let builders: Vec> = - vec![Box::new(MockConnectorBuilder { - scheme: "mqtt".to_string(), - })]; - let extensions = crate::extensions::Extensions::new(); - - let mut reg = make_registrar(&mut rec, &builders, &extensions); - - // No serializer set — error recorded, link not registered - reg.link_to("mqtt://broker/topic").finish(); - - assert!(rec.outbound_connectors().is_empty()); - let errors = drain_errors(&mut rec); - assert_eq!(errors.len(), 1); - assert!(errors[0] - .message - .contains("Outbound connector requires a serializer")); - assert_eq!(errors[0].record_key, "test::Record"); - assert_eq!(errors[0].url.as_deref(), Some("mqtt://broker/topic")); - } - - #[test] - fn finish_with_unregistered_scheme_records_error() { - let mut rec = crate::typed_record::TypedRecord::::new(); - rec.set_buffer(Box::new(MockBuffer)); - - // No connector builders registered at all - let builders: Vec> = vec![]; - let extensions = crate::extensions::Extensions::new(); - - let mut reg = make_registrar(&mut rec, &builders, &extensions); - reg.link_to("mqtt://broker/topic") - .with_serializer(|_ctx, r: &TestRecord| Ok(r.value.to_le_bytes().to_vec())) - .finish(); - - assert!(rec.outbound_connectors().is_empty()); - let errors = drain_errors(&mut rec); - assert_eq!(errors.len(), 1); - assert!(errors[0] - .message - .contains("No connector registered for scheme 'mqtt'")); - assert_eq!(errors[0].record_key, "test::Record"); - } - - // ==================================================================== - // Writer-exclusivity tests (.source / .transform / .link_from) - // ==================================================================== - - /// Helper: build a `TransformDescriptor` with a no-op spawn function. - fn dummy_transform_descriptor() -> crate::transform::TransformDescriptor { - crate::transform::TransformDescriptor:: { - input_keys: vec![], - input_types: vec![], - build_fn: Box::new(|_p, _db, _output_key, _profiling| { - crate::transform::CollectedTransform { - task_future: Box::pin(async {}), - fanin_futures: vec![], - } - }), - } - } - - #[test] - fn cross_stage_registrations_record_without_setter_errors() { - // Cross-stage exclusivity (.source()/.transform()/.link_from()) is - // validated by build(), not by the setters: conflicting registrations - // are all recorded so build() can report the conflict with the record - // key attached. - let mut rec = crate::typed_record::TypedRecord::::new(); - rec.set_buffer(Box::new(MockBuffer)); - rec.set_producer(|_ctx, _p| async move {}); - - let builders: Vec> = - vec![Box::new(MockConnectorBuilder { - scheme: "mqtt".to_string(), - })]; - let extensions = crate::extensions::Extensions::new(); - - let mut reg = make_registrar(&mut rec, &builders, &extensions); - reg.link_from("mqtt://broker/topic") - .with_deserializer(|_ctx, _b: &[u8]| Ok(TestRecord { value: 0 })) - .finish(); - - assert!(rec.has_producer()); - assert_eq!(rec.inbound_connectors().len(), 1); - assert!( - drain_errors(&mut rec).is_empty(), - "no setter-level cross-stage errors; build() reports the conflict" - ); - } - - #[test] - fn duplicate_source_and_transform_record_errors() { - // Same-stage duplicates are still caught at registration time: a - // second .source()/.transform() would silently overwrite the first. - let mut rec = crate::typed_record::TypedRecord::::new(); - rec.set_buffer(Box::new(MockBuffer)); - - rec.set_producer(|_ctx, _p| async move {}); - rec.set_producer(|_ctx, _p| async move {}); - rec.set_transform(dummy_transform_descriptor()); - rec.set_transform(dummy_transform_descriptor()); - - let errors = drain_errors(&mut rec); - assert_eq!(errors.len(), 2); - assert!(errors[0].message.contains("already has a producer service")); - assert!(errors[1] - .message - .contains("already has a .transform(); only one is allowed")); - } - - #[test] - fn multiple_link_from_allowed() { - let mut rec = crate::typed_record::TypedRecord::::new(); - rec.set_buffer(Box::new(MockBuffer)); - - let builders: Vec> = - vec![Box::new(MockConnectorBuilder { - scheme: "mqtt".to_string(), - })]; - let extensions = crate::extensions::Extensions::new(); - let mut reg = make_registrar(&mut rec, &builders, &extensions); - - // Chained via finish() → &mut RecordRegistrar … - reg.link_from("mqtt://broker/topic-a") - .with_deserializer(|_ctx, _b: &[u8]| Ok(TestRecord { value: 0 })) - .finish() - .link_from("mqtt://broker/topic-b") - .with_deserializer(|_ctx, _b: &[u8]| Ok(TestRecord { value: 0 })) - .finish(); - - // … and as separate statements: each call takes a fresh borrow, so - // the registrar is reusable after a chain ends. - reg.link_from("mqtt://broker/topic-c") - .with_deserializer(|_ctx, _b: &[u8]| Ok(TestRecord { value: 0 })) - .finish(); - reg.with_name("third-link"); - - assert_eq!(rec.inbound_connectors().len(), 3); - } - - /// Registrar methods take fresh borrows: separate - /// statements in a configure-style closure must compile. - #[test] - fn registrar_allows_separate_statements() { - let mut rec = crate::typed_record::TypedRecord::::new(); - rec.set_buffer(Box::new(MockBuffer)); - - let builders: Vec> = vec![]; - let extensions = crate::extensions::Extensions::new(); - let mut reg = make_registrar(&mut rec, &builders, &extensions); - - reg.source(|_ctx, _p| async move {}); - reg.tap(|_ctx, _c| async move {}); - - assert!(rec.has_producer()); - assert_eq!(rec.consumer_count(), 1); - } - - // ==================================================================== - // build()-level validation tests - // ==================================================================== - - #[derive(Debug, Clone)] - struct OtherRecord; - - /// Connector builder whose `build()` contributes nothing — for tests - /// that must get through the connector phase. - struct NoopConnectorBuilder; - - impl crate::connector::ConnectorBuilder for NoopConnectorBuilder { - fn build<'a>( - &'a self, - _db: &'a crate::AimDb, - ) -> Pin< - Box< - dyn Future< - Output = DbResult + Send + 'static>>>>, - > + Send - + 'a, - >, - > { - Box::pin(async { Ok(Vec::new()) }) - } - fn scheme(&self) -> &str { - "mqtt" - } - } - - /// A connector that claims every route for its scheme, as KNX and the - /// session *clients* do. - struct OwningConnectorBuilder(&'static str); - - impl crate::connector::ConnectorBuilder for OwningConnectorBuilder { - fn build<'a>( - &'a self, - _db: &'a crate::AimDb, - ) -> Pin< - Box< - dyn Future< - Output = DbResult + Send + 'static>>>>, - > + Send - + 'a, - >, - > { - Box::pin(async { Ok(Vec::new()) }) - } - fn scheme(&self) -> &str { - self.0 - } - fn owns_scheme(&self) -> bool { - true - } - } - - /// Two scheme-owning connectors under one scheme is a configuration error, - /// not a silently duplicated route set. - #[tokio::test] - async fn two_owning_connectors_on_one_scheme_fail_the_build() { - let builder = crate::AimDbBuilder::new() - .runtime(Arc::new(MockRuntime)) - .with_connector(OwningConnectorBuilder("knx")) - .with_connector(OwningConnectorBuilder("knx")); - - let Err(err) = builder.build().await else { - panic!("a second connector for an owned scheme must be rejected"); - }; - let msg = alloc::format!("{err}"); - assert!( - msg.contains("More than one connector registered for scheme 'knx'"), - "unexpected error: {msg}" - ); - } - - /// Distinct schemes are fine — that is how a caller runs two of the same - /// transport side by side. - #[tokio::test] - async fn owning_connectors_on_distinct_schemes_build() { - let builder = crate::AimDbBuilder::new() - .runtime(Arc::new(MockRuntime)) - .with_connector(OwningConnectorBuilder("knx")) - .with_connector(OwningConnectorBuilder("mqtt")); - - assert!(builder.build().await.is_ok()); - } - - /// A connector that collects no routes — a session *server*, say — may be - /// registered twice under one scheme: two endpoints onto one dispatch. - /// `owns_scheme` defaults to `false`, so this must keep working. - #[tokio::test] - async fn two_non_owning_connectors_on_one_scheme_build() { - let builder = crate::AimDbBuilder::new() - .runtime(Arc::new(MockRuntime)) - .with_connector(NoopConnectorBuilder) - .with_connector(NoopConnectorBuilder); - - assert!(builder.build().await.is_ok()); - } - - /// Acceptance criterion: a builder with three distinct - /// mistakes reports all three from one `build()` call. - #[tokio::test] - async fn build_reports_all_configuration_mistakes_at_once() { - let key_rec_a_5 = crate::Name::::new("rec.a"); - let key_rec_b_6 = crate::Name::::new("rec.b"); - let key_rec_c_7 = crate::Name::::new("rec.c"); - let key_rec_c_8 = crate::Name::::new("rec.c"); - let mut builder = crate::AimDbBuilder::new().runtime(Arc::new(MockRuntime)); - - // Mistake 1: outbound link with no serializer - builder.configure(key_rec_a_5, |reg| { - reg.link_to("mqtt://broker/a").finish(); - }); - // Mistake 2: two .source() registrations on one record - builder.configure(key_rec_b_6, |reg| { - reg.source(|_ctx, _p| async move {}); - reg.source(|_ctx, _p| async move {}); - }); - // Mistake 3: key re-registered with a different type - builder.configure(key_rec_c_7, |_reg| {}); - builder.configure(key_rec_c_8, |_reg| {}); - - let Err(err) = builder.build().await else { - panic!("build must fail"); - }; - let crate::DbError::InvalidConfiguration { errors } = err else { - panic!("expected InvalidConfiguration, got {err:?}"); - }; - assert_eq!(errors.len(), 3, "expected 3 errors, got: {errors:?}"); - assert!(errors.iter().any(|e| e.record_key == "rec.a" - && e.url.as_deref() == Some("mqtt://broker/a") - && e.message.contains("requires a serializer"))); - assert!(errors.iter().any( - |e| e.record_key == "rec.b" && e.message.contains("already has a producer service") - )); - assert!(errors - .iter() - .any(|e| e.record_key == "rec.c" && e.message.contains("different type"))); - } - - /// `.buffer()` after `.link_from()` is legitimate now that the buffer - /// requirement is validated by `build()` instead of `finish()`. - #[tokio::test] - async fn buffer_after_link_from_is_valid() { - let key_rec_x_9 = crate::Name::::new("rec.x"); - let mut builder = crate::AimDbBuilder::new() - .runtime(Arc::new(MockRuntime)) - .with_connector(NoopConnectorBuilder); - - builder.configure(key_rec_x_9, |reg| { - reg.link_from("mqtt://broker/x") - .with_deserializer(|_ctx, _b: &[u8]| Ok(TestRecord { value: 0 })) - .finish(); - // Buffer configured AFTER the link — order-independent. - reg.buffer_raw(Box::new(MockBuffer)); - }); - - builder.build().await.expect("build must succeed"); - } - - /// A linked record without a buffer fails at build() — previously this - /// panicked at spawn time, deep inside a connector factory closure. - #[tokio::test] - async fn linked_record_without_buffer_fails_build() { - let key_rec_x_10 = crate::Name::::new("rec.x"); - let mut builder = crate::AimDbBuilder::new() - .runtime(Arc::new(MockRuntime)) - .with_connector(NoopConnectorBuilder); - - builder.configure(key_rec_x_10, |reg| { - reg.link_from("mqtt://broker/x") - .with_deserializer(|_ctx, _b: &[u8]| Ok(TestRecord { value: 0 })) - .finish(); - }); - - let Err(err) = builder.build().await else { - panic!("build must fail"); - }; - let crate::DbError::InvalidConfiguration { errors } = err else { - panic!("expected InvalidConfiguration, got {err:?}"); - }; - assert_eq!(errors.len(), 1); - assert!(errors[0].message.contains("requires a buffer")); - assert_eq!(errors[0].record_key, "rec.x"); - assert_eq!(errors[0].url.as_deref(), Some("mqtt://broker/x")); - } - - // ==================================================================== - // Fused ingest roundtrip tests - // ==================================================================== - - use core::sync::atomic::{AtomicI32, AtomicUsize, Ordering}; - - /// Buffer that records the last pushed value and a push count — - /// atomics only, so the test runs under no_std + alloc too. - struct RecordingBuffer { - last: Arc, - count: Arc, - } - - impl crate::buffer::DynBuffer> for RecordingBuffer { - fn push(&self, sample: crate::Stamped) { - self.last.store(sample.value.value, Ordering::SeqCst); - self.count.fetch_add(1, Ordering::SeqCst); - } - fn subscribe_boxed( - &self, - ) -> Box> + Send> { - unimplemented!("not needed for ingest tests") - } - fn as_any(&self) -> &dyn core::any::Any { - self - } - } - - /// Dispatches `payload` on `topic` through the `mqtt` inbound routes. - fn route(db: &crate::AimDb, topic: &str, payload: &[u8]) { - crate::InboundDispatch::new(db, "mqtt", &Plus) - .expect("routes compile") - .dispatch(topic, payload); - } - - /// End-to-end inbound path: bytes → fused ingest → typed buffer push, - /// with no `Box` in between. - #[tokio::test] - async fn ingest_roundtrip_produces_value() { - let (db, last, count) = inbound_db(|reg| { - reg.link_from("mqtt://cmd/in") - .with_deserializer(|_ctx, bytes: &[u8]| { - if bytes.is_empty() { - return Err("empty payload".into()); - } - Ok(TestRecord { - value: bytes.len() as i32, - }) - }) - .finish(); - }) - .await; - - route(&db, "cmd/in", &[1, 2, 3]); - assert_eq!(count.load(Ordering::SeqCst), 1); - assert_eq!(last.load(Ordering::SeqCst), 3); - - // Bad bytes: the deserializer fails, nothing is produced. - route(&db, "cmd/in", &[]); - assert_eq!(count.load(Ordering::SeqCst), 1); - } - - /// The deserializer set last wins, whichever way its context is typed. - #[tokio::test] - async fn deserializer_set_last_wins() { - let (db, last, _) = inbound_db(|reg| { - reg.link_from("mqtt://cmd/in") - .with_deserializer(|_ctx, _bytes: &[u8]| Ok(TestRecord { value: 0 })) - .with_deserializer(|_ctx: crate::RuntimeContext, _bytes: &[u8]| { - Ok(TestRecord { value: 99 }) - }) - .finish(); - }) - .await; - route(&db, "cmd/in", b"x"); - assert_eq!(last.load(Ordering::SeqCst), 99); - } - - // ==================================================================== - // InboundDispatch: patterns, keys and connector-build errors - // ==================================================================== - - use crate::topic_pattern::test_support::Plus; - - /// A record `rec.in` whose buffer stores the last value and a count. - async fn inbound_db( - links: impl FnOnce(&mut RecordRegistrar<'_, TestRecord>) + Send + 'static, - ) -> (crate::AimDb, Arc, Arc) { - let key_rec_in_11 = crate::Name::::new("rec.in"); - let last = Arc::new(AtomicI32::new(-1)); - let count = Arc::new(AtomicUsize::new(0)); - let (buf_last, buf_count) = (last.clone(), count.clone()); - let mut builder = crate::AimDbBuilder::new() - .runtime(Arc::new(MockRuntime)) - .with_connector(NoopConnectorBuilder); - builder.configure(key_rec_in_11, move |reg| { - reg.buffer_raw(Box::new(RecordingBuffer { - last: buf_last, - count: buf_count, - })); - links(reg); - }); - let (db, _runner) = builder.build().await.expect("build must succeed"); - (db, last, count) - } - - /// Buffer that records the stamp of the last pushed value. - struct StampRecordingBuffer(Arc); - - impl crate::buffer::DynBuffer> for StampRecordingBuffer { - fn push(&self, sample: crate::Stamped) { - self.0.store(sample.stamp().as_nanos(), Ordering::SeqCst); - } - fn subscribe_boxed( - &self, - ) -> Box> + Send> { - unimplemented!("not needed for ingest tests") - } - fn as_any(&self) -> &dyn core::any::Any { - self - } - } - - /// Design 058 §1: an inbound value is stamped when it is written locally. - #[tokio::test] - async fn an_inbound_value_is_stamped_when_written() { - let key_rec_in_12 = crate::Name::::new("rec.in"); - let ops = crate::executor::test_support::ManualClockRuntimeOps::default(); - let stamp = Arc::new(core::sync::atomic::AtomicU64::new(u64::MAX)); - let buf_stamp = stamp.clone(); - let mut builder = crate::AimDbBuilder::new() - .runtime(Arc::new(ops.clone())) - .with_connector(NoopConnectorBuilder); - builder.configure(key_rec_in_12, move |reg| { - reg.buffer_raw(Box::new(StampRecordingBuffer(buf_stamp))); - reg.link_from("mqtt://cmd/in") - .with_deserializer(|_ctx, bytes: &[u8]| { - Ok::<_, crate::IngestError>(TestRecord { - value: bytes.len() as i32, - }) - }) - .finish(); - }); - let (db, _runner) = builder.build().await.expect("build must succeed"); - - ops.clock.advance(core::time::Duration::from_nanos(4242)); - route(&db, "cmd/in", &[1]); - assert_eq!(stamp.load(Ordering::SeqCst), 4242); - } - - /// The key index, or -1 without a key. - fn key_deser( - _ctx: &crate::RuntimeContext, - m: &crate::TopicMatch<'_>, - _bytes: &[u8], - ) -> Result { - Ok(TestRecord { - value: m.key().map_or(-1, |k| k.index() as i32), - }) - } - - fn config_errors(result: crate::DbResult) -> Vec { - match result { - Err(crate::DbError::InvalidConfiguration { errors }) => errors, - Err(e) => panic!("unexpected error {e:?}"), - Ok(_) => panic!("expected configuration errors"), - } - } - - #[tokio::test] - async fn inbound_dispatch_routes_patterns_with_shared_keys() { - let keys: Arc>> = Default::default(); - let seen = keys.clone(); - let (db, last, count) = inbound_db(move |reg| { - reg.link_from("mqtt://temp/{d}") - .key("d", 2) - .with_match_deserializer(move |ctx, m, bytes| { - seen.lock().extend(m.key()); - key_deser(ctx, m, bytes) - }) - .finish(); - reg.link_from("mqtt://hum/{id}") - .key("id", 2) - .with_match_deserializer(key_deser) - .finish(); - reg.link_from("mqtt://cmd/in") - .with_deserializer(|_ctx, _bytes: &[u8]| Ok(TestRecord { value: 100 })) - .finish(); - }) - .await; - - let inbound = crate::InboundDispatch::new(&db, "mqtt", &Plus).expect("routes compile"); - let subscriptions: Vec = inbound - .subscriptions() - .iter() - .map(|s| s.to_string()) - .collect(); - assert_eq!(subscriptions, ["cmd/in", "hum/+", "temp/+"]); - assert_eq!(inbound.route_count(), 3); - - let dispatch = |topic: &str| { - inbound.dispatch(topic, b""); - last.load(Ordering::SeqCst) - }; - assert_eq!(dispatch("temp/a"), 0); - assert_eq!(dispatch("hum/b"), 1); - assert_eq!(dispatch("hum/a"), 0, "one key table per record"); - assert_eq!(dispatch("cmd/in"), 100); - let produced = count.load(Ordering::SeqCst); - dispatch("temp/c"); - assert_eq!(count.load(Ordering::SeqCst), produced, "full table drops"); - - let a = keys.lock()[0]; - assert_eq!(db.inbound_key_name("rec.in", a).as_deref(), Some("a")); - assert_eq!(db.inbound_key_name("other", a), None); - - #[cfg(feature = "remote")] - { - let records = db.list_records(); - let info = records[0].inbound_keys.as_ref().expect("keyed record"); - assert_eq!(info.captures, ["d", "id"]); - assert_eq!((info.capacity, info.assigned, info.dropped), (2, 2, 1)); - } - } - - #[tokio::test] - async fn inbound_dispatch_rejects_links_it_cannot_compile() { - let (db, _, _) = inbound_db(|reg| { - reg.link_from("mqtt://s/{d}/t") - .with_deserializer(|_ctx, _bytes: &[u8]| Ok(TestRecord { value: 0 })) - .finish(); - reg.link_from("mqtt://r/one") - .with_topic_resolver(|| Some("r/{d".into())) - .with_deserializer(|_ctx, _bytes: &[u8]| Ok(TestRecord { value: 0 })) - .finish(); - reg.link_from("mqtt://k/{d}") - .key("d", 4) - .with_topic_resolver(|| Some("k/{x}".into())) - .with_match_deserializer(key_deser) - .finish(); - }) - .await; - - let errors = config_errors(crate::InboundDispatch::new(&db, "mqtt", &Plus)); - assert_eq!(errors.len(), 2, "{errors:?}"); - assert!(errors.iter().all(|e| e.record_key == "rec.in")); - assert!(errors[0].message.contains("unbalanced '{' in 'r/{d'")); - assert!(errors[1] - .message - .contains("key 'd' is not a capture of 'k/{x}'")); - - let errors = config_errors(crate::InboundDispatch::new( - &db, - "mqtt", - &crate::ExactGrammar, - )); - assert_eq!(errors.len(), 3, "{errors:?}"); - assert!(errors[0] - .message - .contains("does not support topic patterns")); - } - - #[tokio::test] - async fn inbound_dispatch_clones_share_records() { - fn assert_send_sync() {} - assert_send_sync::(); - - let (db, last, count) = inbound_db(|reg| { - reg.link_from("mqtt://cmd/in") - .with_deserializer(|_ctx, bytes: &[u8]| { - Ok(TestRecord { - value: bytes.len() as i32, - }) - }) - .finish(); - }) - .await; - - let inbound = crate::InboundDispatch::new(&db, "mqtt", &Plus).unwrap(); - let clone = inbound.clone(); - drop(inbound); - clone.dispatch("cmd/in", b"abcd"); - assert_eq!(count.load(Ordering::SeqCst), 1); - assert_eq!(last.load(Ordering::SeqCst), 4); - } - - #[tokio::test] - async fn admission_outcomes_are_counted_after_production_and_survive_reconnect() { - let (db, last, count) = inbound_db(|reg| { - reg.link_from("mqtt://cmd/in") - .with_admitting_deserializer(&[1], |_ctx, _m, bytes| { - if bytes.is_empty() { - return Err(crate::IngestError::new( - crate::Rejection::TooOld, - "received v0, accepts v1..=2", - )); - } - Ok(crate::IngestValue::upgraded(TestRecord { value: 42 }, 1)) - }) - .finish(); - }) - .await; - let inbound = crate::InboundDispatch::new(&db, "mqtt", &Plus).unwrap(); - let clone = inbound.clone(); - assert_eq!(inbound.routes()[0].id, 0); - clone.dispatch("cmd/in", b"v1"); - assert_eq!(last.load(Ordering::SeqCst), 42); - assert_eq!(count.load(Ordering::SeqCst), 1); - inbound.dispatch("cmd/in", b""); - assert_eq!(count.load(Ordering::SeqCst), 1); - let snapshot = clone.stats(0).unwrap(); - assert_eq!(snapshot.accepted, 1); - assert_eq!(snapshot.too_old, 1); - assert_eq!( - snapshot.upgraded[0], - crate::UpgradeCount { from: 1, count: 1 } - ); - assert_eq!(inbound.stats(0).unwrap(), snapshot); - drop(inbound); - drop(clone); - let reconnected = crate::InboundDispatch::new(&db, "mqtt", &Plus).unwrap(); - assert_eq!(reconnected.stats(0).unwrap(), snapshot); - reconnected.dispatch("cmd/in", b"v1"); - assert_eq!(reconnected.stats(0).unwrap().upgraded[0].count, 2); - #[cfg(all(feature = "remote", feature = "observability"))] - { - let records = db.list_records(); - let metrics = &records - .iter() - .find(|r| r.record_key == "rec.in") - .unwrap() - .inbound_routes; - assert_eq!(metrics.len(), 1); - assert_eq!(metrics[0].link, "mqtt://cmd/in"); - assert_eq!(metrics[0].stats, reconnected.stats(0).unwrap()); - let json = serde_json::to_value(&records).unwrap(); - assert!(json.to_string().contains("too_old")); - } - } - - // ==================================================================== - // OutboundRoutes over typed links - // ==================================================================== - - /// Buffer reader that replays a fixed script, then reports the buffer - /// closed. - struct ScriptedReader { - script: Vec>, - } - - impl crate::buffer::BufferReader> for ScriptedReader { - fn poll_recv( - &mut self, - _cx: &mut core::task::Context<'_>, - ) -> core::task::Poll, crate::DbError>> { - let next = if self.script.is_empty() { - Err(crate::DbError::BufferClosed { - buffer_name: "scripted".to_string(), - }) - } else { - self.script.remove(0) - }; - core::task::Poll::Ready(next.map(|value| { - crate::Stamped::new( - value, - crate::WriteMetadata::new(crate::Stamp::from_nanos(0)), - ) - })) - } - fn try_recv(&mut self) -> Result, crate::DbError> { - unimplemented!("not needed for outbound route tests") - } - } - - type Script = fn() -> Vec>; - - /// Buffer whose readers replay `script`. - struct ScriptedBuffer(Script); - - impl crate::buffer::DynBuffer> for ScriptedBuffer { - fn push(&self, _value: crate::Stamped) {} - fn subscribe_boxed( - &self, - ) -> Box> + Send> { - Box::new(ScriptedReader { script: (self.0)() }) - } - fn as_any(&self) -> &dyn core::any::Any { - self - } - } - - fn values(values: &[i32]) -> Vec> { - values - .iter() - .map(|&value| Ok(TestRecord { value })) - .collect() - } - - fn le(_ctx: crate::RuntimeContext, r: &TestRecord) -> Result, SerializeError> { - Ok(r.value.to_le_bytes().to_vec()) - } - - /// Writes `r` into `out`. - fn le_into( - _ctx: crate::RuntimeContext, - r: &TestRecord, - out: &mut [u8], - ) -> Result { - let bytes = r.value.to_le_bytes(); - out.get_mut(..bytes.len()) - .ok_or(SerializeError::BufferTooSmall)? - .copy_from_slice(&bytes); - Ok(bytes.len()) - } - - /// `OutboundRoutes` for the `mqtt` links `links` registers on a record - /// whose buffer replays `script`. - async fn outbound( - script: Script, - links: impl FnOnce(&mut RecordRegistrar<'_, TestRecord>) + Send + 'static, - ) -> (crate::AimDb, crate::OutboundRoutes) { - let key_rec_out_13 = crate::Name::::new("rec.out"); - let mut builder = crate::AimDbBuilder::new() - .runtime(Arc::new(MockRuntime)) - .with_connector(NoopConnectorBuilder); - builder.configure(key_rec_out_13, move |reg| { - reg.buffer_raw(Box::new(ScriptedBuffer(script))); - links(reg); - }); - let (db, _runner) = builder.build().await.expect("build must succeed"); - let outbound = crate::OutboundRoutes::new(&db, "mqtt").expect("outbound routes"); - (db, outbound) - } - - /// The next message as `(topic, value, owned)`. - async fn pull(o: &mut crate::OutboundRoutes) -> Option<(String, i32, bool)> { - let msg = o.next().await?; - let owned = matches!(msg.payload, crate::OutboundPayload::Owned(_)); - let bytes: [u8; 4] = msg.payload.as_slice().try_into().expect("4 bytes"); - Some((msg.topic.to_string(), i32::from_le_bytes(bytes), owned)) - } - - /// A lag is counted and skipped; a closed buffer ends the route. - #[tokio::test] - async fn outbound_routes_count_lag_and_end_on_close() { - let (_db, mut o) = outbound( - || { - vec![ - Ok(TestRecord { value: 1 }), - Err(lagged()), - Ok(TestRecord { value: 2 }), - ] - }, - |reg| { - reg.link_to("mqtt://tele/out").with_serializer(le).finish(); - }, - ) - .await; - - use crate::outbound::events::{capture, OutboundEvent}; - let seen = Arc::new(spin::Mutex::new(Vec::new())); - let observer = { - let seen = seen.clone(); - Arc::new(move |event: &OutboundEvent<'_>| { - seen.lock().push(match event { - OutboundEvent::Lagged { topic, skipped } => { - assert_eq!((*topic, *skipped), ("tele/out", 1)); - "lag" - } - OutboundEvent::Closed { topic, error } => { - assert_eq!(*topic, "tele/out"); - assert!(matches!(error, crate::DbError::BufferClosed { .. })); - "closed" - } - other => panic!("unexpected {other:?}"), - }); - }) - }; - capture::future(observer, async { - assert_eq!(pull(&mut o).await, Some(("tele/out".into(), 1, true))); - assert_eq!(pull(&mut o).await, Some(("tele/out".into(), 2, true))); - assert_eq!(o.stats(0).unwrap().lagged, 1); - assert_eq!(pull(&mut o).await, None); - }) - .await; - assert_eq!(*seen.lock(), ["lag", "closed"]); - } - - fn lagged() -> crate::DbError { - crate::DbError::BufferLagged { - lag_count: 1, - buffer_name: "scripted".to_string(), - } - } - - /// A value whose serializer fails is counted and skipped. - #[tokio::test] - async fn outbound_routes_skip_serialize_failures() { - let (_db, mut o) = outbound( - || values(&[13, 42]), - |reg| { - reg.link_to("mqtt://tele/out") - .with_serializer(|ctx, r: &TestRecord| { - if r.value == 13 { - return Err(SerializeError::InvalidData); - } - le(ctx, r) - }) - .finish(); - }, - ) - .await; - - assert_eq!(pull(&mut o).await.map(|m| m.1), Some(42)); - assert_eq!(o.stats(0).unwrap().serialize_failed, 1); - } - - #[tokio::test] - async fn outbound_routes_use_scratch_without_owned_fallback() { - let owned_calls = Arc::new(AtomicUsize::new(0)); - let into_calls = Arc::new(AtomicUsize::new(0)); - let (owned_counter, into_counter) = (owned_calls.clone(), into_calls.clone()); - let (_db, mut o) = outbound( - || values(&[7]), - move |reg| { - reg.link_to("mqtt://tele/out") - .with_serializer(move |ctx, r: &TestRecord| { - owned_counter.fetch_add(1, Ordering::SeqCst); - le(ctx, r) - }) - .with_serializer_into(8, move |ctx, r: &TestRecord, out| { - into_counter.fetch_add(1, Ordering::SeqCst); - le_into(ctx, r, out) - }) - .finish(); - }, - ) - .await; - - assert_eq!(pull(&mut o).await, Some(("tele/out".into(), 7, false))); - assert_eq!(into_calls.load(Ordering::SeqCst), 1); - assert_eq!(owned_calls.load(Ordering::SeqCst), 0); - } - - #[tokio::test] - async fn outbound_routes_fall_back_once_when_scratch_is_small() { - let owned_calls = Arc::new(AtomicUsize::new(0)); - let owned_counter = owned_calls.clone(); - let (_db, mut o) = outbound( - || values(&[9]), - move |reg| { - reg.link_to("mqtt://tele/out") - .with_serializer(move |ctx, r: &TestRecord| { - owned_counter.fetch_add(1, Ordering::SeqCst); - le(ctx, r) - }) - .with_serializer_into(2, |_ctx, _r: &TestRecord, _out| { - Err(SerializeError::BufferTooSmall) - }) - .finish(); - }, - ) - .await; - - assert_eq!(pull(&mut o).await, Some(("tele/out".into(), 9, true))); - assert_eq!(owned_calls.load(Ordering::SeqCst), 1); - } - - /// An into-slice serializer that reports more bytes than the scratch - /// holds, or fails with anything but `BufferTooSmall`, skips the value. - #[tokio::test] - async fn outbound_routes_skip_invalid_lengths_and_data() { - let (_db, mut o) = outbound( - || values(&[1, 2, 3]), - |reg| { - reg.link_to("mqtt://tele/out") - .with_serializer(le) - .with_serializer_into(8, |ctx, r: &TestRecord, out| match r.value { - 1 => Ok(out.len() + 1), - 2 => Err(SerializeError::InvalidData), - _ => le_into(ctx, r, out), - }) - .finish(); - }, - ) - .await; - - assert_eq!(pull(&mut o).await, Some(("tele/out".into(), 3, false))); - assert_eq!(o.stats(0).unwrap().serialize_failed, 2); - } - - /// `with_topic_fn` infers an unannotated closure's argument types; - /// `Ok(false)` publishes to the link's default topic. - #[tokio::test] - async fn with_topic_fn_writes_the_topic_or_the_default() { - use core::fmt::Write as _; - let (_db, mut o) = outbound( - || values(&[5, 0]), - |reg| { - reg.link_to("mqtt://tele/out") - .with_topic_fn(8, |v, out| { - if v.value <= 0 { - return Ok(false); - } - write!(out, "dyn/{}", v.value)?; - Ok(true) - }) - .with_serializer(le) - .finish(); - }, - ) - .await; - - assert_eq!(o.routes()[0].topic_capacity, 8); - assert_eq!(pull(&mut o).await.map(|m| m.0), Some("dyn/5".into())); - assert_eq!(pull(&mut o).await.map(|m| m.0), Some("tele/out".into())); - } - - /// A topic that overflows skips its value, even when the writer ignores - /// the error and returns `Ok(true)`. - #[tokio::test] - async fn overflowing_topics_are_skipped() { - use core::fmt::Write as _; - let (_db, mut o) = outbound( - || values(&[123_456, 1_234_567, 7]), - |reg| { - reg.link_to("mqtt://tele/out") - .with_topic_fn(6, |v, out| { - if v.value == 1_234_567 { - let _ = write!(out, "t/{}", v.value); - return Ok(true); - } - write!(out, "t/{}", v.value)?; - Ok(true) - }) - .with_serializer(le) - .finish(); - }, - ) - .await; - - // "t/123456" (8 bytes) and "t/1234567" (9 bytes) do not fit in 6. - assert_eq!(pull(&mut o).await, Some(("t/7".into(), 7, true))); - assert_eq!(o.stats(0).unwrap().topic_overflow, 2); - } - - /// Registrar → build → `OutboundRoutes`, pinning the factory wiring: the - /// serializer set last wins, whichever way its context is typed. - #[tokio::test] - async fn outbound_roundtrip_yields_serialized_values() { - let (_db, mut o) = outbound( - || values(&[5]), - |reg| { - reg.link_to("mqtt://tele/out?qos=1") - .with_serializer(|_ctx, _r: &TestRecord| Ok(vec![0])) - .with_serializer(|_ctx: crate::RuntimeContext, r: &TestRecord| { - Ok(r.value.to_le_bytes().to_vec()) - }) - .with_serializer_into(4, |ctx, r: &TestRecord, out| le_into(ctx, r, out)) - .finish(); - }, - ) - .await; - - let route = &o.routes()[0]; - assert_eq!(&*route.default_topic, "tele/out"); - assert_eq!(route.payload_capacity, 4); - assert_eq!(route.record_index, 0); - assert_eq!(pull(&mut o).await, Some(("tele/out".into(), 5, false))); - assert_eq!(pull(&mut o).await, None); - } - - #[test] - fn serializer_setters_clear_recorded_wire_format() { - use crate::connector::WIRE_FORMAT_KEY; - - let mut rec = crate::typed_record::TypedRecord::::new(); - rec.set_buffer(Box::new(MockBuffer)); - let builders: Vec> = - vec![Box::new(MockConnectorBuilder { - scheme: "mqtt".to_string(), - })]; - let extensions = crate::extensions::Extensions::new(); - let mut reg = make_registrar(&mut rec, &builders, &extensions); - - reg.link_to("mqtt://a") - .with_config(WIRE_FORMAT_KEY, "cdr") - .with_serializer(|_ctx, r: &TestRecord| Ok(r.value.to_le_bytes().to_vec())) - .finish(); - reg.link_to("mqtt://b") - .with_serializer(|_ctx, r: &TestRecord| Ok(r.value.to_le_bytes().to_vec())) - .with_config(WIRE_FORMAT_KEY, "cdr") - .with_serializer_into(4, |_ctx, _r: &TestRecord, _out| Ok(0)) - .finish(); - reg.link_from("mqtt://c") - .with_config(WIRE_FORMAT_KEY, "cdr") - .with_deserializer(|_ctx, _bytes: &[u8]| Ok(TestRecord { value: 0 })) - .finish(); - reg.link_from("mqtt://e") - .with_config(WIRE_FORMAT_KEY, "cdr") - .with_match_deserializer(|_ctx, _m, _bytes: &[u8]| Ok(TestRecord { value: 0 })) - .finish(); - reg.link_to("mqtt://d") - .with_serializer(|_ctx, r: &TestRecord| Ok(r.value.to_le_bytes().to_vec())) - .with_config(WIRE_FORMAT_KEY, "cdr") - .finish(); - - let has_format = - |config: &[(String, String)]| config.iter().any(|(k, _)| k == WIRE_FORMAT_KEY); - let outbound = rec.outbound_connectors(); - assert!(!has_format(&outbound[0].config)); - assert!(!has_format(&outbound[1].config)); - assert!(has_format(&outbound[2].config), "recorded after the setter"); - let inbound = rec.inbound_connectors(); - assert!(!has_format(&inbound[0].config)); - assert!(!has_format(&inbound[1].config)); - } - - /// Connectors read each route's record type and options from its info; - /// a topic writer shows as a non-zero `topic_capacity`. - #[tokio::test] - async fn route_infos_carry_type_config_and_resolved_topic() { - use core::any::TypeId; - - let (_db, outbound) = outbound( - || values(&[]), - |reg| { - reg.link_to("mqtt://tele/fixed") - .with_serializer(le) - .with_config("qos", "1") - .finish(); - reg.link_to("mqtt://tele/written") - .with_topic_fn(16, |_v, _out| Ok(false)) - .with_serializer(le) - .finish(); - }, - ) - .await; - let routes = outbound.routes(); - assert_eq!(routes.len(), 2); - assert!(routes - .iter() - .all(|r| r.type_id == TypeId::of::())); - assert_eq!( - routes[0].config.protocol_options, - vec![("qos".to_string(), "1".to_string())] - ); - assert_eq!(routes[0].topic_capacity, 0); - assert_eq!(routes[1].topic_capacity, 16); - - let resolved = Arc::new(AtomicUsize::new(0)); - let calls = resolved.clone(); - let (db, _last, _count) = inbound_db(move |reg| { - reg.link_from("mqtt://cmd/in") - .with_topic_resolver(move || { - calls.fetch_add(1, Ordering::SeqCst); - Some("cmd/resolved".to_string()) - }) - .with_deserializer(|_ctx, _bytes: &[u8]| Ok(TestRecord { value: 0 })) - .with_config("qos", "2") - .finish(); - reg.link_from("mqtt://dev/{id}") - .with_match_deserializer(key_deser) - .finish(); - }) - .await; - let inbound = crate::InboundDispatch::new(&db, "mqtt", &Plus).expect("routes compile"); - assert_eq!(resolved.load(Ordering::SeqCst), 1, "resolved once"); - - let infos = inbound.routes(); - assert_eq!(infos.len(), inbound.route_count()); - let topics: Vec<&str> = infos.iter().map(|i| &*i.topic).collect(); - assert_eq!(topics, ["cmd/resolved", "dev/{id}"]); - assert!(infos - .iter() - .all(|i| i.type_id == TypeId::of::())); - assert!(infos.iter().all(|i| i.record_index == 0)); - assert_eq!( - infos[0].config.protocol_options, - vec![("qos".to_string(), "2".to_string())] - ); - } - - /// #332: a record's schema and its outbound link addresses reach the - /// graph node and `record.list`. - #[tokio::test] - async fn graph_node_carries_schema_and_outbound_links() { - let key_rec_out_14 = crate::Name::::new("rec.out"); - let key_rec_plain_15 = crate::Name::::new("rec.plain"); - let mut builder = crate::AimDbBuilder::new() - .runtime(Arc::new(MockRuntime)) - .with_connector(NoopConnectorBuilder); - builder.configure(key_rec_out_14, |reg| { - reg.buffer_raw(Box::new(MockBuffer)); - reg.schema("flow", 2).schema("flow", 2); - reg.link_to("mqtt://plant/boiler/flow_avg") - .with_serializer(le) - .finish(); - reg.link_to("mqtt://plant/boiler/flow_raw") - .with_serializer(le) - .finish(); - }); - builder.configure(key_rec_plain_15, |_reg| {}); - let (db, _runner) = builder.build().await.expect("build must succeed"); - - let graph = db.inner().dependency_graph(); - let out = graph.node("rec.out").unwrap(); - assert_eq!( - out.schema, - Some(crate::graph::SchemaInfo { - name: "flow".to_string(), - version: 2 - }) - ); - assert_eq!( - out.outbound_links, - [ - "mqtt://plant/boiler/flow_avg", - "mqtt://plant/boiler/flow_raw" - ] - ); - assert!(out.has_outbound_link); - let plain = graph.node("rec.plain").unwrap(); - assert_eq!( - (plain.schema.as_ref(), plain.has_outbound_link), - (None, false) - ); - assert!(plain.outbound_links.is_empty()); - - #[cfg(feature = "remote")] - { - let records = db.list_records(); - let out = records.iter().find(|r| r.record_key == "rec.out").unwrap(); - assert_eq!(out.schema_type.as_deref(), Some("flow")); - assert_eq!(out.schema_version, Some(2)); - let plain = records - .iter() - .find(|r| r.record_key == "rec.plain") - .unwrap(); - assert_eq!( - (plain.schema_type.as_deref(), plain.schema_version), - (None, None) - ); - } - } - - /// #332: two different schemas on one record fail `build()`. - #[tokio::test] - async fn conflicting_schemas_fail_build() { - let key_rec_x_16 = crate::Name::::new("rec.x"); - let mut builder = crate::AimDbBuilder::new().runtime(Arc::new(MockRuntime)); - builder.configure(key_rec_x_16, |reg| { - reg.schema("flow", 1).schema("flow", 2); - }); - let Err(crate::DbError::InvalidConfiguration { errors }) = builder.build().await else { - panic!("build must fail"); - }; - assert_eq!(errors.len(), 1, "{errors:?}"); - assert_eq!(errors[0].record_key, "rec.x"); - assert!(errors[0].message.contains("flow v1"), "{errors:?}"); - } -} diff --git a/aimdb-core/src/typed_api/consumer.rs b/aimdb-core/src/typed_api/consumer.rs new file mode 100644 index 00000000..2fc40a54 --- /dev/null +++ b/aimdb-core/src/typed_api/consumer.rs @@ -0,0 +1,93 @@ +#[cfg(feature = "observability")] +use alloc::boxed::Box; +use alloc::sync::Arc; +use core::fmt::Debug; +use core::marker::PhantomData; + +use crate::buffer::DynBuffer; + +// ============================================================================ +// Consumer - Type-safe value consumption +// ============================================================================ + +/// Type-safe consumer for a specific record type +/// +/// `Consumer` provides scoped access to subscribe to values of type `T` only. +/// This follows the principle of least privilege - services only get access +/// to what they need, not the entire database. +/// +/// # Type Parameters +/// * `T` - The record type this consumer can subscribe to +/// +/// # Benefits +/// +/// - **Type Safety**: Compile-time guarantee of correct type +/// - **Testability**: Easy to mock for testing +/// - **Clear Intent**: Function signature shows what it consumes +/// - **Decoupling**: No access to other record types +/// - **Security**: Cannot misuse database for unintended operations +pub struct Consumer { + /// Pre-resolved buffer handle to the record's buffer. + buffer: Arc>>, + /// Stage profiling state (set by the spawn machinery for `.tap()` / `.link_to()`). + #[cfg(feature = "observability")] + profiling: Option<(Arc, crate::profiling::Clock)>, + // See Producer: `fn() -> T` keeps Send/Sync independent of T. + _phantom: PhantomData T>, +} + +impl Consumer +where + T: Send + Sync + 'static + Debug + Clone, +{ + /// Create a new consumer bound to a pre-resolved buffer handle. + pub(crate) fn new(buffer: Arc>>) -> Self { + Self { + buffer, + #[cfg(feature = "observability")] + profiling: None, + _phantom: PhantomData, + } + } + + /// Attaches stage profiling state. Internal — called by the spawn machinery. + #[cfg(feature = "observability")] + pub(crate) fn set_profiling( + &mut self, + metrics: Arc, + clock: crate::profiling::Clock, + ) { + self.profiling = Some((metrics, clock)); + } + + /// Subscribe to updates for this record type. + /// + /// Returns a [`Reader`](crate::buffer::Reader) that yields values as they + /// are produced. Its `recv().await` is allocation-free. + /// Infallible — the buffer is pre-resolved at `Consumer` construction. + pub fn subscribe(&self) -> crate::buffer::Reader { + let reader = self.buffer.subscribe_boxed(); + #[cfg(feature = "observability")] + if let Some((metrics, clock)) = &self.profiling { + return crate::buffer::Reader::new(Box::new( + crate::profiling::ProfilingBufferReader::new( + reader, + metrics.clone(), + clock.clone(), + ), + )); + } + crate::buffer::Reader::new(reader) + } +} + +impl Clone for Consumer { + fn clone(&self) -> Self { + Self { + buffer: self.buffer.clone(), + #[cfg(feature = "observability")] + profiling: self.profiling.clone(), + _phantom: PhantomData, + } + } +} diff --git a/aimdb-core/src/typed_api/link_inbound.rs b/aimdb-core/src/typed_api/link_inbound.rs new file mode 100644 index 00000000..172ff7a5 --- /dev/null +++ b/aimdb-core/src/typed_api/link_inbound.rs @@ -0,0 +1,432 @@ +use alloc::{ + string::{String, ToString}, + sync::Arc, + vec::Vec, +}; + +use core::fmt::Debug; + +use crate::typed_api::registrar::{wire_link, WireLink}; +use crate::typed_api::{Detached, DetachedContract, Input, Producer, RecordRegistrar}; +use crate::AimDb; + +// ============================================================================ +// InboundLinkBuilder - Fluent inbound connector configuration +// ============================================================================ + +/// The producer an inbound ingest factory writes to. Factories run during +/// build() after every record is registered and validated, so a failed lookup +/// is an aimdb bug, not a user mistake. +#[allow( + clippy::panic, + reason = "the factory returns no Result and this lookup was validated at build() time" +)] +fn inbound_producer(db: &AimDb, record_key: &str) -> Producer +where + T: Send + Sync + 'static + Debug + Clone, +{ + let writer = db + .inner() + .get_typed_record_by_key_raw::(record_key) + .and_then(|rec| rec.writer_handle()) + .unwrap_or_else(|e| { + panic!( + "ingest factory: no producer for record '{record_key}' ({e:?}) — \ + this is a bug in aimdb-core" + ) + }); + Producer::::new(writer) +} + +/// Fused ingest factory: resolves the typed producer once at route-collection +/// time; per message the returned closure runs deserialize + produce with no +/// erasure crossing. +pub(super) fn ingest_factory( + record_key: String, + deser: TypedMatchDeserializerFn, +) -> crate::connector::IngestFactoryFn +where + T: Send + Sync + 'static + Debug + Clone, +{ + Arc::new(move |db: &AimDb| { + let producer = inbound_producer::(db, &record_key); + let deser = deser.clone(); + Arc::new( + move |ctx: &crate::RuntimeContext, m: &crate::TopicMatch<'_>, payload: &[u8]| { + let admitted = deser(ctx, m, payload)?; + producer.produce(admitted.value); + Ok(admitted.outcome) + }, + ) as crate::connector::IngestFn + }) +} + +/// Type alias for typed context-aware deserializer callbacks +/// +/// Stays typed until registration fuses it with the producer — no +/// per-message erasure. +type TypedContextDeserializerFn = Arc< + dyn Fn(crate::RuntimeContext, &[u8]) -> Result, crate::IngestError> + + Send + + Sync + + 'static, +>; + +/// Like [`TypedContextDeserializerFn`], also receiving the topic match. +pub(super) type TypedMatchDeserializerFn = Arc< + dyn Fn( + &crate::RuntimeContext, + &crate::TopicMatch<'_>, + &[u8], + ) -> Result, crate::IngestError> + + Send + + Sync + + 'static, +>; + +type InboundWireFinalizer = + Arc) -> Result, String> + Send + Sync>; + +/// Inbound link builder attached to a record: what +/// [`RecordRegistrar::link_from`] returns. +/// +/// `'r` is the borrow of the registrar taken by `link_from()`; `'a` is the +/// registrar's own borrow of the record being configured. +pub type InboundConnectorBuilder<'r, 'a, T, S = crate::Undeclared> = + InboundLinkBuilder>; + +/// Inbound link not attached to a record yet, built with +/// [`InboundLink::new`] and registered by [`RecordRegistrar::input`]. +pub type InboundLink = InboundLinkBuilder; + +/// Inbound link carrying a data contract, built by +/// [`InboundLink::into_contract`]: an [`Input`] only of a record whose key +/// declares the contract. +pub type ContractInboundLink = InboundLinkBuilder; + +/// Builder for configuring inbound connector links (External → AimDB) +/// +/// `R` is what the builder is attached to. [`RecordRegistrar::link_from`] +/// returns the attached form, [`InboundConnectorBuilder`], which +/// [`finish()`](InboundLinkBuilder::finish) registers on its record. +/// [`InboundLink::new`] builds the detached form, [`InboundLink`], before +/// any record exists; [`RecordRegistrar::input`] registers it, and checks +/// it then, not when it is built. Both register the same link: +/// +/// ```rust,ignore +/// reg.link_from("mqtt://in").with_deserializer(de).finish(); +/// reg.input(InboundLink::new("mqtt://in").with_deserializer(de)); +/// ``` +/// +/// The option methods below, and the connector crates' extension traits, +/// work on both forms. +#[must_use = "a link does nothing until it is passed to `.input()` or finished with `.finish()`"] +pub struct InboundLinkBuilder { + wire: crate::link_wire::WireOptions, + wire_codec: Option, + wire_finalizer: Option>, + at: R, + pub(super) url: String, + pub(super) connector: Option, + pub(super) config: Vec<(String, String)>, + pub(super) context_deserializer: Option>, + pub(super) match_deserializer: Option>, + pub(super) upgrade_versions: Vec, + pub(super) key: Option<(String, u16)>, + pub(super) topic_resolver: Option, +} + +impl InboundLinkBuilder +where + T: Send + Sync + 'static + Debug + Clone, +{ + /// Starts an inbound link from `address` on a connector registered with + /// [`AimDbBuilder::connect`](crate::AimDbBuilder::connect). + /// + /// `address` is the part after `scheme://`; the connector supplies the + /// scheme. A full URL (as a `#[link_address]` key gives) is accepted if + /// its scheme is the connector's. A different scheme, or a handle from + /// another builder, is reported by `build()` once the link is passed to + /// [`RecordRegistrar::input`]. + pub fn on(connector: crate::ConnectorHandle, address: &str) -> Self { + Self { + connector: Some(connector), + ..Self::new(address) + } + } + + /// Starts an inbound link from `url` that is not attached to a record yet. + pub fn new(url: &str) -> Self { + Self { + at: Detached, + wire: Default::default(), + wire_codec: None, + wire_finalizer: None, + url: url.to_string(), + connector: None, + config: Vec::new(), + context_deserializer: None, + match_deserializer: None, + upgrade_versions: Vec::new(), + key: None, + topic_resolver: None, + } + } + + /// Marks this link as carrying a data contract, so it wires only into a + /// record whose key declares the contract. `aimdb-data-contracts`' + /// `subscribe` calls this; the link's options are unchanged. + pub fn into_contract(self) -> ContractInboundLink { + self.attach(DetachedContract) + } +} + +impl InboundLinkBuilder +where + T: Send + Sync + 'static + Debug + Clone, +{ + pub(super) fn attach(self, at: R) -> InboundLinkBuilder { + InboundLinkBuilder { + at, + wire: self.wire, + wire_codec: self.wire_codec, + wire_finalizer: self.wire_finalizer, + url: self.url, + connector: self.connector, + config: self.config, + context_deserializer: self.context_deserializer, + match_deserializer: self.match_deserializer, + upgrade_versions: self.upgrade_versions, + key: self.key, + topic_resolver: self.topic_resolver, + } + } +} + +impl InboundLinkBuilder +where + T: Send + Sync + 'static + Debug + Clone, +{ + #[doc(hidden)] + pub fn wire_options(&self) -> crate::link_wire::WireOptions { + self.wire + } + #[doc(hidden)] + pub fn with_wire_options(mut self, options: crate::link_wire::WireOptions) -> Self { + self.wire = options; + self + } + #[doc(hidden)] + pub fn wire_codec_info(&self) -> Option { + self.wire_codec + } + #[doc(hidden)] + pub fn with_wire_codec_info(mut self, info: Option) -> Self { + self.wire_codec = info; + self + } + #[doc(hidden)] + pub fn with_wire_finalizer(mut self, replace: bool, finalize: F) -> Self + where + F: Fn(InboundLink) -> Result, String> + Send + Sync + 'static, + { + if replace || self.wire_finalizer.is_none() { + self.wire_finalizer = Some(Arc::new(finalize)); + } + self + } + + fn detach(self) -> (R, InboundLink) { + let link = InboundLinkBuilder { + at: Detached, + wire: self.wire, + wire_codec: self.wire_codec, + wire_finalizer: self.wire_finalizer, + url: self.url, + connector: self.connector, + config: self.config, + context_deserializer: self.context_deserializer, + match_deserializer: self.match_deserializer, + upgrade_versions: self.upgrade_versions, + key: self.key, + topic_resolver: self.topic_resolver, + }; + (self.at, link) + } + + /// Adds a configuration option to the connector + pub fn with_config(mut self, key: &str, value: &str) -> Self { + self.config.push((key.to_string(), value.to_string())); + self + } + + /// Drops any recorded [`WIRE_FORMAT_KEY`](crate::connector::WIRE_FORMAT_KEY): + /// a newly installed codec closure has no known format until a codec verb + /// records one. + fn clear_wire_format(mut self) -> Self { + self.wire_codec = None; + self.config + .retain(|(key, _)| key != crate::connector::WIRE_FORMAT_KEY); + self + } + + /// Sets the deserialization callback + /// + /// The closure receives the [`RuntimeContext`](crate::RuntimeContext) for + /// platform-independent timestamps and logging, plus the raw bytes from + /// the external system. Ignore the context parameter (`|_ctx, data| …`) + /// when it is not needed. Removes any recorded + /// [`WIRE_FORMAT_KEY`](crate::connector::WIRE_FORMAT_KEY). + pub fn with_deserializer(mut self, f: F) -> Self + where + F: Fn(crate::RuntimeContext, &[u8]) -> Result + + Send + + Sync + + 'static, + { + self.context_deserializer = Some(Arc::new(move |ctx, bytes| { + f(ctx, bytes).map(crate::IngestValue::current) + })); + self.upgrade_versions.clear(); + self.clear_wire_format() + } + + /// Like [`with_deserializer`](Self::with_deserializer), also receiving the + /// topic the message arrived on, its captures and its key. The context is + /// borrowed, so no reference count changes per message. Removes any + /// recorded [`WIRE_FORMAT_KEY`](crate::connector::WIRE_FORMAT_KEY). + pub fn with_match_deserializer(mut self, f: F) -> Self + where + F: Fn( + &crate::RuntimeContext, + &crate::TopicMatch<'_>, + &[u8], + ) -> Result + + Send + + Sync + + 'static, + { + self.match_deserializer = Some(Arc::new(move |ctx, m, bytes| { + f(ctx, m, bytes).map(crate::IngestValue::current) + })); + self.upgrade_versions.clear(); + self.clear_wire_format() + } + + /// Installs contract admission with success metadata and declared source + /// versions. Counters are allocated once at registration. Like the match + /// deserializer, this borrows the context and receives wildcard captures. + pub fn with_admitting_deserializer(mut self, versions: &[u32], f: F) -> Self + where + F: Fn( + &crate::RuntimeContext, + &crate::TopicMatch<'_>, + &[u8], + ) -> Result, crate::IngestError> + + Send + + Sync + + 'static, + { + self.match_deserializer = Some(Arc::new(f)); + self.upgrade_versions = versions.to_vec(); + self.clear_wire_format() + } + + /// Clear both inbound callback slots before installing a complete strategy. + #[doc(hidden)] + pub fn clear_deserializers(mut self) -> Self { + self.context_deserializer = None; + self.match_deserializer = None; + self + } + + /// Assigns each value of capture `name` a [`KeyId`](crate::KeyId), up to + /// `capacity` values per record. Messages with a value beyond that are + /// dropped. A value keeps its key even if its payload fails to + /// deserialize, and keys are never freed, so anyone who can publish under + /// the pattern can fill the table. + pub fn key(mut self, name: &str, capacity: u16) -> Self { + self.key = Some((name.to_string(), capacity)); + self + } + + /// Sets the operation timeout in milliseconds (the connector interprets + /// it; passed as the `timeout_ms` option — see + /// `ConnectorConfig::from_query`) + /// + /// Protocol-specific knobs (e.g. MQTT subscribe QoS) are provided by the + /// connector crates as extension traits over this builder, or generically + /// via [`with_config`](Self::with_config). + pub fn with_timeout_ms(mut self, timeout_ms: u32) -> Self { + self.config + .push(("timeout_ms".to_string(), timeout_ms.to_string())); + self + } + + /// Sets a dynamic topic resolver for late-binding scenarios + /// + /// The resolver is called once at connector startup to determine + /// the subscription topic. Return `None` to use the default + /// static topic from the URL. + /// + /// # Use Cases + /// + /// - Topics determined from smart contracts at runtime + /// - Service discovery integration + /// - Environment-specific topic configuration + pub fn with_topic_resolver(mut self, resolver: F) -> Self + where + F: Fn() -> Option + Send + Sync + 'static, + { + self.topic_resolver = Some(Arc::new(resolver)); + self + } +} + +impl<'r, 'a, T, S: crate::SchemaState> InboundLinkBuilder> +where + T: Send + Sync + 'static + Debug + Clone, +{ + /// Finalizes the inbound connector registration + /// + /// Configuration mistakes — an invalid URL, a missing deserializer, an + /// unregistered scheme, or a conflict with `.source()`/`.transform()` + /// (local producer + inbound connector would race as last-writer-wins) — + /// are recorded instead of panicking: the link is **not** registered and + /// `build()` reports every finding via `DbError::InvalidConfiguration`. + /// The registrar is returned either way so chained configuration keeps + /// compiling; the failed `build()` is the single error surface. + /// + /// The buffer requirement is validated by `build()` (calling `.buffer()` + /// after `.link_from()` is fine). + pub fn finish(self) -> &'r mut RecordRegistrar<'a, T, S> { + let (registrar, link) = self.detach(); + registrar.push_inbound(link); + registrar + } +} + +/// A contract link is an input only of a record whose key declares the +/// contract: `subscribe(..)` on a `Name` record does not compile. +impl Input for ContractInboundLink +where + T: Send + Sync + 'static + Debug + Clone, +{ + fn wire(self, reg: &mut RecordRegistrar<'_, T, S>) { + reg.push_inbound(self.attach(Detached)); + } +} + +wire_link!(InboundLink); + +impl Input for InboundLink +where + T: Send + Sync + 'static + Debug + Clone, +{ + fn wire(self, reg: &mut RecordRegistrar<'_, T, S>) { + reg.push_inbound(self); + } +} + +#[cfg(test)] +mod tests {} diff --git a/aimdb-core/src/typed_api/link_outbound.rs b/aimdb-core/src/typed_api/link_outbound.rs new file mode 100644 index 00000000..09d263bd --- /dev/null +++ b/aimdb-core/src/typed_api/link_outbound.rs @@ -0,0 +1,480 @@ +use alloc::{ + string::{String, ToString}, + sync::Arc, + vec::Vec, +}; + +use core::fmt::Debug; + +use super::registrar::{ + wire_link, TypedContextSerializerFn, TypedContextSerializerIntoFn, WireLink, +}; +use crate::typed_api::{Consumer, Detached, DetachedContract, Output, RecordRegistrar}; +use crate::AimDb; + +// ============================================================================ +// Outbound routes +// ============================================================================ + +/// Type alias for the unified typed serializer captured by [`TypedRoute`] +/// +/// Raw and context-aware serializers collapse into this shape at `finish()`; +/// the raw variant simply ignores the threaded context. +pub(super) type FusedSerializeFn = Arc< + dyn Fn(&crate::RuntimeContext, &T) -> Result, crate::connector::SerializeError> + + Send + + Sync, +>; + +/// Builds a link's `Consumer` from the live database, once per route. +pub(super) type ConsumerFactoryFn = Arc Consumer + Send + Sync>; + +/// Optional allocation-free serializer captured beside [`FusedSerializeFn`]. +/// +/// The callback writes into the `OutboundRoutes` scratch buffer. Returning +/// `BufferTooSmall` selects the owned serializer for that value; other failures +/// retain the existing skip-and-log behavior. +pub(super) type FusedSerializeIntoFn = Arc< + dyn Fn(&crate::RuntimeContext, &T, &mut [u8]) -> Result + + Send + + Sync, +>; + +/// An outbound link's topic writer and the capacity it writes into. +type TopicWriterCfg = (usize, Arc>); + +/// Runs `writer` for `value` into `out`. `Ok(true)`: publish to what `out` +/// holds; `Ok(false)`: to the link's default topic; `Err`: the topic did not +/// fit and the value is skipped, whatever the writer returned. +pub(super) fn write_topic + ?Sized>( + writer: &W, + value: &T, + out: &mut crate::connector::TopicBuf<'_>, +) -> Result { + match writer.write_topic(value, out) { + Ok(written) if !out.overflowed() => Ok(written), + _ => Err(crate::connector::TopicOverflow), + } +} + +/// Serializes one outbound value: into `scratch` through +/// `with_serializer_into` when the link has one, else (or when the value does +/// not fit) through the owned serializer. +pub(super) fn serialize_outbound( + serialize: &FusedSerializeFn, + serialize_into: Option<&FusedSerializeIntoFn>, + ctx: &crate::RuntimeContext, + value: &T, + scratch: &mut [u8], +) -> Result { + use crate::connector::SerializeError; + use crate::outbound::{SerializeFailure, StagedPayload}; + + let Some(serialize_into) = serialize_into else { + return serialize(ctx, value) + .map(StagedPayload::Owned) + .map_err(SerializeFailure::Owned); + }; + match serialize_into(ctx, value, scratch) { + Ok(len) if len <= scratch.len() => Ok(StagedPayload::Scratch(len)), + Ok(len) => Err(SerializeFailure::InvalidLength { + len, + capacity: scratch.len(), + }), + Err(SerializeError::BufferTooSmall) => serialize(ctx, value) + .map(StagedPayload::Owned) + .map_err(SerializeFailure::Fallback), + Err(e) => Err(SerializeFailure::Into(e)), + } +} + +/// One outbound link's per-route state inside +/// [`OutboundRoutes`](crate::OutboundRoutes): reader, topic writer and +/// serializers, all typed. +pub(super) struct TypedRoute { + pub(super) reader: crate::buffer::Reader, + pub(super) writer: Option>>, + pub(super) serialize: FusedSerializeFn, + pub(super) serialize_into: Option>, +} + +impl crate::outbound::PollRoute for TypedRoute { + fn poll_route( + &mut self, + cx: &mut core::task::Context<'_>, + ctx: &crate::RuntimeContext, + topic: &mut [u8], + payload: &mut [u8], + ) -> core::task::Poll { + use crate::outbound::RouteOutcome; + use core::task::Poll; + + let sample = match self.reader.poll_recv(cx) { + Poll::Pending => return Poll::Pending, + Poll::Ready(Ok(sample)) => sample, + Poll::Ready(Err(crate::DbError::BufferLagged { lag_count, .. })) => { + return Poll::Ready(RouteOutcome::Lagged(lag_count)); + } + Poll::Ready(Err(e)) => return Poll::Ready(RouteOutcome::Closed(e)), + }; + + let topic_len = match &self.writer { + None => None, + Some(writer) => { + let mut out = crate::connector::TopicBuf::new(topic); + match write_topic(&**writer, &sample.value, &mut out) { + Ok(written) => written.then_some(out.len()), + Err(_) => return Poll::Ready(RouteOutcome::TopicOverflow), + } + } + }; + + let serialized = serialize_outbound( + &self.serialize, + self.serialize_into.as_ref(), + ctx, + &sample.value, + payload, + ); + Poll::Ready(match serialized { + Ok(payload) => RouteOutcome::Staged { + topic_len, + payload, + metadata: *sample.metadata(), + }, + Err(failure) => RouteOutcome::SerializeFailed(failure), + }) + } +} + +// ============================================================================ +// Link builders - Fluent connector link configuration +// ============================================================================ + +/// Outbound link builder attached to a record: what +/// [`RecordRegistrar::link_to`] returns. +/// +/// `'r` is the borrow of the registrar taken by `link_to()`; `'a` is the +/// registrar's own borrow of the record being configured. +pub type OutboundConnectorBuilder<'r, 'a, T, S = crate::Undeclared> = + OutboundLinkBuilder>; + +/// Outbound link not attached to a record yet, built with +/// [`OutboundLink::new`] and registered by [`RecordRegistrar::output`]. +pub type OutboundLink = OutboundLinkBuilder; + +/// Outbound link carrying a data contract, built by +/// [`OutboundLink::into_contract`]: an [`Output`] only of a record whose key +/// declares the contract. +pub type ContractOutboundLink = OutboundLinkBuilder; + +type OutboundWireFinalizer = + Arc) -> Result, String> + Send + Sync>; + +/// Builder for configuring outbound connector links (AimDB → External) +/// +/// `R` is what the builder is attached to. [`RecordRegistrar::link_to`] +/// returns the attached form, [`OutboundConnectorBuilder`], which +/// [`finish()`](OutboundLinkBuilder::finish) registers on its record. +/// [`OutboundLink::new`] builds the detached form, [`OutboundLink`], before +/// any record exists; [`RecordRegistrar::output`] registers it, and checks +/// it then, not when it is built. Both register the same link: +/// +/// ```rust,ignore +/// reg.link_to("mqtt://out").with_serializer(ser).finish(); +/// reg.output(OutboundLink::new("mqtt://out").with_serializer(ser)); +/// ``` +/// +/// The option methods below, and the connector crates' extension traits, +/// work on both forms. +#[must_use = "a link does nothing until it is passed to `.output()` or finished with `.finish()`"] +pub struct OutboundLinkBuilder { + wire: crate::link_wire::WireOptions, + wire_codec: Option, + wire_finalizer: Option>, + at: R, + pub(super) url: String, + pub(super) connector: Option, + pub(super) config: Vec<(String, String)>, + pub(super) context_serializer: Option>, + pub(super) context_serializer_into: Option<(usize, TypedContextSerializerIntoFn)>, + pub(super) topic_writer: Option>, +} + +impl OutboundLinkBuilder +where + T: Send + Sync + 'static + Debug + Clone, +{ + /// Starts an outbound link to `address` on a connector registered with + /// [`AimDbBuilder::connect`](crate::AimDbBuilder::connect). + /// + /// `address` is the part after `scheme://`; the connector supplies the + /// scheme. A full URL (as a `#[link_address]` key gives) is accepted if + /// its scheme is the connector's. A different scheme, or a handle from + /// another builder, is reported by `build()` once the link is passed to + /// [`RecordRegistrar::output`]. + pub fn on(connector: crate::ConnectorHandle, address: &str) -> Self { + Self { + connector: Some(connector), + ..Self::new(address) + } + } + + /// Starts an outbound link to `url` that is not attached to a record yet. + pub fn new(url: &str) -> Self { + Self { + at: Detached, + wire: Default::default(), + wire_codec: None, + wire_finalizer: None, + url: url.to_string(), + connector: None, + config: Vec::new(), + context_serializer: None, + context_serializer_into: None, + topic_writer: None, + } + } + + /// Marks this link as carrying a data contract, so it wires only into a + /// record whose key declares the contract. `aimdb-data-contracts`' + /// `publish` calls this; the link's options are unchanged. + pub fn into_contract(self) -> ContractOutboundLink { + self.attach(DetachedContract) + } +} + +impl OutboundLinkBuilder +where + T: Send + Sync + 'static + Debug + Clone, +{ + pub(super) fn attach(self, at: R) -> OutboundLinkBuilder { + OutboundLinkBuilder { + at, + wire: self.wire, + wire_codec: self.wire_codec, + wire_finalizer: self.wire_finalizer, + url: self.url, + connector: self.connector, + config: self.config, + context_serializer: self.context_serializer, + context_serializer_into: self.context_serializer_into, + topic_writer: self.topic_writer, + } + } +} + +impl OutboundLinkBuilder +where + T: Send + Sync + 'static + Debug + Clone, +{ + #[doc(hidden)] + pub fn wire_options(&self) -> crate::link_wire::WireOptions { + self.wire + } + #[doc(hidden)] + pub fn with_wire_options(mut self, options: crate::link_wire::WireOptions) -> Self { + self.wire = options; + self + } + #[doc(hidden)] + pub fn wire_codec_info(&self) -> Option { + self.wire_codec + } + #[doc(hidden)] + pub fn with_wire_codec_info(mut self, info: Option) -> Self { + self.wire_codec = info; + self + } + #[doc(hidden)] + pub fn with_wire_finalizer(mut self, replace: bool, finalize: F) -> Self + where + F: Fn(OutboundLink) -> Result, String> + Send + Sync + 'static, + { + if replace || self.wire_finalizer.is_none() { + self.wire_finalizer = Some(Arc::new(finalize)); + } + self + } + + fn detach(self) -> (R, OutboundLink) { + let link = OutboundLinkBuilder { + at: Detached, + wire: self.wire, + wire_codec: self.wire_codec, + wire_finalizer: self.wire_finalizer, + url: self.url, + connector: self.connector, + config: self.config, + context_serializer: self.context_serializer, + context_serializer_into: self.context_serializer_into, + topic_writer: self.topic_writer, + }; + (self.at, link) + } + + /// Adds a configuration option to the connector + pub fn with_config(mut self, key: &str, value: &str) -> Self { + self.config.push((key.to_string(), value.to_string())); + self + } + + /// Drops any recorded [`WIRE_FORMAT_KEY`](crate::connector::WIRE_FORMAT_KEY): + /// a newly installed codec closure has no known format until a codec verb + /// records one. + fn clear_wire_format(mut self) -> Self { + self.wire_codec = None; + self.config + .retain(|(key, _)| key != crate::connector::WIRE_FORMAT_KEY); + self + } + + /// Sets the serialization callback + /// + /// The closure receives the [`RuntimeContext`](crate::RuntimeContext) for + /// platform-independent timestamps and logging, plus the typed value being + /// serialized. Ignore the context parameter (`|_ctx, value| …`) when it is + /// not needed. Removes any recorded + /// [`WIRE_FORMAT_KEY`](crate::connector::WIRE_FORMAT_KEY). + pub fn with_serializer(mut self, f: F) -> Self + where + F: Fn(crate::RuntimeContext, &T) -> Result, crate::connector::SerializeError> + + Send + + Sync + + 'static, + { + self.context_serializer = Some(Arc::new(f)); + self.clear_wire_format() + } + + /// Adds an into-slice fast path beside the required owned serializer. + /// + /// One zero-initialized scratch buffer of `capacity` bytes is allocated when + /// each route pump starts, then reused for every message. A successful + /// callback returns the initialized prefix length. The framework validates + /// that length before borrowing the prefix. `BufferTooSmall` falls back to + /// [`with_serializer`](Self::with_serializer) for that value; any other + /// codec error is logged and the value is skipped. + /// + /// This method is an optimization only: callers must still install the + /// owned serializer so oversized and legacy values retain their old behavior. + /// Removes any recorded [`WIRE_FORMAT_KEY`](crate::connector::WIRE_FORMAT_KEY). + pub fn with_serializer_into(mut self, capacity: usize, f: F) -> Self + where + F: Fn( + crate::RuntimeContext, + &T, + &mut [u8], + ) -> Result + + Send + + Sync + + 'static, + { + self.context_serializer_into = Some((capacity, Arc::new(f))); + self.clear_wire_format() + } + + /// Removes a previously installed into-slice serializer. + /// + /// Higher-level builder extensions use this when replacing a bounded + /// serialization strategy with an owned-only one. Clearing the fast path + /// prevents the old scratch serializer from emitting a different wire + /// format beside the replacement owned serializer. + pub fn clear_serializer_into(mut self) -> Self { + self.context_serializer_into = None; + self + } + + /// Sets the operation timeout in milliseconds (the connector interprets + /// it; passed as the `timeout_ms` option — see + /// `ConnectorConfig::from_query`) + /// + /// Protocol-specific knobs (e.g. MQTT QoS/retain) are provided by the + /// connector crates as extension traits over this builder, or generically + /// via [`with_config`](Self::with_config). + pub fn with_timeout_ms(mut self, timeout_ms: u32) -> Self { + self.config + .push(("timeout_ms".to_string(), timeout_ms.to_string())); + self + } + + /// Sets a [`TopicWriter`](crate::connector::TopicWriter) that writes each + /// value's destination. + /// + /// `capacity` is the longest topic the writer produces, in bytes. A value + /// whose topic does not fit is skipped and logged. For a closure, use + /// [`with_topic_fn`](Self::with_topic_fn). + pub fn with_topic_writer(mut self, capacity: usize, writer: W) -> Self + where + W: crate::connector::TopicWriter + 'static, + { + self.topic_writer = Some((capacity, Arc::new(writer))); + self + } + + /// Sets a closure that writes each value's destination; see + /// [`with_topic_writer`](Self::with_topic_writer). + /// + /// ```rust,ignore + /// .with_topic_fn(32, |v, out| { + /// write!(out, "sensors/{}/{}", v.site, v.id)?; + /// Ok(true) + /// }) + /// ``` + pub fn with_topic_fn(self, capacity: usize, f: F) -> Self + where + F: Fn( + &T, + &mut crate::connector::TopicBuf<'_>, + ) -> Result + + Send + + Sync + + 'static, + { + self.with_topic_writer(capacity, f) + } +} + +impl<'r, 'a, T, S: crate::SchemaState> OutboundLinkBuilder> +where + T: Send + Sync + 'static + Debug + Clone, +{ + /// Finalizes the connector registration + /// + /// Configuration mistakes — an invalid URL, a missing serializer, or an + /// unregistered scheme — are recorded instead of panicking: the link is + /// **not** registered and `build()` reports every finding via + /// `DbError::InvalidConfiguration`. The registrar is returned either way + /// so chained configuration keeps compiling; the failed `build()` is the + /// single error surface. + /// + /// The buffer requirement is validated by `build()` (calling `.buffer()` + /// after `.link_to()` is fine). + pub fn finish(self) -> &'r mut RecordRegistrar<'a, T, S> { + let (registrar, link) = self.detach(); + registrar.push_outbound(link); + registrar + } +} + +/// A contract link is an output only of a record whose key declares the +/// contract: `publish(..)` on a `Name` record does not compile. +impl Output for ContractOutboundLink +where + T: Send + Sync + 'static + Debug + Clone, +{ + fn wire(self, reg: &mut RecordRegistrar<'_, T, S>) { + reg.push_outbound(self.attach(Detached)); + } +} + +wire_link!(OutboundLink); + +impl Output for OutboundLink +where + T: Send + Sync + 'static + Debug + Clone, +{ + fn wire(self, reg: &mut RecordRegistrar<'_, T, S>) { + reg.push_outbound(self); + } +} diff --git a/aimdb-core/src/typed_api/mod.rs b/aimdb-core/src/typed_api/mod.rs new file mode 100644 index 00000000..e4482c08 --- /dev/null +++ b/aimdb-core/src/typed_api/mod.rs @@ -0,0 +1,201 @@ +//! Type-safe Producer-Consumer API +//! +//! Provides the complete typed API for producer-consumer patterns including: +//! - `Producer` - Type-safe value production +//! - `Consumer` - Type-safe value consumption +//! - `RecordRegistrar` - Fluent record configuration API +//! - `RecordT` trait - Self-registering records +//! +//! # Producer Example +//! +//! ```no_run +//! # use aimdb_core::{Producer, RuntimeContext}; +//! # #[derive(Clone, Debug)] struct Temperature { celsius: f32 } +//! # async fn read_sensor() -> Temperature { Temperature { celsius: 21.0 } } +//! async fn temperature_producer( +//! ctx: RuntimeContext, +//! producer: Producer, +//! ) { +//! loop { +//! let temp = read_sensor().await; +//! producer.produce(temp); +//! ctx.time().sleep_secs(1).await; +//! } +//! } +//! ``` +//! +//! # Consumer Example +//! +//! ```no_run +//! # use aimdb_core::{Consumer, RuntimeContext}; +//! # #[derive(Clone, Debug)] struct Temperature { celsius: f32 } +//! async fn temperature_monitor( +//! ctx: RuntimeContext, +//! consumer: Consumer, +//! ) { +//! let mut rx = consumer.subscribe(); +//! // Each value comes with the metadata of the write that stored it. +//! while let Ok(temp) = rx.recv().await { +//! ctx.log().info(&format!( +//! "Temp: {:.1}°C, written at {:?}", +//! temp.value.celsius, +//! temp.stamp() +//! )); +//! } +//! } +//! ``` +//! +//! # Record Registration Example +//! +//! Illustrative (not compiled: `.buffer()` comes from your runtime adapter's +//! registrar extension trait, which `aimdb-core` cannot depend on): +//! +//! ```rust,ignore +//! let record_1 = aimdb_core::Name::::new("sensors.outdoor"); +//! builder.configure(record_1, |reg| { +//! reg.buffer(cfg) +//! .source(temperature_producer) +//! .tap(temperature_monitor) +//! .link_to("mqtt://sensors/temp") +//! .with_serializer(|_ctx, t| serde_json::to_vec(t)) +//! .finish(); +//! }); +//! ``` + +use core::fmt::Debug; + +mod consumer; +mod link_inbound; +mod link_outbound; +mod producer; +mod registrar; + +pub use crate::typed_api::{ + consumer::Consumer, + link_inbound::{ContractInboundLink, InboundConnectorBuilder, InboundLink, InboundLinkBuilder}, + link_outbound::{ + ContractOutboundLink, OutboundConnectorBuilder, OutboundLink, OutboundLinkBuilder, + }, + producer::Producer, + registrar::{RecordRegistrar, StageKind}, +}; + +/// Marks a link builder that is not attached to a record yet. +/// +/// See [`OutboundLink`] and [`InboundLink`]. +#[derive(Debug, Clone, Copy, Default)] +pub struct Detached; + +/// Marks a detached link that carries a data contract: what +/// `aimdb-data-contracts`' `publish` / `subscribe` return. +/// +/// It takes every option a [`Detached`] link takes, but is an +/// [`Input`] / [`Output`] only of a record whose key declares the contract +/// ([`ContractDeclared`](crate::ContractDeclared)). +#[derive(Debug, Clone, Copy, Default)] +pub struct DetachedContract; + +// ============================================================================ +// Input / Output - what `.input()` and `.output()` accept +// ============================================================================ + +/// Something that can write into a `T` record, passed to +/// [`RecordRegistrar::input`]. +/// +/// [`InboundLink`] implements it. `wire` receives the full registrar, so an +/// input may call `.source()`, `.link_from()`, `.buffer()` or anything else a +/// `configure` closure can; inputs are expected to only add a writer. +/// +/// Two conventions make wiring mistakes compile errors: +/// +/// - **An input yields an event, and records are built with `From`.** A +/// device input implements `Input` for every `T: From`, so one +/// input type serves every contract that can be built from its event. - **A device channel is an owned value that is not `Clone`.** A board +/// hands out its channels once, and an input takes one by value, so wiring +/// one device into two records is `use of moved value`. +/// +/// ``` +/// use aimdb_core::{Input, RecordRegistrar}; +/// use core::fmt::Debug; +/// +/// /// Produces 0, 1, 2 into any record built from an `i32`. +/// struct Counter; +/// +/// impl Input for Counter +/// where +/// T: From + Send + Sync + 'static + Debug + Clone, +/// { +/// fn wire(self, reg: &mut RecordRegistrar<'_, T, S>) { +/// reg.source(|_ctx, producer| async move { +/// for i in 0..3 { +/// producer.produce(T::from(i)); +/// } +/// }); +/// } +/// } +/// ``` +/// +/// A channel used for a second record does not compile: +/// +/// ```compile_fail,E0382 +/// # use aimdb_core::{Input, RecordRegistrar}; +/// # use core::fmt::Debug; +/// /// A device channel, handed out once by the board. Not `Clone`. +/// struct Channel; +/// +/// /// An input on one channel. +/// struct Sensor(Channel); +/// +/// impl Input for Sensor +/// where +/// T: From + Send + Sync + 'static + Debug + Clone, +/// { +/// fn wire(self, reg: &mut RecordRegistrar<'_, T, S>) { +/// reg.source(|_ctx, producer| async move { producer.produce(T::from(0)) }); +/// } +/// } +/// +/// #[derive(Clone, Debug)] +/// struct Level(u8); +/// +/// impl From for Level { +/// fn from(raw: u8) -> Self { +/// Level(raw) +/// } +/// } +/// +/// fn wire( +/// first: &mut RecordRegistrar<'_, Level>, +/// second: &mut RecordRegistrar<'_, Level>, +/// channel: Channel, +/// ) { +/// first.input(Sensor(channel)); +/// second.input(Sensor(channel)); // use of moved value: `channel` +/// } +/// ``` +#[diagnostic::on_unimplemented( + message = "`{Self}` cannot be the input of a `{T}` record", + label = "not an input for `{T}`", + note = "an input implements `Input<{T}>`; device inputs usually do so for every `T: From`" +)] +pub trait Input { + /// Registers this input's writer on the record. + fn wire(self, reg: &mut RecordRegistrar<'_, T, S>); +} + +/// Something that can read from a `T` record, passed to +/// [`RecordRegistrar::output`]. +/// +/// [`OutboundLink`] implements it. Like [`Input`], `wire` receives the +/// full registrar. +#[diagnostic::on_unimplemented( + message = "`{Self}` cannot be an output of a `{T}` record", + label = "not an output for `{T}`" +)] +pub trait Output { + /// Registers this output's reader on the record. + fn wire(self, reg: &mut RecordRegistrar<'_, T, S>); +} + +#[cfg(test)] +mod tests; diff --git a/aimdb-core/src/typed_api/producer.rs b/aimdb-core/src/typed_api/producer.rs new file mode 100644 index 00000000..ef5d8bf4 --- /dev/null +++ b/aimdb-core/src/typed_api/producer.rs @@ -0,0 +1,132 @@ +use alloc::sync::Arc; +use core::fmt::Debug; +use core::marker::PhantomData; + +use crate::buffer::{TryProduceError, WriteHandle}; + +// ============================================================================ +// Producer - Type-safe value production +// ============================================================================ + +/// Type-safe producer for a specific record type +/// +/// `Producer` provides scoped access to produce values of type `T` only. +/// This follows the principle of least privilege - services only get access +/// to what they need, not the entire database. +/// +/// # Type Parameters +/// * `T` - The record type this producer can emit +/// +/// Pre-binds the record's buffer, latest-snapshot slot, and metadata tracker +/// (via an internal `Arc>`), so `produce()` is a single +/// virtual call rather than a `HashMap` lookup + downcast on each invocation +///. +/// +/// # Benefits +/// +/// - **Type Safety**: Compile-time guarantee of correct type +/// - **Testability**: Easy to mock for testing +/// - **Clear Intent**: Function signature shows what it produces +/// - **Decoupling**: No access to other record types +/// - **Security**: Cannot misuse database for unintended operations +pub struct Producer { + /// Pre-resolved write handle to the record's buffer/snapshot/metadata. + write: Arc>, + /// Stage profiling state (set by the spawn machinery for `.source()` stages). + #[cfg(feature = "observability")] + profiling: Option>, + // `fn() -> T` carries T without forcing Producer's Send/Sync to depend on T. + // T is only a type-system marker here — it is never stored or referenced. + _phantom: PhantomData T>, +} + +impl Producer +where + T: Send + 'static + Debug + Clone, +{ + /// Create a new producer bound to a pre-resolved write handle. + pub(crate) fn new(write: Arc>) -> Self { + Self { + write, + #[cfg(feature = "observability")] + profiling: None, + _phantom: PhantomData, + } + } + + /// Attaches stage profiling state. Internal — called by the spawn machinery. + #[cfg(feature = "observability")] + pub(crate) fn set_profiling( + &mut self, + metrics: Arc, + clock: crate::profiling::Clock, + ) { + self.profiling = Some(Arc::new(crate::profiling::ProducerProfilingState::new( + metrics, clock, + ))); + } + + /// Push a value. Infallible — overwrite-on-overflow buffers cannot reject. + /// Use this for fire-and-forget telemetry. + /// + /// Forwards the value to the record's buffer, the latest-snapshot slot, + /// and the metadata tracker in a single synchronous call. + /// + /// # Example + /// + /// ```no_run + /// # use aimdb_core::{Producer, RuntimeContext}; + /// # #[derive(Clone, Debug)] struct Telemetry { celsius: f32 } + /// # async fn read_sensor() -> Telemetry { Telemetry { celsius: 21.0 } } + /// async fn sensor_loop(ctx: RuntimeContext, producer: Producer) { + /// loop { + /// producer.produce(read_sensor().await); + /// ctx.time().sleep_secs(1).await; + /// } + /// } + /// ``` + pub fn produce(&self, value: T) { + #[cfg(feature = "observability")] + if let Some(state) = &self.profiling { + state.record_produce(); + } + self.write.push(value); + } + + /// Lets a write handle report that it rejected a value. + /// + /// All current buffers (`SpmcRing`, `SingleLatest`, `Mailbox`) overwrite + /// existing values when full and return `Ok(())`. Use + /// [`produce`](Self::produce) for them. A future buffer that refuses a + /// write when full can return the value through [`TryProduceError::Full`]. + /// A buffer that detects closure can return it through + /// [`TryProduceError::Closed`]. + /// + /// # Example + /// + /// ```no_run + /// # use aimdb_core::{Producer, TryProduceError}; + /// # #[derive(Clone, Debug)] struct Command { id: u32 } + /// fn send_command(producer: &Producer, cmd: Command) { + /// match producer.try_produce(cmd) { + /// Ok(()) => {} + /// Err(TryProduceError::Full(_)) => { /* backpressure: retry later */ } + /// Err(TryProduceError::Closed(_)) => { /* record shut down */ } + /// } + /// } + /// ``` + pub fn try_produce(&self, value: T) -> Result<(), TryProduceError> { + self.write.try_push(value) + } +} + +impl Clone for Producer { + fn clone(&self) -> Self { + Self { + write: self.write.clone(), + #[cfg(feature = "observability")] + profiling: self.profiling.clone(), + _phantom: PhantomData, + } + } +} diff --git a/aimdb-core/src/typed_api/registrar.rs b/aimdb-core/src/typed_api/registrar.rs new file mode 100644 index 00000000..150f1322 --- /dev/null +++ b/aimdb-core/src/typed_api/registrar.rs @@ -0,0 +1,793 @@ +use alloc::{ + boxed::Box, + string::{String, ToString}, + sync::Arc, + vec::Vec, +}; + +use core::fmt::Debug; +use core::future::Future; + +use crate::typed_api::{ + link_inbound::{ingest_factory, TypedMatchDeserializerFn}, + link_outbound::{ + serialize_outbound, write_topic, ConsumerFactoryFn, FusedSerializeFn, FusedSerializeIntoFn, + TypedRoute, + }, + Consumer, InboundConnectorBuilder, InboundLink, Input, OutboundConnectorBuilder, OutboundLink, + Output, +}; +use crate::typed_record::TypedRecord; +use crate::AimDb; + +// ============================================================================ +// RecordRegistrar - Fluent registration API +// ============================================================================ + +/// Type alias for typed context-aware serializer callbacks +/// +/// Stays typed until registration fuses it with the consumer — no per-message +/// erasure. +pub(super) type TypedContextSerializerFn = Arc< + dyn Fn(crate::RuntimeContext, &T) -> Result, crate::connector::SerializeError> + + Send + + Sync + + 'static, +>; + +/// Typed into-slice serializer stored by [`OutboundLinkBuilder`]. +pub(super) type TypedContextSerializerIntoFn = Arc< + dyn Fn(crate::RuntimeContext, &T, &mut [u8]) -> Result + + Send + + Sync + + 'static, +>; + +/// Kind of execution stage, used to address per-stage profiling metrics and to +/// remember which stage `RecordRegistrar::with_name` should rename. +#[doc(hidden)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum StageKind { + /// A `.source()` producer callback. + Source, + /// A `.tap()` observer callback. + Tap, + /// An outbound `.link_to()` connector. + Link, + /// A `.transform()` callback (reserved; not yet instrumented). + Transform, +} + +/// Registrar for configuring a typed record +/// +/// Provides a fluent API for registering producer and consumer functions. +/// +/// `S` is the record's [`SchemaState`](crate::SchemaState): `configure` +/// hands out [`Declared`](crate::Declared) for a key that declares a data +/// contract (`Key`, `#[record_key(contract = T)]`) and +/// [`Undeclared`](crate::Undeclared) otherwise. Contract-only verbs +/// (`linked_to`, `publish`, `observe`, …) are implemented only for +/// `Declared`, so using one on a `Name` record does not compile. +/// Everything else works in both states; extension traits implement for any +/// `S: SchemaState`. +pub struct RecordRegistrar< + 'a, + T: Send + Sync + 'static + Debug + Clone, + S: crate::SchemaState = crate::Undeclared, +> { + /// The typed record being configured + pub(crate) rec: &'a mut TypedRecord, + /// Connector builders indexed by scheme + pub(crate) connector_builders: &'a [Box], + /// The builder's id, checked against + /// [`ConnectorHandle`](crate::ConnectorHandle)s on links. + pub(crate) builder_id: u32, + /// The record key for this record + pub(crate) record_key: String, + pub(crate) key_link_address: Option, + /// Extension storage from the builder — allows external crates (e.g. + /// `aimdb-persistence`) to retrieve typed state inside `.persist()`. + pub(crate) extensions: &'a crate::extensions::Extensions, + /// The most recently registered stage, so `.with_name()` knows what to name. + /// Tracked even when the `observability` feature is off (then it's just unused). + #[cfg_attr(not(feature = "observability"), allow(dead_code))] + pub(crate) last_stage: Option<(StageKind, usize)>, + pub(crate) _schema: core::marker::PhantomData S>, +} + +impl<'a, T, S: crate::SchemaState> RecordRegistrar<'a, T, S> +where + T: Send + Sync + 'static + Debug + Clone, +{ + /// Returns a reference to the builder's extension storage. + /// + /// External crates call this inside their `.persist()` (or similar) extension + /// methods to retrieve typed state that was stored via + /// `builder.extensions_mut().insert(...)` before `configure()` was called. + pub fn extensions(&self) -> &crate::extensions::Extensions { + self.extensions + } + + /// Returns the key this record is registered under. + /// + /// Extension crates use it to name per-record state; `aimdb-persistence` + /// stores a record's history under this key. + pub fn record_key(&self) -> &str { + &self.record_key + } + + /// Assigns a human-readable name to the stage registered immediately before + /// this call (the most recent `.source()`, `.tap()`, or `.link_to()`). + /// + /// The name shows up in stage profiling output. This method is always + /// available; when the `observability` feature is disabled it is a no-op. + pub fn with_name(&mut self, name: &str) -> &mut Self { + #[cfg(feature = "observability")] + if let Some((kind, idx)) = self.last_stage { + self.rec.profiling_mut().set_stage_name(kind, idx, name); + } + #[cfg(not(feature = "observability"))] + let _ = name; + self + } + + /// Registers a signal gauge on this record and returns a handle to feed it. + /// + /// Values pushed via [`SignalGaugeHandle::update`](crate::SignalGaugeHandle::update) + /// fold into per-record last/min/max/mean statistics that surface on + /// `record.list` / `record.get` and stage profiling. This is the core hook + /// behind `aimdb-data-contracts`' `Observable::observe()`. + /// + /// Always available, mirroring [`with_name`](Self::with_name): when the + /// `observability` feature is disabled it returns an inert handle whose + /// `update` is a no-op, so callers never `#[cfg]` on core's features. + pub fn signal_gauge( + &mut self, + name: &'static str, + unit: &'static str, + ) -> crate::signal::SignalGaugeHandle { + #[cfg(feature = "observability")] + { + let stats = self.rec.profiling_mut().push_signal_gauge(name, unit); + crate::signal::SignalGaugeHandle::live(stats) + } + #[cfg(not(feature = "observability"))] + { + let _ = (name, unit); + crate::signal::SignalGaugeHandle::inert() + } + } + + /// Sets the data-contract schema this record carries, reported in the + /// dependency graph (`graph.nodes`) and in `record.list`. + /// + /// Only `configure` calls this, from the key's [`TypedKey::SCHEMA`](crate::TypedKey::SCHEMA): + /// the key is the one source of a record's schema (063). Setting the same + /// schema again does nothing; a different one fails `build()`. + #[cfg(test)] + pub(crate) fn schema(&mut self, name: &str, version: u32) -> &mut Self { + self.rec.set_schema(name, version); + self + } + + /// Registers a producer service for this record type. + /// + /// The closure receives the [`RuntimeContext`](crate::RuntimeContext) + /// (time + logging capabilities) and a pre-resolved [`Producer`](crate::Producer); it is + /// collected at `build()` time and driven by the `AimDbRunner`. + pub fn source(&mut self, f: F) -> &mut Self + where + F: FnOnce(crate::RuntimeContext, crate::Producer) -> Fut + Send + 'static, + Fut: Future + Send + 'static, + { + self.rec.set_producer(f); + #[cfg(feature = "observability")] + { + let (idx, _) = self.rec.profiling_mut().push_source(); + self.last_stage = Some((StageKind::Source, idx)); + } + #[cfg(not(feature = "observability"))] + { + self.last_stage = Some((StageKind::Source, 0)); + } + self + } + + /// Register a side-effect observer that taps into the data stream. + /// + /// The closure receives the [`RuntimeContext`](crate::RuntimeContext) and a + /// pre-resolved [`Consumer`]; it is collected at `build()` time and + /// driven by the `AimDbRunner`. Multiple taps per record are allowed. + pub fn tap(&mut self, f: F) -> &mut Self + where + F: FnOnce(crate::RuntimeContext, crate::Consumer) -> Fut + Send + 'static, + Fut: Future + Send + 'static, + T: Sync, + { + self.rec.add_consumer(f); + #[cfg(feature = "observability")] + { + let (idx, _) = self.rec.profiling_mut().push_tap(); + self.last_stage = Some((StageKind::Tap, idx)); + } + #[cfg(not(feature = "observability"))] + { + self.last_stage = Some((StageKind::Tap, 0)); + } + self + } + + /// Configures a buffer for this record (low-level API) + /// + /// **Note:** This is the foundational API used by runtime adapter implementations. + /// Most users should use the higher-level `buffer()` method provided by runtime + /// adapter extension traits (e.g., `TokioRecordRegistrarExt::buffer()`) which + /// accept `BufferCfg` and construct the appropriate buffer type automatically. + /// + /// This method accepts a boxed buffer trait object and is used by: + /// - Runtime adapter implementations to provide convenient wrappers + /// - Advanced use cases requiring custom buffer implementations + /// + /// **Note:** For metadata tracking in std mode, call `buffer_with_cfg()` instead, + /// or call `buffer_cfg()` separately to set the configuration. + pub fn buffer_raw( + &mut self, + buffer: Box>>, + ) -> &mut Self { + self.rec.set_buffer(buffer); + self + } + + /// Configures a buffer with metadata tracking + pub fn buffer_with_cfg( + &mut self, + buffer: Box>>, + cfg: crate::buffer::BufferCfg, + ) -> &mut Self { + self.rec.set_buffer(buffer); + self.rec.set_buffer_cfg(cfg); + self + } + + /// Sets the buffer configuration for metadata tracking + pub fn buffer_cfg(&mut self, cfg: crate::buffer::BufferCfg) -> &mut Self { + self.rec.set_buffer_cfg(cfg); + self + } + + /// Installs the JSON codec for this record (feature `remote`) + /// + /// Enables `record.latest()?.as_json()` and the AimX `record.get` / `set` / + /// `subscribe` protocol. Requires `T: RemoteSerialize` + /// (blanket-impl'd for every `Serialize + DeserializeOwned` type). Works on + /// no_std + alloc. + #[cfg(feature = "remote")] + pub fn with_remote_access(&mut self) -> &mut Self + where + T: crate::codec::RemoteSerialize + 'static, + { + self.rec.with_remote_access(); + self + } + + /// Register a single-input reactive transform. + /// + /// Conflicts with `.source()` and other `.transform()`s are recorded and + /// reported from `build()`. + /// + /// # Type Parameters + /// * `I` - The input record type to subscribe to + /// + /// # Arguments + /// * `input_key` - The record key to subscribe to as input + /// * `build_fn` - Closure that configures the transform pipeline via `TransformBuilder` + pub fn transform(&mut self, input_key: K, build_fn: F) -> &mut Self + where + K: crate::record_id::TypedKey, + F: FnOnce( + crate::transform::TransformBuilder, + ) -> crate::transform::TransformPipeline, + { + let input_key_str = input_key.as_str().to_string(); + let builder = crate::transform::TransformBuilder::::new(input_key_str); + let pipeline = build_fn(builder); + let descriptor = pipeline.into_descriptor(); + self.rec.set_transform(descriptor); + #[cfg(feature = "observability")] + { + let (idx, _) = self.rec.profiling_mut().push_transform(); + self.last_stage = Some((StageKind::Transform, idx)); + } + #[cfg(not(feature = "observability"))] + { + self.last_stage = Some((StageKind::Transform, 0)); + } + self + } + + /// Multi-input reactive transform (join). + /// + /// Derives this record from multiple input records. Available on every + /// runtime. Conflicts with `.source()` and other `.transform()`s are + /// recorded and reported from `build()`. + pub fn transform_join(&mut self, build_fn: F) -> &mut Self + where + F: FnOnce(crate::transform::JoinBuilder) -> crate::transform::JoinPipeline, + { + let builder = crate::transform::JoinBuilder::::new(); + let pipeline = build_fn(builder); + let descriptor = pipeline.into_descriptor(); + self.rec.set_transform(descriptor); + #[cfg(feature = "observability")] + { + let (idx, _) = self.rec.profiling_mut().push_transform(); + self.last_stage = Some((StageKind::Transform, idx)); + } + #[cfg(not(feature = "observability"))] + { + self.last_stage = Some((StageKind::Transform, 0)); + } + self + } + /// Builds a link using the address declared on this record's typed key. + /// A missing address is reported by `build()`. + pub fn link_to_key(&mut self) -> OutboundConnectorBuilder<'_, 'a, T, S> { + let address = self.key_link_address.clone().unwrap_or_default(); + self.link_to(&address) + } + /// Builds a link using the address declared on this record's typed key. + /// A missing address is reported by `build()`. + pub fn link_from_key(&mut self) -> InboundConnectorBuilder<'_, 'a, T, S> { + let address = self.key_link_address.clone().unwrap_or_default(); + self.link_from(&address) + } + + /// Link TO external system (outbound: AimDB → External) + /// + /// Subscribes to buffer updates and publishes them to an external system. + pub fn link_to(&mut self, url: &str) -> OutboundConnectorBuilder<'_, 'a, T, S> { + OutboundLink::new(url).attach(self) + } + + /// Link FROM external system (inbound: External → AimDB) + /// + /// Subscribes to an external data source and produces values into this record's buffer. + pub fn link_from(&mut self, url: &str) -> InboundConnectorBuilder<'_, 'a, T, S> { + InboundLink::new(url).attach(self) + } + + /// Wires `input` as a writer of this record. + /// + /// Takes anything implementing [`Input`], such as an [`InboundLink`]. + /// Conflicting writers are reported by `build()`, exactly as for + /// `.source()` and `.link_from()`; several inbound links on one record + /// are allowed (fan-in). + pub fn input(&mut self, input: impl Input) -> &mut Self { + input.wire(self); + self + } + + /// Wires `output` as a reader of this record. + /// + /// Takes anything implementing [`Output`], such as an + /// [`OutboundLink`]. A following [`with_name`](Self::with_name) names the + /// stage the output registered, as after `.link_to(..).finish()`. + pub fn output(&mut self, output: impl Output) -> &mut Self { + output.wire(self); + self + } +} + +// ============================================================================ +// Link registration - the one validation path for attached and detached links +// ============================================================================ + +/// The wire state a detached link of either direction carries into +/// registration. +pub(super) trait WireLink: Sized { + fn wire_url(&self) -> &str; + fn wire_parts( + &mut self, + ) -> ( + &mut crate::link_wire::WireOptions, + &mut Vec<(String, String)>, + ); + #[allow(clippy::type_complexity)] + fn take_wire_finalizer( + &mut self, + ) -> Option Result + Send + Sync>>; +} + +macro_rules! wire_link { + ($link:ident) => { + impl WireLink for $link { + fn wire_url(&self) -> &str { + &self.url + } + fn wire_parts( + &mut self, + ) -> ( + &mut crate::link_wire::WireOptions, + &mut Vec<(String, String)>, + ) { + (&mut self.wire, &mut self.config) + } + fn take_wire_finalizer( + &mut self, + ) -> Option Result + Send + Sync>> { + self.wire_finalizer.take() + } + } + }; +} +pub(super) use wire_link; + +impl<'a, T, S: crate::SchemaState> RecordRegistrar<'a, T, S> +where + T: Send + Sync + 'static + Debug + Clone, +{ + /// Resolves the carrier and runs the link's wire finalizer: the one path + /// for both directions. Records a config error and returns `None` if the + /// link is refused. + fn finalize_wire(&mut self, mut link: L) -> Option { + let url = link.wire_url().to_string(); + let finalized = (|| { + let (wire, config) = link.wire_parts(); + wire.take_carrier(config)?; + if let Some(finalize) = link.take_wire_finalizer() { + link = finalize(link)?; + } else if link.wire_parts().0.carrier == crate::EnvelopeCarrier::Inline { + return Err( + "inline envelopes require with_envelope or with_versioned_codec".into(), + ); + } + let (wire, config) = link.wire_parts(); + wire.record_carrier(config); + Ok::(link) + })(); + match finalized { + Ok(link) => Some(link), + Err(message) => { + self.rec.push_config_error(crate::ConfigError::new( + self.record_key.clone(), + Some(url), + message, + )); + None + } + } + } + + /// Validates and registers an outbound link, or records why not. + pub(super) fn push_outbound(&mut self, link: OutboundLink) { + let Some(mut link) = self.finalize_wire(link) else { + return; + }; + + use crate::connector::{ConnectorLink, LinkAddress}; + use crate::error::ConfigError; + + let record_key = self.record_key.clone(); + + if let Some(handle) = link.connector { + match crate::connector::resolve_link_url( + self.builder_id, + self.connector_builders, + handle, + &link.url, + ) { + Ok(url) => link.url = url, + Err(message) => { + self.rec.push_config_error(ConfigError::new( + record_key, + Some(link.url), + message, + )); + return; + } + } + } + + let Ok(url) = LinkAddress::parse(&link.url) else { + self.rec.push_config_error(ConfigError::new( + record_key, + Some(link.url), + "Invalid connector URL", + )); + return; + }; + + let url_string = url.to_string(); + let scheme = url.scheme().to_string(); + + if url.resource_id().contains(['{', '}']) { + self.rec.push_config_error(ConfigError::new( + record_key, + Some(link.url), + "Outbound topics cannot contain '{' or '}'", + )); + return; + } + + // Adapt the stored serializer to the fused calling convention. Stays + // typed: fused with the consumer below, no `Box` per message + //. + let serialize: FusedSerializeFn = if let Some(ser) = link.context_serializer { + Arc::new(move |ctx: &crate::RuntimeContext, value: &T| ser(ctx.clone(), value)) + } else { + self.rec.push_config_error(ConfigError::new( + record_key, + Some(link.url), + "Outbound connector requires a serializer. Call .with_serializer()", + )); + return; + }; + + let serialize_into: Option<(usize, FusedSerializeIntoFn)> = + link.context_serializer_into.map(|(capacity, ser)| { + let adapted: FusedSerializeIntoFn = Arc::new( + move |ctx: &crate::RuntimeContext, value: &T, out: &mut [u8]| { + ser(ctx.clone(), value, out) + }, + ); + (capacity, adapted) + }); + + // Validation: Check that connector builder is registered + let has_connector = self.connector_builders.iter().any(|b| b.scheme() == scheme); + + if !has_connector { + self.rec.push_config_error(ConfigError::new( + record_key, + Some(url_string), + alloc::format!( + "No connector registered for scheme '{scheme}'. Register via .with_connector()" + ), + )); + return; + } + + // Register the link as a profiling stage (so `.with_name()` can name it + // and the consumer it creates can be timed). + #[cfg(feature = "observability")] + let link_metrics = { + let (idx, metrics) = self.rec.profiling_mut().push_link(); + self.last_stage = Some((StageKind::Link, idx)); + metrics + }; + #[cfg(not(feature = "observability"))] + { + self.last_stage = Some((StageKind::Link, 0)); + } + + // Resolves the record and builds a `Consumer` bound to its buffer + // handle, once per route (not per message) — same pattern as the + // build-time path in `TypedRecord::collect_consumer_futures`. + // + // The factories run during build() after every record is registered + // and validated (including the linked-records-need-a-buffer check), + // so failures here are aimdb bugs, not user mistakes. + #[allow( + clippy::panic, + reason = "the factory returns no Result and these lookups were validated at build() time" + )] + let make_consumer: ConsumerFactoryFn = { + let record_key = self.record_key.clone(); + Arc::new(move |db: &AimDb| { + let typed_rec = db + .inner() + .get_typed_record_by_key_raw::(&record_key) + .unwrap_or_else(|e| { + panic!( + "outbound link: record '{record_key}' lookup failed ({e:?}) — \ + this is a bug in aimdb-core" + ) + }); + let buffer = typed_rec.buffer_handle().unwrap_or_else(|| { + panic!( + "outbound link: record '{record_key}' has no buffer despite \ + build()-time validation — this is a bug in aimdb-core" + ) + }); + + #[allow(unused_mut)] + let mut consumer = Consumer::::new(buffer); + #[cfg(feature = "observability")] + consumer.set_profiling(link_metrics.clone(), db.profiling_clock().clone()); + consumer + }) + }; + + let topic_writer = link.topic_writer; + let has_topic_writer = topic_writer.is_some(); + + // Renders the record's current value through this link's topic writer + // and serializer, for late-join snapshots (`OutboundLatest`). + let latest_fn: crate::outbound::LatestFn = { + let record_key = self.record_key.clone(); + let topic_writer = topic_writer.clone(); + let serialize = serialize.clone(); + let serialize_into = serialize_into.clone(); + Arc::new( + move |db: &AimDb, + ctx: &crate::RuntimeContext, + accept: &dyn Fn(Option<&str>) -> bool| { + let sample = db + .inner() + .get_typed_record_by_key_raw::(&record_key) + .ok()? + .latest()? + .into_stamped(); + + let topic = match &topic_writer { + None => None, + Some((capacity, writer)) => { + let mut buf = alloc::vec![0u8; *capacity]; + let mut out = crate::connector::TopicBuf::new(&mut buf); + let written = write_topic(&**writer, &sample.value, &mut out).ok()?; + let len = out.len(); + // `TopicBuf` only ever holds whole `&str`s. + written + .then(|| String::from_utf8(buf[..len].to_vec()).ok()) + .flatten() + } + }; + // Serialize only for a topic the caller wants. + if !accept(topic.as_deref()) { + return None; + } + + let mut scratch = alloc::vec![0u8; serialize_into.as_ref().map_or(0, |(capacity, _)| *capacity)]; + let payload = match serialize_outbound( + &serialize, + serialize_into.as_ref().map(|(_, f)| f), + ctx, + &sample.value, + &mut scratch, + ) + .ok()? + { + crate::outbound::StagedPayload::Scratch(len) => scratch[..len].to_vec(), + crate::outbound::StagedPayload::Owned(bytes) => bytes, + }; + + Some(crate::outbound::Rendered { + topic, + payload, + metadata: *sample.metadata(), + }) + }, + ) + }; + + // Subscribed when `OutboundRoutes` is built. + let route_factory: crate::outbound::RouteFactoryFn = { + Arc::new(move |db: &AimDb| { + let (topic_capacity, writer) = match &topic_writer { + Some((capacity, writer)) => (*capacity, Some(writer.clone())), + None => (0, None), + }; + crate::outbound::RouteParts { + route: Box::new(TypedRoute { + reader: make_consumer(db).subscribe(), + writer, + serialize: serialize.clone(), + serialize_into: serialize_into.as_ref().map(|(_, f)| f.clone()), + }), + topic_capacity, + payload_capacity: serialize_into.as_ref().map_or(0, |(capacity, _)| *capacity), + } + }) + }; + + // Named `out`, not `link`: `out.config = link.config` must read the + // user's link, not the new one. + let mut out = ConnectorLink::new(url, route_factory, latest_fn, has_topic_writer); + out.config = link.config; + + // Routes are built later, when a connector builds its `OutboundRoutes`. + self.rec.add_outbound_connector(out); + } + + /// Validates and registers an inbound link, or records why not. + pub(super) fn push_inbound(&mut self, link: InboundLink) { + let Some(mut link) = self.finalize_wire(link) else { + return; + }; + + match self.inbound_link(&mut link) { + Ok(inbound) => self.rec.add_inbound_connector(inbound), + Err(message) => { + let key = self.record_key.clone(); + let error = crate::error::ConfigError::new(key, Some(link.url), message); + self.rec.push_config_error(error); + } + } + } + + /// The link `push_inbound()` registers, or why it is rejected. + /// + /// The buffer requirement and mutual exclusion with local producers + /// (.source()/.transform()) are validated by `build()`: `.buffer()` may + /// legitimately be called after `.link_from()`. + fn inbound_link( + &self, + link: &mut InboundLink, + ) -> Result { + use crate::connector::{InboundConnectorLink, LinkAddress}; + + if let Some(handle) = link.connector { + link.url = crate::connector::resolve_link_url( + self.builder_id, + self.connector_builders, + handle, + &link.url, + )?; + } + let url = LinkAddress::parse(&link.url).map_err(|_| "Invalid connector URL")?; + let record_key = self.record_key.clone(); + + let deser: TypedMatchDeserializerFn = match ( + link.context_deserializer.take(), + link.match_deserializer.take(), + ) { + (Some(deser), None) => Arc::new(move |ctx, _m, bytes| deser(ctx.clone(), bytes)), + (None, Some(deser)) => deser, + (Some(_), Some(_)) => { + return Err( + "Set either .with_deserializer() or .with_match_deserializer(), not both" + .into(), + ) + } + (None, None) => { + return Err("Inbound connector requires a deserializer. Call \ + .with_deserializer() or .with_match_deserializer()" + .into()) + } + }; + + // The `{…}` syntax; the connector checks the rest. + let pattern = crate::TopicPattern::parse(url.resource_id()).map_err(|e| e.to_string())?; + + let key = match link.key.take() { + None => None, + Some((capture, capacity)) => { + let Some(capacity) = core::num::NonZeroU16::new(capacity) else { + return Err(alloc::format!( + "key '{capture}' needs a capacity of at least 1" + )); + }; + if !pattern.capture_names().any(|n| n == capture) { + return Err(alloc::format!( + "key '{capture}' is not a capture of the topic" + )); + } + let links = self.rec.inbound_connectors(); + if let Some((_, other)) = links.iter().find_map(|l| l.key.as_ref()) { + if *other != capacity { + return Err(alloc::format!( + "key '{capture}' has capacity {capacity}, another keyed link of \ + this record has {other}" + )); + } + } + Some((capture, capacity)) + } + }; + + let scheme = url.scheme(); + if !self.connector_builders.iter().any(|b| b.scheme() == scheme) { + return Err(alloc::format!( + "No connector registered for scheme '{scheme}'. Register via .with_connector()" + )); + } + + // Named `inbound`, not `link`, for the same reason as in `push_outbound`. + let mut inbound = InboundConnectorLink::new(url, ingest_factory(record_key, deser)) + .with_upgrade_versions(&link.upgrade_versions); + inbound.config = core::mem::take(&mut link.config); + inbound.key = key; + inbound.topic_resolver = link.topic_resolver.take(); + Ok(inbound) + } +} diff --git a/aimdb-core/src/typed_api/tests/build.rs b/aimdb-core/src/typed_api/tests/build.rs new file mode 100644 index 00000000..0b5accd4 --- /dev/null +++ b/aimdb-core/src/typed_api/tests/build.rs @@ -0,0 +1,335 @@ +//! Whole-builder checks through `AimDbBuilder::build()`: cross-stage and +//! cross-connector validation, graph and schema reporting. + +use super::*; + +/// The target shape from #390, through `build()`: links on a handle +/// build; the same links on another builder's handle fail it. +#[tokio::test] +async fn handle_links_build_and_foreign_handles_fail_it() { + let mut other = crate::AimDbBuilder::new(); + let foreign = other.connect(NoopConnectorBuilder); + + for (use_foreign, expect_ok) in [(false, true), (true, false)] { + let key_temp_indoor_1 = crate::Name::::new("temp.indoor"); + let mut builder = crate::AimDbBuilder::new().runtime(Arc::new(MockRuntime)); + let mqtt = builder.connect(NoopConnectorBuilder); + let on = if use_foreign { foreign } else { mqtt }; + builder.configure(key_temp_indoor_1, move |reg| { + reg.buffer_raw(Box::new(MockBuffer)) + .input(InboundLink::on(on, "commands/temp/indoor").with_deserializer(de)) + .output(OutboundLink::on(on, "sensors/temp/indoor").with_serializer(ser)); + }); + let result = builder.build().await; + if expect_ok { + let (db, _runner) = result.expect("handle links build"); + let inbound = crate::InboundDispatch::new(&db, "mqtt", &Plus).expect("routes compile"); + assert_eq!(inbound.subscriptions()[0].as_ref(), "commands/temp/indoor"); + } else { + let errors = config_errors(result); + assert_eq!(errors.len(), 2, "got: {errors:?}"); + assert!(errors.iter().all(|e| e.record_key == "temp.indoor" + && e.message == "Connector handle belongs to a different AimDbBuilder")); + } + } +} + +/// A connector registered with `connect` serves links exactly like one +/// registered with `with_connector`. +#[tokio::test] +async fn connected_connector_serves_links() { + let key_rec_in_2 = crate::Name::::new("rec.in"); + let mut builder = crate::AimDbBuilder::new().runtime(Arc::new(MockRuntime)); + let _mqtt = builder.connect(NoopConnectorBuilder); + builder.configure(key_rec_in_2, |reg| { + reg.buffer_raw(Box::new(MockBuffer)) + .input(InboundLink::new("mqtt://a").with_deserializer(de)); + }); + let (db, _runner) = builder.build().await.expect("builds"); + let inbound = crate::InboundDispatch::new(&db, "mqtt", &Plus).expect("routes compile"); + assert_eq!(inbound.route_count(), 1); +} + +/// Two inbound links on one record are fan-in, through `.input()` as +/// through `.link_from()`. +#[tokio::test] +async fn two_inbound_inputs_fan_in() { + let key_rec_in_3 = crate::Name::::new("rec.in"); + let mut builder = crate::AimDbBuilder::new() + .runtime(Arc::new(MockRuntime)) + .with_connector(NoopConnectorBuilder); + builder.configure(key_rec_in_3, |reg| { + reg.buffer_raw(Box::new(MockBuffer)) + .input(InboundLink::new("mqtt://a").with_deserializer(de)) + .input(InboundLink::new("mqtt://b").with_deserializer(de)); + }); + let (db, _runner) = builder.build().await.expect("fan-in builds"); + let inbound = crate::InboundDispatch::new(&db, "mqtt", &Plus).expect("routes compile"); + assert_eq!(inbound.route_count(), 2); +} + +#[tokio::test] +async fn input_source_and_link_conflict() { + let key_rec_in_4 = crate::Name::::new("rec.in"); + let mut builder = crate::AimDbBuilder::new() + .runtime(Arc::new(MockRuntime)) + .with_connector(NoopConnectorBuilder); + builder.configure(key_rec_in_4, |reg| { + reg.buffer_raw(Box::new(MockBuffer)) + .input(Counter) + .input(InboundLink::new("mqtt://a").with_deserializer(de)); + }); + let errors = config_errors(builder.build().await); + assert_eq!(errors.len(), 1, "got: {errors:?}"); + assert_eq!(errors[0].record_key, "rec.in"); + assert!( + errors[0] + .message + .contains("conflicting writers: record has source + inbound link"), + "got: {}", + errors[0].message + ); +} + +// ==================================================================== +// build()-level validation tests +// ==================================================================== + +#[derive(Debug, Clone)] +struct OtherRecord; + +/// A connector that claims every route for its scheme, as KNX and the +/// session *clients* do. +struct OwningConnectorBuilder(&'static str); + +impl crate::connector::ConnectorBuilder for OwningConnectorBuilder { + fn build<'a>( + &'a self, + _db: &'a crate::AimDb, + ) -> Pin< + Box< + dyn Future + Send + 'static>>>>> + + Send + + 'a, + >, + > { + Box::pin(async { Ok(Vec::new()) }) + } + fn scheme(&self) -> &str { + self.0 + } + fn owns_scheme(&self) -> bool { + true + } +} + +/// Two scheme-owning connectors under one scheme is a configuration error, +/// not a silently duplicated route set. +#[tokio::test] +async fn two_owning_connectors_on_one_scheme_fail_the_build() { + let builder = crate::AimDbBuilder::new() + .runtime(Arc::new(MockRuntime)) + .with_connector(OwningConnectorBuilder("knx")) + .with_connector(OwningConnectorBuilder("knx")); + + let Err(err) = builder.build().await else { + panic!("a second connector for an owned scheme must be rejected"); + }; + let msg = alloc::format!("{err}"); + assert!( + msg.contains("More than one connector registered for scheme 'knx'"), + "unexpected error: {msg}" + ); +} + +/// Distinct schemes are fine — that is how a caller runs two of the same +/// transport side by side. +#[tokio::test] +async fn owning_connectors_on_distinct_schemes_build() { + let builder = crate::AimDbBuilder::new() + .runtime(Arc::new(MockRuntime)) + .with_connector(OwningConnectorBuilder("knx")) + .with_connector(OwningConnectorBuilder("mqtt")); + + assert!(builder.build().await.is_ok()); +} + +/// A connector that collects no routes — a session *server*, say — may be +/// registered twice under one scheme: two endpoints onto one dispatch. +/// `owns_scheme` defaults to `false`, so this must keep working. +#[tokio::test] +async fn two_non_owning_connectors_on_one_scheme_build() { + let builder = crate::AimDbBuilder::new() + .runtime(Arc::new(MockRuntime)) + .with_connector(NoopConnectorBuilder) + .with_connector(NoopConnectorBuilder); + + assert!(builder.build().await.is_ok()); +} + +/// Acceptance criterion: a builder with three distinct +/// mistakes reports all three from one `build()` call. +#[tokio::test] +async fn build_reports_all_configuration_mistakes_at_once() { + let key_rec_a_5 = crate::Name::::new("rec.a"); + let key_rec_b_6 = crate::Name::::new("rec.b"); + let key_rec_c_7 = crate::Name::::new("rec.c"); + let key_rec_c_8 = crate::Name::::new("rec.c"); + let mut builder = crate::AimDbBuilder::new().runtime(Arc::new(MockRuntime)); + + // Mistake 1: outbound link with no serializer + builder.configure(key_rec_a_5, |reg| { + reg.link_to("mqtt://broker/a").finish(); + }); + // Mistake 2: two .source() registrations on one record + builder.configure(key_rec_b_6, |reg| { + reg.source(|_ctx, _p| async move {}); + reg.source(|_ctx, _p| async move {}); + }); + // Mistake 3: key re-registered with a different type + builder.configure(key_rec_c_7, |_reg| {}); + builder.configure(key_rec_c_8, |_reg| {}); + + let Err(err) = builder.build().await else { + panic!("build must fail"); + }; + let crate::DbError::InvalidConfiguration { errors } = err else { + panic!("expected InvalidConfiguration, got {err:?}"); + }; + assert_eq!(errors.len(), 3, "expected 3 errors, got: {errors:?}"); + assert!(errors.iter().any(|e| e.record_key == "rec.a" + && e.url.as_deref() == Some("mqtt://broker/a") + && e.message.contains("requires a serializer"))); + assert!(errors + .iter() + .any(|e| e.record_key == "rec.b" && e.message.contains("already has a producer service"))); + assert!(errors + .iter() + .any(|e| e.record_key == "rec.c" && e.message.contains("different type"))); +} + +/// `.buffer()` after `.link_from()` is legitimate now that the buffer +/// requirement is validated by `build()` instead of `finish()`. +#[tokio::test] +async fn buffer_after_link_from_is_valid() { + let key_rec_x_9 = crate::Name::::new("rec.x"); + let mut builder = crate::AimDbBuilder::new() + .runtime(Arc::new(MockRuntime)) + .with_connector(NoopConnectorBuilder); + + builder.configure(key_rec_x_9, |reg| { + reg.link_from("mqtt://broker/x") + .with_deserializer(|_ctx, _b: &[u8]| Ok(TestRecord { value: 0 })) + .finish(); + // Buffer configured AFTER the link — order-independent. + reg.buffer_raw(Box::new(MockBuffer)); + }); + + builder.build().await.expect("build must succeed"); +} + +/// A linked record without a buffer fails at build() — previously this +/// panicked at spawn time, deep inside a connector factory closure. +#[tokio::test] +async fn linked_record_without_buffer_fails_build() { + let key_rec_x_10 = crate::Name::::new("rec.x"); + let mut builder = crate::AimDbBuilder::new() + .runtime(Arc::new(MockRuntime)) + .with_connector(NoopConnectorBuilder); + + builder.configure(key_rec_x_10, |reg| { + reg.link_from("mqtt://broker/x") + .with_deserializer(|_ctx, _b: &[u8]| Ok(TestRecord { value: 0 })) + .finish(); + }); + + let Err(err) = builder.build().await else { + panic!("build must fail"); + }; + let crate::DbError::InvalidConfiguration { errors } = err else { + panic!("expected InvalidConfiguration, got {err:?}"); + }; + assert_eq!(errors.len(), 1); + assert!(errors[0].message.contains("requires a buffer")); + assert_eq!(errors[0].record_key, "rec.x"); + assert_eq!(errors[0].url.as_deref(), Some("mqtt://broker/x")); +} + +/// #332: a record's schema and its outbound link addresses reach the +/// graph node and `record.list`. +#[tokio::test] +async fn graph_node_carries_schema_and_outbound_links() { + let key_rec_out_14 = crate::Name::::new("rec.out"); + let key_rec_plain_15 = crate::Name::::new("rec.plain"); + let mut builder = crate::AimDbBuilder::new() + .runtime(Arc::new(MockRuntime)) + .with_connector(NoopConnectorBuilder); + builder.configure(key_rec_out_14, |reg| { + reg.buffer_raw(Box::new(MockBuffer)); + reg.schema("flow", 2).schema("flow", 2); + reg.link_to("mqtt://plant/boiler/flow_avg") + .with_serializer(le) + .finish(); + reg.link_to("mqtt://plant/boiler/flow_raw") + .with_serializer(le) + .finish(); + }); + builder.configure(key_rec_plain_15, |_reg| {}); + let (db, _runner) = builder.build().await.expect("build must succeed"); + + let graph = db.inner().dependency_graph(); + let out = graph.node("rec.out").unwrap(); + assert_eq!( + out.schema, + Some(crate::graph::SchemaInfo { + name: "flow".to_string(), + version: 2 + }) + ); + assert_eq!( + out.outbound_links, + [ + "mqtt://plant/boiler/flow_avg", + "mqtt://plant/boiler/flow_raw" + ] + ); + assert!(out.has_outbound_link); + let plain = graph.node("rec.plain").unwrap(); + assert_eq!( + (plain.schema.as_ref(), plain.has_outbound_link), + (None, false) + ); + assert!(plain.outbound_links.is_empty()); + + #[cfg(feature = "remote")] + { + let records = db.list_records(); + let out = records.iter().find(|r| r.record_key == "rec.out").unwrap(); + assert_eq!(out.schema_type.as_deref(), Some("flow")); + assert_eq!(out.schema_version, Some(2)); + let plain = records + .iter() + .find(|r| r.record_key == "rec.plain") + .unwrap(); + assert_eq!( + (plain.schema_type.as_deref(), plain.schema_version), + (None, None) + ); + } +} + +/// #332: two different schemas on one record fail `build()`. +#[tokio::test] +async fn conflicting_schemas_fail_build() { + let key_rec_x_16 = crate::Name::::new("rec.x"); + let mut builder = crate::AimDbBuilder::new().runtime(Arc::new(MockRuntime)); + builder.configure(key_rec_x_16, |reg| { + reg.schema("flow", 1).schema("flow", 2); + }); + let Err(crate::DbError::InvalidConfiguration { errors }) = builder.build().await else { + panic!("build must fail"); + }; + assert_eq!(errors.len(), 1, "{errors:?}"); + assert_eq!(errors[0].record_key, "rec.x"); + assert!(errors[0].message.contains("flow v1"), "{errors:?}"); +} diff --git a/aimdb-core/src/typed_api/tests/link_inbound.rs b/aimdb-core/src/typed_api/tests/link_inbound.rs new file mode 100644 index 00000000..fa53b7e3 --- /dev/null +++ b/aimdb-core/src/typed_api/tests/link_inbound.rs @@ -0,0 +1,443 @@ +//! `InboundLinkBuilder`: registration (`finish`) and the ingest path +//! (`InboundDispatch`, stamping, admission counters). + +use super::*; + +// ==================================================================== +// Inbound link registration tests (fused ingest) +// ==================================================================== + +#[test] +fn inbound_finish_registers_fused_link() { + let mut rec = crate::typed_record::TypedRecord::::new(); + rec.set_buffer(Box::new(MockBuffer)); + + let builders: Vec> = + vec![Box::new(MockConnectorBuilder { + scheme: "mqtt".to_string(), + })]; + let extensions = crate::extensions::Extensions::new(); + + let mut reg = make_registrar(&mut rec, &builders, &extensions); + + reg.link_from("mqtt://broker/topic") + .with_deserializer(|_ctx, bytes: &[u8]| { + Ok(TestRecord { + value: bytes.len() as i32, + }) + }) + .finish(); + + assert_eq!(rec.inbound_connectors().len(), 1); + assert_eq!(rec.inbound_connectors()[0].resolve_topic(), "broker/topic"); + assert!(drain_errors(&mut rec).is_empty()); +} + +#[test] +fn inbound_finish_without_deserializer_records_error() { + let mut rec = crate::typed_record::TypedRecord::::new(); + rec.set_buffer(Box::new(MockBuffer)); + + let builders: Vec> = + vec![Box::new(MockConnectorBuilder { + scheme: "mqtt".to_string(), + })]; + let extensions = crate::extensions::Extensions::new(); + + let mut reg = make_registrar(&mut rec, &builders, &extensions); + + // No deserializer set — error recorded, link not registered + reg.link_from("mqtt://broker/topic").finish(); + + assert!(rec.inbound_connectors().is_empty()); + let errors = drain_errors(&mut rec); + assert_eq!(errors.len(), 1); + assert!(errors[0] + .message + .contains("Inbound connector requires a deserializer")); + assert_eq!(errors[0].record_key, "test::Record"); + assert_eq!(errors[0].url.as_deref(), Some("mqtt://broker/topic")); +} + +// ==================================================================== +// Topic patterns and keys on inbound links +// ==================================================================== + +/// Runs `configure` against a fresh registrar with an `mqtt` connector +/// and returns the record's links and recorded errors. +fn register( + configure: impl FnOnce(&mut RecordRegistrar<'_, TestRecord>), +) -> ( + Vec, + Vec, +) { + let mut rec = crate::typed_record::TypedRecord::::new(); + rec.set_buffer(Box::new(MockBuffer)); + let builders: Vec> = + vec![Box::new(MockConnectorBuilder { + scheme: "mqtt".to_string(), + })]; + let extensions = crate::extensions::Extensions::new(); + configure(&mut make_registrar(&mut rec, &builders, &extensions)); + (rec.inbound_connectors().to_vec(), drain_errors(&mut rec)) +} + +fn match_deser( + _ctx: &crate::RuntimeContext, + m: &crate::TopicMatch<'_>, + _bytes: &[u8], +) -> Result { + Ok(TestRecord { + value: m.topic().len() as i32, + }) +} + +#[test] +fn inbound_finish_registers_match_link_with_key() { + let (links, errors) = register(|reg| { + reg.link_from("mqtt://s/{device}/t") + .key("device", 16) + .with_match_deserializer(match_deser) + .finish(); + }); + assert!(errors.is_empty(), "{errors:?}"); + let (capture, capacity) = links[0].key.clone().unwrap(); + assert_eq!((capture.as_str(), capacity.get()), ("device", 16)); +} + +#[test] +fn inbound_finish_rejects_both_deserializers() { + let (links, errors) = register(|reg| { + reg.link_from("mqtt://s/{device}/t") + .with_deserializer(|_ctx, _bytes: &[u8]| Ok(TestRecord { value: 0 })) + .with_match_deserializer(match_deser) + .finish(); + }); + assert!(links.is_empty()); + assert!(errors[0].message.contains("not both"), "{:?}", errors[0]); +} + +#[test] +fn inbound_finish_rejects_invalid_pattern_syntax() { + for topic in [ + "s/{d", + "s/{}", + "s/{d-1}", + "{d}/{d}", + "{a}/{b}/{c}/{d}/{e}/{f}/{g}/{h}/{i}", + ] { + let url = alloc::format!("mqtt://{topic}"); + let (links, errors) = register(|reg| { + reg.link_from(&url) + .with_deserializer(|_ctx, _bytes: &[u8]| Ok(TestRecord { value: 0 })) + .finish(); + }); + assert!(links.is_empty(), "{topic}"); + assert_eq!(errors.len(), 1, "{topic}"); + assert_eq!(errors[0].record_key, "test::Record"); + assert_eq!(errors[0].url.as_deref(), Some(url.as_str())); + } +} + +#[test] +fn inbound_finish_rejects_bad_keys() { + for (topic, key, capacity, needle) in [ + ("s/{d}/t", "device", 4, "not a capture"), + ("s/{d}/t", "d", 0, "at least 1"), + ] { + let (links, errors) = register(|reg| { + reg.link_from(&alloc::format!("mqtt://{topic}")) + .key(key, capacity) + .with_match_deserializer(match_deser) + .finish(); + }); + assert!(links.is_empty()); + assert!(errors[0].message.contains(needle), "{:?}", errors[0]); + } +} + +#[test] +fn keyed_links_of_one_record_share_a_capacity() { + let (links, errors) = register(|reg| { + reg.link_from("mqtt://temp/{d}") + .key("d", 8) + .with_match_deserializer(match_deser) + .finish(); + reg.link_from("mqtt://hum/{id}") + .key("id", 8) + .with_match_deserializer(match_deser) + .finish(); + reg.link_from("mqtt://co2/{id}") + .key("id", 16) + .with_match_deserializer(match_deser) + .finish(); + }); + assert_eq!(links.len(), 2); + assert_eq!(errors.len(), 1); + assert!(errors[0].message.contains("has 8"), "{:?}", errors[0]); +} + +/// Dispatches `payload` on `topic` through the `mqtt` inbound routes. +fn route(db: &crate::AimDb, topic: &str, payload: &[u8]) { + crate::InboundDispatch::new(db, "mqtt", &Plus) + .expect("routes compile") + .dispatch(topic, payload); +} + +/// End-to-end inbound path: bytes → fused ingest → typed buffer push, +/// with no `Box` in between. +#[tokio::test] +async fn ingest_roundtrip_produces_value() { + let (db, last, count) = inbound_db(|reg| { + reg.link_from("mqtt://cmd/in") + .with_deserializer(|_ctx, bytes: &[u8]| { + if bytes.is_empty() { + return Err("empty payload".into()); + } + Ok(TestRecord { + value: bytes.len() as i32, + }) + }) + .finish(); + }) + .await; + + route(&db, "cmd/in", &[1, 2, 3]); + assert_eq!(count.load(Ordering::SeqCst), 1); + assert_eq!(last.load(Ordering::SeqCst), 3); + + // Bad bytes: the deserializer fails, nothing is produced. + route(&db, "cmd/in", &[]); + assert_eq!(count.load(Ordering::SeqCst), 1); +} + +/// The deserializer set last wins, whichever way its context is typed. +#[tokio::test] +async fn deserializer_set_last_wins() { + let (db, last, _) = inbound_db(|reg| { + reg.link_from("mqtt://cmd/in") + .with_deserializer(|_ctx, _bytes: &[u8]| Ok(TestRecord { value: 0 })) + .with_deserializer(|_ctx: crate::RuntimeContext, _bytes: &[u8]| { + Ok(TestRecord { value: 99 }) + }) + .finish(); + }) + .await; + route(&db, "cmd/in", b"x"); + assert_eq!(last.load(Ordering::SeqCst), 99); +} + +/// Buffer that records the stamp of the last pushed value. +struct StampRecordingBuffer(Arc); + +impl crate::buffer::DynBuffer> for StampRecordingBuffer { + fn push(&self, sample: crate::Stamped) { + self.0.store(sample.stamp().as_nanos(), Ordering::SeqCst); + } + fn subscribe_boxed( + &self, + ) -> Box> + Send> { + unimplemented!("not needed for ingest tests") + } + fn as_any(&self) -> &dyn core::any::Any { + self + } +} + +/// Design 058 §1: an inbound value is stamped when it is written locally. +#[tokio::test] +async fn an_inbound_value_is_stamped_when_written() { + let key_rec_in_12 = crate::Name::::new("rec.in"); + let ops = crate::executor::test_support::ManualClockRuntimeOps::default(); + let stamp = Arc::new(core::sync::atomic::AtomicU64::new(u64::MAX)); + let buf_stamp = stamp.clone(); + let mut builder = crate::AimDbBuilder::new() + .runtime(Arc::new(ops.clone())) + .with_connector(NoopConnectorBuilder); + builder.configure(key_rec_in_12, move |reg| { + reg.buffer_raw(Box::new(StampRecordingBuffer(buf_stamp))); + reg.link_from("mqtt://cmd/in") + .with_deserializer(|_ctx, bytes: &[u8]| { + Ok::<_, crate::IngestError>(TestRecord { + value: bytes.len() as i32, + }) + }) + .finish(); + }); + let (db, _runner) = builder.build().await.expect("build must succeed"); + + ops.clock.advance(core::time::Duration::from_nanos(4242)); + route(&db, "cmd/in", &[1]); + assert_eq!(stamp.load(Ordering::SeqCst), 4242); +} + +#[tokio::test] +async fn inbound_dispatch_routes_patterns_with_shared_keys() { + let keys: Arc>> = Default::default(); + let seen = keys.clone(); + let (db, last, count) = inbound_db(move |reg| { + reg.link_from("mqtt://temp/{d}") + .key("d", 2) + .with_match_deserializer(move |ctx, m, bytes| { + seen.lock().extend(m.key()); + key_deser(ctx, m, bytes) + }) + .finish(); + reg.link_from("mqtt://hum/{id}") + .key("id", 2) + .with_match_deserializer(key_deser) + .finish(); + reg.link_from("mqtt://cmd/in") + .with_deserializer(|_ctx, _bytes: &[u8]| Ok(TestRecord { value: 100 })) + .finish(); + }) + .await; + + let inbound = crate::InboundDispatch::new(&db, "mqtt", &Plus).expect("routes compile"); + let subscriptions: Vec = inbound + .subscriptions() + .iter() + .map(|s| s.to_string()) + .collect(); + assert_eq!(subscriptions, ["cmd/in", "hum/+", "temp/+"]); + assert_eq!(inbound.route_count(), 3); + + let dispatch = |topic: &str| { + inbound.dispatch(topic, b""); + last.load(Ordering::SeqCst) + }; + assert_eq!(dispatch("temp/a"), 0); + assert_eq!(dispatch("hum/b"), 1); + assert_eq!(dispatch("hum/a"), 0, "one key table per record"); + assert_eq!(dispatch("cmd/in"), 100); + let produced = count.load(Ordering::SeqCst); + dispatch("temp/c"); + assert_eq!(count.load(Ordering::SeqCst), produced, "full table drops"); + + let a = keys.lock()[0]; + assert_eq!(db.inbound_key_name("rec.in", a).as_deref(), Some("a")); + assert_eq!(db.inbound_key_name("other", a), None); + + #[cfg(feature = "remote")] + { + let records = db.list_records(); + let info = records[0].inbound_keys.as_ref().expect("keyed record"); + assert_eq!(info.captures, ["d", "id"]); + assert_eq!((info.capacity, info.assigned, info.dropped), (2, 2, 1)); + } +} + +#[tokio::test] +async fn inbound_dispatch_rejects_links_it_cannot_compile() { + let (db, _, _) = inbound_db(|reg| { + reg.link_from("mqtt://s/{d}/t") + .with_deserializer(|_ctx, _bytes: &[u8]| Ok(TestRecord { value: 0 })) + .finish(); + reg.link_from("mqtt://r/one") + .with_topic_resolver(|| Some("r/{d".into())) + .with_deserializer(|_ctx, _bytes: &[u8]| Ok(TestRecord { value: 0 })) + .finish(); + reg.link_from("mqtt://k/{d}") + .key("d", 4) + .with_topic_resolver(|| Some("k/{x}".into())) + .with_match_deserializer(key_deser) + .finish(); + }) + .await; + + let errors = config_errors(crate::InboundDispatch::new(&db, "mqtt", &Plus)); + assert_eq!(errors.len(), 2, "{errors:?}"); + assert!(errors.iter().all(|e| e.record_key == "rec.in")); + assert!(errors[0].message.contains("unbalanced '{' in 'r/{d'")); + assert!(errors[1] + .message + .contains("key 'd' is not a capture of 'k/{x}'")); + + let errors = config_errors(crate::InboundDispatch::new( + &db, + "mqtt", + &crate::ExactGrammar, + )); + assert_eq!(errors.len(), 3, "{errors:?}"); + assert!(errors[0] + .message + .contains("does not support topic patterns")); +} + +#[tokio::test] +async fn inbound_dispatch_clones_share_records() { + fn assert_send_sync() {} + assert_send_sync::(); + + let (db, last, count) = inbound_db(|reg| { + reg.link_from("mqtt://cmd/in") + .with_deserializer(|_ctx, bytes: &[u8]| { + Ok(TestRecord { + value: bytes.len() as i32, + }) + }) + .finish(); + }) + .await; + + let inbound = crate::InboundDispatch::new(&db, "mqtt", &Plus).unwrap(); + let clone = inbound.clone(); + drop(inbound); + clone.dispatch("cmd/in", b"abcd"); + assert_eq!(count.load(Ordering::SeqCst), 1); + assert_eq!(last.load(Ordering::SeqCst), 4); +} + +#[tokio::test] +async fn admission_outcomes_are_counted_after_production_and_survive_reconnect() { + let (db, last, count) = inbound_db(|reg| { + reg.link_from("mqtt://cmd/in") + .with_admitting_deserializer(&[1], |_ctx, _m, bytes| { + if bytes.is_empty() { + return Err(crate::IngestError::new( + crate::Rejection::TooOld, + "received v0, accepts v1..=2", + )); + } + Ok(crate::IngestValue::upgraded(TestRecord { value: 42 }, 1)) + }) + .finish(); + }) + .await; + let inbound = crate::InboundDispatch::new(&db, "mqtt", &Plus).unwrap(); + let clone = inbound.clone(); + assert_eq!(inbound.routes()[0].id, 0); + clone.dispatch("cmd/in", b"v1"); + assert_eq!(last.load(Ordering::SeqCst), 42); + assert_eq!(count.load(Ordering::SeqCst), 1); + inbound.dispatch("cmd/in", b""); + assert_eq!(count.load(Ordering::SeqCst), 1); + let snapshot = clone.stats(0).unwrap(); + assert_eq!(snapshot.accepted, 1); + assert_eq!(snapshot.too_old, 1); + assert_eq!( + snapshot.upgraded[0], + crate::UpgradeCount { from: 1, count: 1 } + ); + assert_eq!(inbound.stats(0).unwrap(), snapshot); + drop(inbound); + drop(clone); + let reconnected = crate::InboundDispatch::new(&db, "mqtt", &Plus).unwrap(); + assert_eq!(reconnected.stats(0).unwrap(), snapshot); + reconnected.dispatch("cmd/in", b"v1"); + assert_eq!(reconnected.stats(0).unwrap().upgraded[0].count, 2); + #[cfg(all(feature = "remote", feature = "observability"))] + { + let records = db.list_records(); + let metrics = &records + .iter() + .find(|r| r.record_key == "rec.in") + .unwrap() + .inbound_routes; + assert_eq!(metrics.len(), 1); + assert_eq!(metrics[0].link, "mqtt://cmd/in"); + assert_eq!(metrics[0].stats, reconnected.stats(0).unwrap()); + let json = serde_json::to_value(&records).unwrap(); + assert!(json.to_string().contains("too_old")); + } +} diff --git a/aimdb-core/src/typed_api/tests/link_outbound.rs b/aimdb-core/src/typed_api/tests/link_outbound.rs new file mode 100644 index 00000000..ebe90dc5 --- /dev/null +++ b/aimdb-core/src/typed_api/tests/link_outbound.rs @@ -0,0 +1,517 @@ +//! `OutboundLinkBuilder`: registration (`finish`, serializers, wire format) +//! and the pull path (`OutboundRoutes`, scratch, topic writers). + +use super::*; + +#[test] +fn outbound_finish_rejects_patterns() { + let mut rec = crate::typed_record::TypedRecord::::new(); + rec.set_buffer(Box::new(MockBuffer)); + let builders: Vec> = + vec![Box::new(MockConnectorBuilder { + scheme: "mqtt".to_string(), + })]; + let extensions = crate::extensions::Extensions::new(); + let mut reg = make_registrar(&mut rec, &builders, &extensions); + + reg.link_to("mqtt://out/{device}") + .with_serializer(|_ctx, r: &TestRecord| Ok(r.value.to_le_bytes().to_vec())) + .finish(); + + assert!(rec.outbound_connectors().is_empty()); + let errors = drain_errors(&mut rec); + assert!(errors[0].message.contains("cannot contain '{' or '}'")); +} + +// ==================================================================== +// Outbound link registration tests (fused source) +// ==================================================================== + +#[test] +fn outbound_finish_registers_fused_link() { + let mut rec = crate::typed_record::TypedRecord::::new(); + rec.set_buffer(Box::new(MockBuffer)); + + let builders: Vec> = + vec![Box::new(MockConnectorBuilder { + scheme: "mqtt".to_string(), + })]; + let extensions = crate::extensions::Extensions::new(); + + let mut reg = make_registrar(&mut rec, &builders, &extensions); + + reg.link_to("mqtt://broker/topic") + .with_serializer(|_ctx, record: &TestRecord| Ok(record.value.to_le_bytes().to_vec())) + .finish(); + + assert_eq!(rec.outbound_connectors().len(), 1); + assert_eq!( + rec.outbound_connectors()[0].url.resource_id(), + "broker/topic" + ); + assert!(drain_errors(&mut rec).is_empty()); +} + +#[test] +fn outbound_finish_without_serializer_records_error() { + let mut rec = crate::typed_record::TypedRecord::::new(); + rec.set_buffer(Box::new(MockBuffer)); + + let builders: Vec> = + vec![Box::new(MockConnectorBuilder { + scheme: "mqtt".to_string(), + })]; + let extensions = crate::extensions::Extensions::new(); + + let mut reg = make_registrar(&mut rec, &builders, &extensions); + + // No serializer set — error recorded, link not registered + reg.link_to("mqtt://broker/topic").finish(); + + assert!(rec.outbound_connectors().is_empty()); + let errors = drain_errors(&mut rec); + assert_eq!(errors.len(), 1); + assert!(errors[0] + .message + .contains("Outbound connector requires a serializer")); + assert_eq!(errors[0].record_key, "test::Record"); + assert_eq!(errors[0].url.as_deref(), Some("mqtt://broker/topic")); +} + +// ==================================================================== +// OutboundRoutes over typed links +// ==================================================================== + +/// Buffer reader that replays a fixed script, then reports the buffer +/// closed. +struct ScriptedReader { + script: Vec>, +} + +impl crate::buffer::BufferReader> for ScriptedReader { + fn poll_recv( + &mut self, + _cx: &mut core::task::Context<'_>, + ) -> core::task::Poll, crate::DbError>> { + let next = if self.script.is_empty() { + Err(crate::DbError::BufferClosed { + buffer_name: "scripted".to_string(), + }) + } else { + self.script.remove(0) + }; + core::task::Poll::Ready(next.map(|value| { + crate::Stamped::new( + value, + crate::WriteMetadata::new(crate::Stamp::from_nanos(0)), + ) + })) + } + fn try_recv(&mut self) -> Result, crate::DbError> { + unimplemented!("not needed for outbound route tests") + } +} + +type Script = fn() -> Vec>; + +/// Buffer whose readers replay `script`. +struct ScriptedBuffer(Script); + +impl crate::buffer::DynBuffer> for ScriptedBuffer { + fn push(&self, _value: crate::Stamped) {} + fn subscribe_boxed( + &self, + ) -> Box> + Send> { + Box::new(ScriptedReader { script: (self.0)() }) + } + fn as_any(&self) -> &dyn core::any::Any { + self + } +} + +fn values(values: &[i32]) -> Vec> { + values + .iter() + .map(|&value| Ok(TestRecord { value })) + .collect() +} + +/// Writes `r` into `out`. +fn le_into( + _ctx: crate::RuntimeContext, + r: &TestRecord, + out: &mut [u8], +) -> Result { + let bytes = r.value.to_le_bytes(); + out.get_mut(..bytes.len()) + .ok_or(SerializeError::BufferTooSmall)? + .copy_from_slice(&bytes); + Ok(bytes.len()) +} + +/// `OutboundRoutes` for the `mqtt` links `links` registers on a record +/// whose buffer replays `script`. +async fn outbound( + script: Script, + links: impl FnOnce(&mut RecordRegistrar<'_, TestRecord>) + Send + 'static, +) -> (crate::AimDb, crate::OutboundRoutes) { + let key_rec_out_13 = crate::Name::::new("rec.out"); + let mut builder = crate::AimDbBuilder::new() + .runtime(Arc::new(MockRuntime)) + .with_connector(NoopConnectorBuilder); + builder.configure(key_rec_out_13, move |reg| { + reg.buffer_raw(Box::new(ScriptedBuffer(script))); + links(reg); + }); + let (db, _runner) = builder.build().await.expect("build must succeed"); + let outbound = crate::OutboundRoutes::new(&db, "mqtt").expect("outbound routes"); + (db, outbound) +} + +/// The next message as `(topic, value, owned)`. +async fn pull(o: &mut crate::OutboundRoutes) -> Option<(String, i32, bool)> { + let msg = o.next().await?; + let owned = matches!(msg.payload, crate::OutboundPayload::Owned(_)); + let bytes: [u8; 4] = msg.payload.as_slice().try_into().expect("4 bytes"); + Some((msg.topic.to_string(), i32::from_le_bytes(bytes), owned)) +} + +/// A lag is counted and skipped; a closed buffer ends the route. +#[tokio::test] +async fn outbound_routes_count_lag_and_end_on_close() { + let (_db, mut o) = outbound( + || { + vec![ + Ok(TestRecord { value: 1 }), + Err(lagged()), + Ok(TestRecord { value: 2 }), + ] + }, + |reg| { + reg.link_to("mqtt://tele/out").with_serializer(le).finish(); + }, + ) + .await; + + use crate::outbound::events::{capture, OutboundEvent}; + let seen = Arc::new(spin::Mutex::new(Vec::new())); + let observer = { + let seen = seen.clone(); + Arc::new(move |event: &OutboundEvent<'_>| { + seen.lock().push(match event { + OutboundEvent::Lagged { topic, skipped } => { + assert_eq!((*topic, *skipped), ("tele/out", 1)); + "lag" + } + OutboundEvent::Closed { topic, error } => { + assert_eq!(*topic, "tele/out"); + assert!(matches!(error, crate::DbError::BufferClosed { .. })); + "closed" + } + other => panic!("unexpected {other:?}"), + }); + }) + }; + capture::future(observer, async { + assert_eq!(pull(&mut o).await, Some(("tele/out".into(), 1, true))); + assert_eq!(pull(&mut o).await, Some(("tele/out".into(), 2, true))); + assert_eq!(o.stats(0).unwrap().lagged, 1); + assert_eq!(pull(&mut o).await, None); + }) + .await; + assert_eq!(*seen.lock(), ["lag", "closed"]); +} + +fn lagged() -> crate::DbError { + crate::DbError::BufferLagged { + lag_count: 1, + buffer_name: "scripted".to_string(), + } +} + +/// A value whose serializer fails is counted and skipped. +#[tokio::test] +async fn outbound_routes_skip_serialize_failures() { + let (_db, mut o) = outbound( + || values(&[13, 42]), + |reg| { + reg.link_to("mqtt://tele/out") + .with_serializer(|ctx, r: &TestRecord| { + if r.value == 13 { + return Err(SerializeError::InvalidData); + } + le(ctx, r) + }) + .finish(); + }, + ) + .await; + + assert_eq!(pull(&mut o).await.map(|m| m.1), Some(42)); + assert_eq!(o.stats(0).unwrap().serialize_failed, 1); +} + +#[tokio::test] +async fn outbound_routes_use_scratch_without_owned_fallback() { + let owned_calls = Arc::new(AtomicUsize::new(0)); + let into_calls = Arc::new(AtomicUsize::new(0)); + let (owned_counter, into_counter) = (owned_calls.clone(), into_calls.clone()); + let (_db, mut o) = outbound( + || values(&[7]), + move |reg| { + reg.link_to("mqtt://tele/out") + .with_serializer(move |ctx, r: &TestRecord| { + owned_counter.fetch_add(1, Ordering::SeqCst); + le(ctx, r) + }) + .with_serializer_into(8, move |ctx, r: &TestRecord, out| { + into_counter.fetch_add(1, Ordering::SeqCst); + le_into(ctx, r, out) + }) + .finish(); + }, + ) + .await; + + assert_eq!(pull(&mut o).await, Some(("tele/out".into(), 7, false))); + assert_eq!(into_calls.load(Ordering::SeqCst), 1); + assert_eq!(owned_calls.load(Ordering::SeqCst), 0); +} + +#[tokio::test] +async fn outbound_routes_fall_back_once_when_scratch_is_small() { + let owned_calls = Arc::new(AtomicUsize::new(0)); + let owned_counter = owned_calls.clone(); + let (_db, mut o) = outbound( + || values(&[9]), + move |reg| { + reg.link_to("mqtt://tele/out") + .with_serializer(move |ctx, r: &TestRecord| { + owned_counter.fetch_add(1, Ordering::SeqCst); + le(ctx, r) + }) + .with_serializer_into(2, |_ctx, _r: &TestRecord, _out| { + Err(SerializeError::BufferTooSmall) + }) + .finish(); + }, + ) + .await; + + assert_eq!(pull(&mut o).await, Some(("tele/out".into(), 9, true))); + assert_eq!(owned_calls.load(Ordering::SeqCst), 1); +} + +/// An into-slice serializer that reports more bytes than the scratch +/// holds, or fails with anything but `BufferTooSmall`, skips the value. +#[tokio::test] +async fn outbound_routes_skip_invalid_lengths_and_data() { + let (_db, mut o) = outbound( + || values(&[1, 2, 3]), + |reg| { + reg.link_to("mqtt://tele/out") + .with_serializer(le) + .with_serializer_into(8, |ctx, r: &TestRecord, out| match r.value { + 1 => Ok(out.len() + 1), + 2 => Err(SerializeError::InvalidData), + _ => le_into(ctx, r, out), + }) + .finish(); + }, + ) + .await; + + assert_eq!(pull(&mut o).await, Some(("tele/out".into(), 3, false))); + assert_eq!(o.stats(0).unwrap().serialize_failed, 2); +} + +/// `with_topic_fn` infers an unannotated closure's argument types; +/// `Ok(false)` publishes to the link's default topic. +#[tokio::test] +async fn with_topic_fn_writes_the_topic_or_the_default() { + use core::fmt::Write as _; + let (_db, mut o) = outbound( + || values(&[5, 0]), + |reg| { + reg.link_to("mqtt://tele/out") + .with_topic_fn(8, |v, out| { + if v.value <= 0 { + return Ok(false); + } + write!(out, "dyn/{}", v.value)?; + Ok(true) + }) + .with_serializer(le) + .finish(); + }, + ) + .await; + + assert_eq!(o.routes()[0].topic_capacity, 8); + assert_eq!(pull(&mut o).await.map(|m| m.0), Some("dyn/5".into())); + assert_eq!(pull(&mut o).await.map(|m| m.0), Some("tele/out".into())); +} + +/// A topic that overflows skips its value, even when the writer ignores +/// the error and returns `Ok(true)`. +#[tokio::test] +async fn overflowing_topics_are_skipped() { + use core::fmt::Write as _; + let (_db, mut o) = outbound( + || values(&[123_456, 1_234_567, 7]), + |reg| { + reg.link_to("mqtt://tele/out") + .with_topic_fn(6, |v, out| { + if v.value == 1_234_567 { + let _ = write!(out, "t/{}", v.value); + return Ok(true); + } + write!(out, "t/{}", v.value)?; + Ok(true) + }) + .with_serializer(le) + .finish(); + }, + ) + .await; + + // "t/123456" (8 bytes) and "t/1234567" (9 bytes) do not fit in 6. + assert_eq!(pull(&mut o).await, Some(("t/7".into(), 7, true))); + assert_eq!(o.stats(0).unwrap().topic_overflow, 2); +} + +/// Registrar → build → `OutboundRoutes`, pinning the factory wiring: the +/// serializer set last wins, whichever way its context is typed. +#[tokio::test] +async fn outbound_roundtrip_yields_serialized_values() { + let (_db, mut o) = outbound( + || values(&[5]), + |reg| { + reg.link_to("mqtt://tele/out?qos=1") + .with_serializer(|_ctx, _r: &TestRecord| Ok(vec![0])) + .with_serializer(|_ctx: crate::RuntimeContext, r: &TestRecord| { + Ok(r.value.to_le_bytes().to_vec()) + }) + .with_serializer_into(4, |ctx, r: &TestRecord, out| le_into(ctx, r, out)) + .finish(); + }, + ) + .await; + + let route = &o.routes()[0]; + assert_eq!(&*route.default_topic, "tele/out"); + assert_eq!(route.payload_capacity, 4); + assert_eq!(route.record_index, 0); + assert_eq!(pull(&mut o).await, Some(("tele/out".into(), 5, false))); + assert_eq!(pull(&mut o).await, None); +} + +#[test] +fn serializer_setters_clear_recorded_wire_format() { + use crate::connector::WIRE_FORMAT_KEY; + + let mut rec = crate::typed_record::TypedRecord::::new(); + rec.set_buffer(Box::new(MockBuffer)); + let builders: Vec> = + vec![Box::new(MockConnectorBuilder { + scheme: "mqtt".to_string(), + })]; + let extensions = crate::extensions::Extensions::new(); + let mut reg = make_registrar(&mut rec, &builders, &extensions); + + reg.link_to("mqtt://a") + .with_config(WIRE_FORMAT_KEY, "cdr") + .with_serializer(|_ctx, r: &TestRecord| Ok(r.value.to_le_bytes().to_vec())) + .finish(); + reg.link_to("mqtt://b") + .with_serializer(|_ctx, r: &TestRecord| Ok(r.value.to_le_bytes().to_vec())) + .with_config(WIRE_FORMAT_KEY, "cdr") + .with_serializer_into(4, |_ctx, _r: &TestRecord, _out| Ok(0)) + .finish(); + reg.link_from("mqtt://c") + .with_config(WIRE_FORMAT_KEY, "cdr") + .with_deserializer(|_ctx, _bytes: &[u8]| Ok(TestRecord { value: 0 })) + .finish(); + reg.link_from("mqtt://e") + .with_config(WIRE_FORMAT_KEY, "cdr") + .with_match_deserializer(|_ctx, _m, _bytes: &[u8]| Ok(TestRecord { value: 0 })) + .finish(); + reg.link_to("mqtt://d") + .with_serializer(|_ctx, r: &TestRecord| Ok(r.value.to_le_bytes().to_vec())) + .with_config(WIRE_FORMAT_KEY, "cdr") + .finish(); + + let has_format = |config: &[(String, String)]| config.iter().any(|(k, _)| k == WIRE_FORMAT_KEY); + let outbound = rec.outbound_connectors(); + assert!(!has_format(&outbound[0].config)); + assert!(!has_format(&outbound[1].config)); + assert!(has_format(&outbound[2].config), "recorded after the setter"); + let inbound = rec.inbound_connectors(); + assert!(!has_format(&inbound[0].config)); + assert!(!has_format(&inbound[1].config)); +} + +/// Connectors read each route's record type and options from its info; +/// a topic writer shows as a non-zero `topic_capacity`. +#[tokio::test] +async fn route_infos_carry_type_config_and_resolved_topic() { + use core::any::TypeId; + + let (_db, outbound) = outbound( + || values(&[]), + |reg| { + reg.link_to("mqtt://tele/fixed") + .with_serializer(le) + .with_config("qos", "1") + .finish(); + reg.link_to("mqtt://tele/written") + .with_topic_fn(16, |_v, _out| Ok(false)) + .with_serializer(le) + .finish(); + }, + ) + .await; + let routes = outbound.routes(); + assert_eq!(routes.len(), 2); + assert!(routes + .iter() + .all(|r| r.type_id == TypeId::of::())); + assert_eq!( + routes[0].config.protocol_options, + vec![("qos".to_string(), "1".to_string())] + ); + assert_eq!(routes[0].topic_capacity, 0); + assert_eq!(routes[1].topic_capacity, 16); + + let resolved = Arc::new(AtomicUsize::new(0)); + let calls = resolved.clone(); + let (db, _last, _count) = inbound_db(move |reg| { + reg.link_from("mqtt://cmd/in") + .with_topic_resolver(move || { + calls.fetch_add(1, Ordering::SeqCst); + Some("cmd/resolved".to_string()) + }) + .with_deserializer(|_ctx, _bytes: &[u8]| Ok(TestRecord { value: 0 })) + .with_config("qos", "2") + .finish(); + reg.link_from("mqtt://dev/{id}") + .with_match_deserializer(key_deser) + .finish(); + }) + .await; + let inbound = crate::InboundDispatch::new(&db, "mqtt", &Plus).expect("routes compile"); + assert_eq!(resolved.load(Ordering::SeqCst), 1, "resolved once"); + + let infos = inbound.routes(); + assert_eq!(infos.len(), inbound.route_count()); + let topics: Vec<&str> = infos.iter().map(|i| &*i.topic).collect(); + assert_eq!(topics, ["cmd/resolved", "dev/{id}"]); + assert!(infos + .iter() + .all(|i| i.type_id == TypeId::of::())); + assert!(infos.iter().all(|i| i.record_index == 0)); + assert_eq!( + infos[0].config.protocol_options, + vec![("qos".to_string(), "2".to_string())] + ); +} diff --git a/aimdb-core/src/typed_api/tests/mod.rs b/aimdb-core/src/typed_api/tests/mod.rs new file mode 100644 index 00000000..42bf0c94 --- /dev/null +++ b/aimdb-core/src/typed_api/tests/mod.rs @@ -0,0 +1,264 @@ +//! Tests for `typed_api`, split per concern. Shared fixtures live here; +//! child modules see them (and every private item of `typed_api`) via +//! `use super::*`. + +mod build; +mod link_inbound; +mod link_outbound; +mod registrar; + +use super::*; +use crate::{connector::SerializeError, DbResult}; +use alloc::sync::Arc; +use core::future::Future; +use core::pin::Pin; + +// The original inline module got these through `super::*` from the old +// `typed_api.rs` imports; after the split they live in the submodules. +use alloc::{ + boxed::Box, + string::{String, ToString}, + vec::Vec, +}; + +#[cfg(not(feature = "std"))] +use alloc::vec; + +#[allow(dead_code)] +#[derive(Clone, Debug)] +struct TestRecord { + value: i32, +} + +#[test] +fn test_link_address_simple() { + use crate::connector::LinkAddress; + let addr = LinkAddress::parse("mqtt://sensors").unwrap(); + assert_eq!(addr.scheme(), "mqtt"); + assert_eq!(addr.resource_id(), "sensors"); +} + +#[test] +fn test_link_address_multi_level() { + use crate::connector::LinkAddress; + let addr = LinkAddress::parse("mqtt://sensors/temperature").unwrap(); + assert_eq!(addr.resource_id(), "sensors/temperature"); +} + +#[test] +fn test_link_address_deep() { + use crate::connector::LinkAddress; + let addr = LinkAddress::parse("mqtt://factory/floor1/sensors/temp").unwrap(); + assert_eq!(addr.resource_id(), "factory/floor1/sensors/temp"); +} + +// ==================================================================== +// Test infrastructure for InboundLinkBuilder deserializer tests +// ==================================================================== + +/// Minimal mock runtime for context tests — the builder only needs the +/// dyn-safe `RuntimeOps` surface, supplied by the shared test stub. +use crate::executor::test_support::NoopRuntimeOps as MockRuntime; + +/// Minimal mock buffer so `has_buffer()` returns true +struct MockBuffer; + +impl crate::buffer::DynBuffer> for MockBuffer { + fn push(&self, _value: crate::Stamped) {} + fn subscribe_boxed( + &self, + ) -> Box> + Send> { + unimplemented!("not needed for deserializer tests") + } + fn as_any(&self) -> &dyn core::any::Any { + self + } +} + +/// Mock connector builder that reports a given scheme +struct MockConnectorBuilder { + scheme: String, +} + +impl crate::connector::ConnectorBuilder for MockConnectorBuilder { + fn build<'a>( + &'a self, + _db: &'a crate::AimDb, + ) -> Pin< + Box< + dyn Future + Send + 'static>>>>> + + Send + + 'a, + >, + > { + unimplemented!("not needed for deserializer tests") + } + fn scheme(&self) -> &str { + &self.scheme + } +} + +/// Helper: build a RecordRegistrar wired to a TypedRecord with a buffer and a +/// mock connector builder for the given scheme. +fn make_registrar<'a>( + rec: &'a mut crate::typed_record::TypedRecord, + builders: &'a [Box], + extensions: &'a crate::extensions::Extensions, +) -> RecordRegistrar<'a, TestRecord> { + RecordRegistrar { + rec, + connector_builders: builders, + builder_id: TEST_BUILDER, + record_key: "test::Record".to_string(), + key_link_address: None, + extensions, + last_stage: None, + _schema: core::marker::PhantomData, + } +} + +/// Drains the configuration errors a registrar/setter recorded on `rec`. +fn drain_errors( + rec: &mut crate::typed_record::TypedRecord, +) -> Vec { + use crate::typed_record::AnyRecord; + rec.drain_config_errors() +} + +fn ser(_ctx: crate::RuntimeContext, r: &TestRecord) -> Result, SerializeError> { + Ok(r.value.to_le_bytes().to_vec()) +} + +fn de(_ctx: crate::RuntimeContext, _bytes: &[u8]) -> Result { + Ok(TestRecord { value: 0 }) +} + +impl From for TestRecord { + fn from(value: i32) -> Self { + TestRecord { value } + } +} + +/// A custom input, generic over every record type it can produce. +struct Counter; + +impl Input for Counter +where + T: From + Send + Sync + 'static + Debug + Clone, +{ + fn wire(self, reg: &mut RecordRegistrar<'_, T, S>) { + reg.source(|_ctx, producer| async move { + for i in 0..3 { + producer.produce(T::from(i)); + } + }); + } +} + +// ==================================================================== +// Links through a connector handle: `OutboundLink::on` / `InboundLink::on` +// ==================================================================== + +/// The builder id `make_registrar` uses; real builders start at 1. +const TEST_BUILDER: u32 = 0; + +/// Connector builder whose `build()` contributes nothing — for tests +/// that must get through the connector phase. +struct NoopConnectorBuilder; + +impl crate::connector::ConnectorBuilder for NoopConnectorBuilder { + fn build<'a>( + &'a self, + _db: &'a crate::AimDb, + ) -> Pin< + Box< + dyn Future + Send + 'static>>>>> + + Send + + 'a, + >, + > { + Box::pin(async { Ok(Vec::new()) }) + } + fn scheme(&self) -> &str { + "mqtt" + } +} + +// ==================================================================== +// Fused ingest roundtrip tests +// ==================================================================== + +use core::sync::atomic::{AtomicI32, AtomicUsize, Ordering}; + +/// Buffer that records the last pushed value and a push count — +/// atomics only, so the test runs under no_std + alloc too. +struct RecordingBuffer { + last: Arc, + count: Arc, +} + +impl crate::buffer::DynBuffer> for RecordingBuffer { + fn push(&self, sample: crate::Stamped) { + self.last.store(sample.value.value, Ordering::SeqCst); + self.count.fetch_add(1, Ordering::SeqCst); + } + fn subscribe_boxed( + &self, + ) -> Box> + Send> { + unimplemented!("not needed for ingest tests") + } + fn as_any(&self) -> &dyn core::any::Any { + self + } +} + +// ==================================================================== +// InboundDispatch: patterns, keys and connector-build errors +// ==================================================================== + +use crate::topic_pattern::test_support::Plus; + +/// A record `rec.in` whose buffer stores the last value and a count. +async fn inbound_db( + links: impl FnOnce(&mut RecordRegistrar<'_, TestRecord>) + Send + 'static, +) -> (crate::AimDb, Arc, Arc) { + let key_rec_in_11 = crate::Name::::new("rec.in"); + let last = Arc::new(AtomicI32::new(-1)); + let count = Arc::new(AtomicUsize::new(0)); + let (buf_last, buf_count) = (last.clone(), count.clone()); + let mut builder = crate::AimDbBuilder::new() + .runtime(Arc::new(MockRuntime)) + .with_connector(NoopConnectorBuilder); + builder.configure(key_rec_in_11, move |reg| { + reg.buffer_raw(Box::new(RecordingBuffer { + last: buf_last, + count: buf_count, + })); + links(reg); + }); + let (db, _runner) = builder.build().await.expect("build must succeed"); + (db, last, count) +} + +/// The key index, or -1 without a key. +fn key_deser( + _ctx: &crate::RuntimeContext, + m: &crate::TopicMatch<'_>, + _bytes: &[u8], +) -> Result { + Ok(TestRecord { + value: m.key().map_or(-1, |k| k.index() as i32), + }) +} + +fn config_errors(result: crate::DbResult) -> Vec { + match result { + Err(crate::DbError::InvalidConfiguration { errors }) => errors, + Err(e) => panic!("unexpected error {e:?}"), + Ok(_) => panic!("expected configuration errors"), + } +} + +fn le(_ctx: crate::RuntimeContext, r: &TestRecord) -> Result, SerializeError> { + Ok(r.value.to_le_bytes().to_vec()) +} diff --git a/aimdb-core/src/typed_api/tests/registrar.rs b/aimdb-core/src/typed_api/tests/registrar.rs new file mode 100644 index 00000000..c15d6425 --- /dev/null +++ b/aimdb-core/src/typed_api/tests/registrar.rs @@ -0,0 +1,490 @@ +//! `RecordRegistrar`: link registration and validation shared by both +//! directions (connector handles, detached links, envelopes, stage rules). + +use super::*; + +/// A detached link keeps its options when registered: `push_outbound` / +/// `push_inbound` must copy the config from the user's link, not from +/// the link they build. +#[test] +fn detached_links_keep_their_config() { + let mut rec = crate::typed_record::TypedRecord::::new(); + rec.set_buffer(Box::new(MockBuffer)); + let builders: Vec> = + vec![Box::new(MockConnectorBuilder { + scheme: "mqtt".to_string(), + })]; + let extensions = crate::extensions::Extensions::new(); + let mut reg = make_registrar(&mut rec, &builders, &extensions); + + reg.push_outbound( + OutboundLink::new("mqtt://out") + .with_config("qos", "1") + .with_serializer(|_ctx, r: &TestRecord| Ok(r.value.to_le_bytes().to_vec())), + ); + reg.push_inbound( + InboundLink::new("mqtt://in") + .with_config("qos", "2") + .with_deserializer(|_ctx, _bytes: &[u8]| Ok(TestRecord { value: 0 })), + ); + + let qos = |config: &[(String, String)]| { + config + .iter() + .find(|(k, _)| k == "qos") + .map(|(_, v)| v.clone()) + }; + assert_eq!( + qos(&rec.outbound_connectors()[0].config).as_deref(), + Some("1") + ); + assert_eq!( + qos(&rec.inbound_connectors()[0].config).as_deref(), + Some("2") + ); + assert!(drain_errors(&mut rec).is_empty()); +} + +#[test] +fn envelope_config_is_consumed_by_core_and_never_reaches_connectors() { + use crate::link_wire::ENVELOPE_KEY; + let mut rec = crate::typed_record::TypedRecord::::new(); + rec.set_buffer(Box::new(MockBuffer)); + let builders: Vec> = + vec![Box::new(MockConnectorBuilder { + scheme: "mqtt".to_string(), + })]; + let extensions = crate::extensions::Extensions::new(); + let mut reg = make_registrar(&mut rec, &builders, &extensions); + + reg.push_outbound( + OutboundLink::new("mqtt://out") + .with_config(ENVELOPE_KEY, "inline") + .with_config("qos", "1") + .with_config(ENVELOPE_KEY, "bound") + .with_serializer(|_ctx, r: &TestRecord| Ok(r.value.to_le_bytes().to_vec())), + ); + reg.push_inbound( + InboundLink::new("mqtt://in") + .with_config(ENVELOPE_KEY, "bound") + .with_config("qos", "2") + .with_deserializer(|_ctx, _bytes: &[u8]| Ok(TestRecord { value: 0 })), + ); + // Still read first: the last entry wins, and inline needs a finalizer. + reg.push_inbound( + InboundLink::new("mqtt://inline") + .with_config(ENVELOPE_KEY, "inline") + .with_deserializer(|_ctx, _bytes: &[u8]| Ok(TestRecord { value: 0 })), + ); + + let expected = [("qos".to_string(), "1".to_string())]; + assert_eq!(rec.outbound_connectors()[0].config, expected); + let expected = [("qos".to_string(), "2".to_string())]; + assert_eq!(rec.inbound_connectors()[0].config, expected); + assert_eq!(rec.inbound_connectors().len(), 1); + let errors = drain_errors(&mut rec); + assert_eq!(errors.len(), 1); + assert!(errors[0].message.contains("inline envelopes require")); +} + +// ==================================================================== +// Detached links via .input() / .output() +// ==================================================================== + +/// Runs `wire` on a fresh buffered `TestRecord` with an `mqtt` connector +/// registered, and returns the record. +fn registered( + wire: impl FnOnce(&mut RecordRegistrar<'_, TestRecord>), +) -> crate::typed_record::TypedRecord { + let mut rec = crate::typed_record::TypedRecord::::new(); + rec.set_buffer(Box::new(MockBuffer)); + let builders: Vec> = + vec![Box::new(MockConnectorBuilder { + scheme: "mqtt".to_string(), + })]; + let extensions = crate::extensions::Extensions::new(); + wire(&mut make_registrar(&mut rec, &builders, &extensions)); + rec +} + +fn match_de( + _ctx: &crate::RuntimeContext, + _m: &crate::TopicMatch<'_>, + _bytes: &[u8], +) -> Result { + Ok(TestRecord { value: 0 }) +} + +/// The same options, applied to an attached or a detached builder. +fn outbound_options( + b: OutboundLinkBuilder, +) -> OutboundLinkBuilder { + b.with_config("qos", "1") + .with_serializer(ser) + .with_config(crate::connector::WIRE_FORMAT_KEY, "le") + .with_timeout_ms(50) +} + +fn inbound_options(b: InboundLinkBuilder) -> InboundLinkBuilder { + b.with_config("qos", "1") + .with_match_deserializer(match_de) + .with_config(crate::connector::WIRE_FORMAT_KEY, "le") + .key("d", 4) + .with_topic_resolver(|| None) +} + +#[test] +fn detached_inbound_link_registers_like_link_from() { + let mut attached = registered(|reg| { + inbound_options(reg.link_from("mqtt://temp/{d}")).finish(); + }); + let mut detached = registered(|reg| { + reg.input(inbound_options(InboundLink::new("mqtt://temp/{d}"))); + }); + + let (a, d) = (attached.inbound_connectors(), detached.inbound_connectors()); + assert_eq!((a.len(), d.len()), (1, 1)); + assert_eq!(a[0].url.to_string(), d[0].url.to_string()); + assert_eq!(a[0].config, d[0].config); + assert!(d[0].config.iter().any(|(k, v)| k == "qos" && v == "1")); + assert_eq!(a[0].key, d[0].key); + assert!(d[0].key.is_some()); + assert!(a[0].topic_resolver.is_some() && d[0].topic_resolver.is_some()); + assert!(drain_errors(&mut attached).is_empty()); + assert!(drain_errors(&mut detached).is_empty()); +} + +#[test] +fn detached_outbound_links_register_like_link_to() { + let mut attached = registered(|reg| { + outbound_options(reg.link_to("mqtt://out")).finish(); + reg.with_name("out"); + }); + let mut detached = registered(|reg| { + reg.output(outbound_options(OutboundLink::new("mqtt://out"))) + .with_name("out"); + }); + + let (a, d) = ( + attached.outbound_connectors(), + detached.outbound_connectors(), + ); + assert_eq!((a.len(), d.len()), (1, 1)); + assert_eq!(a[0].url.to_string(), d[0].url.to_string()); + assert_eq!(a[0].config, d[0].config); + assert!(d[0] + .config + .iter() + .any(|(k, v)| k == "timeout_ms" && v == "50")); + + #[cfg(feature = "observability")] + for rec in [&attached, &detached] { + let links = rec.profiling().links(); + assert_eq!(links.len(), 1, "one profiling stage per link"); + assert_eq!(links[0].name.as_deref(), Some("out")); + } + assert!(drain_errors(&mut attached).is_empty()); + assert!(drain_errors(&mut detached).is_empty()); +} + +#[test] +fn detached_links_record_the_same_errors_as_attached_ones() { + /// Links registered and errors recorded (url, message). + type Outcome = (usize, Vec<(Option, String)>); + fn outcome(mut rec: crate::typed_record::TypedRecord) -> Outcome { + let links = rec.outbound_connectors().len() + rec.inbound_connectors().len(); + let errors = drain_errors(&mut rec) + .into_iter() + .map(|e| (e.url, e.message)) + .collect(); + (links, errors) + } + + // Each case runs once through `link_to`/`link_from` + `finish()` + // and once through `.output()`/`.input()`; `$b` is the builder. + macro_rules! same_errors { + (out $url:expr, |$b:ident| $opts:expr, $msg:expr) => {{ + let attached = outcome(registered(|reg| { + let $b = reg.link_to($url); + $opts.finish(); + })); + let detached = outcome(registered(|reg| { + let $b = OutboundLink::new($url); + reg.output($opts); + })); + assert_eq!(attached, detached, "outbound {}", $url); + assert_eq!(detached.0, 0, "nothing registered for {}", $url); + assert_eq!(detached.1.len(), 1, "one error for {}", $url); + assert!(detached.1[0].1.contains($msg), "{:?}", detached.1); + }}; + (in $url:expr, |$b:ident| $opts:expr, $msg:expr) => {{ + let attached = outcome(registered(|reg| { + let $b = reg.link_from($url); + $opts.finish(); + })); + let detached = outcome(registered(|reg| { + let $b = InboundLink::new($url); + reg.input($opts); + })); + assert_eq!(attached, detached, "inbound {}", $url); + assert_eq!(detached.0, 0, "nothing registered for {}", $url); + assert_eq!(detached.1.len(), 1, "one error for {}", $url); + assert!(detached.1[0].1.contains($msg), "{:?}", detached.1); + }}; + } + + same_errors!(out "no-scheme", |b| b.with_serializer(ser), "Invalid connector URL"); + same_errors!(out "mqtt://a/{x}", |b| b.with_serializer(ser), "cannot contain"); + same_errors!(out "mqtt://a", |b| b, "requires a serializer"); + same_errors!(out "kafka://a", |b| b.with_serializer(ser), "No connector registered"); + + same_errors!(in "no-scheme", |b| b.with_deserializer(de), "Invalid connector URL"); + same_errors!(in "mqtt://a", |b| b, "requires a deserializer"); + same_errors!( + in "mqtt://a", + |b| b.with_deserializer(de).with_match_deserializer(match_de), + "not both" + ); + same_errors!(in "kafka://a", |b| b.with_deserializer(de), "No connector registered"); + same_errors!( + in "mqtt://t/{d}", + |b| b.with_deserializer(de).key("x", 2), + "is not a capture" + ); + same_errors!( + in "mqtt://t/{d}", + |b| b.with_deserializer(de).key("d", 0), + "at least 1" + ); +} + +#[test] +fn custom_input_wires_a_source() { + let mut rec = registered(|reg| { + reg.input(Counter); + }); + assert!(rec.has_producer()); + assert!(drain_errors(&mut rec).is_empty()); +} + +/// Runs `wire` on a fresh buffered `TestRecord` with connectors +/// `[mqtt, knx]`, so a handle with index 1 really selects `knx`. +fn registered_mqtt_knx( + wire: impl FnOnce(&mut RecordRegistrar<'_, TestRecord>), +) -> crate::typed_record::TypedRecord { + let mut rec = crate::typed_record::TypedRecord::::new(); + rec.set_buffer(Box::new(MockBuffer)); + let builders: Vec> = vec![ + Box::new(MockConnectorBuilder { + scheme: "mqtt".to_string(), + }), + Box::new(MockConnectorBuilder { + scheme: "knx".to_string(), + }), + ]; + let extensions = crate::extensions::Extensions::new(); + wire(&mut make_registrar(&mut rec, &builders, &extensions)); + rec +} + +fn handle(builder: u32, index: u16) -> crate::ConnectorHandle { + crate::ConnectorHandle { builder, index } +} + +#[test] +fn handle_links_take_the_connector_scheme() { + let (mqtt, knx) = (handle(TEST_BUILDER, 0), handle(TEST_BUILDER, 1)); + let mut rec = registered_mqtt_knx(|reg| { + reg.input(InboundLink::on(knx, "1/0/7").with_deserializer(de)) + .output(OutboundLink::on(knx, "1/2/3").with_serializer(ser)) + // A full URL, as a `#[link_address]` key gives, when it matches. + .output(OutboundLink::on(mqtt, "mqtt://sensors/temp").with_serializer(ser)); + }); + + assert!(drain_errors(&mut rec).is_empty()); + assert_eq!(rec.inbound_connectors()[0].url.to_string(), "knx://1/0/7"); + let out: Vec = rec + .outbound_connectors() + .iter() + .map(|l| l.url.to_string()) + .collect(); + assert_eq!(out, ["knx://1/2/3", "mqtt://sensors/temp"]); +} + +#[test] +fn handle_links_reject_wrong_scheme_and_foreign_handles() { + let (mqtt, knx) = (handle(TEST_BUILDER, 0), handle(TEST_BUILDER, 1)); + let foreign = handle(TEST_BUILDER + 1, 0); + let out_of_range = handle(TEST_BUILDER, 7); + let mut rec = registered_mqtt_knx(|reg| { + reg.output(OutboundLink::on(mqtt, "knx://1/2/3").with_serializer(ser)) + .input(InboundLink::on(knx, "mqtt://x").with_deserializer(de)) + .output(OutboundLink::on(foreign, "a").with_serializer(ser)) + .input(InboundLink::on(foreign, "a").with_deserializer(de)) + .output(OutboundLink::on(out_of_range, "a").with_serializer(ser)); + }); + + assert!(rec.outbound_connectors().is_empty()); + assert!(rec.inbound_connectors().is_empty()); + let errors: Vec<(Option, String)> = drain_errors(&mut rec) + .into_iter() + .map(|e| (e.url, e.message)) + .collect(); + let foreign_msg = "Connector handle belongs to a different AimDbBuilder"; + let expected = [ + ( + "knx://1/2/3", + "Address scheme 'knx' does not match the connector's scheme 'mqtt'", + ), + ( + "mqtt://x", + "Address scheme 'mqtt' does not match the connector's scheme 'knx'", + ), + ("a", foreign_msg), + ("a", foreign_msg), + ("a", foreign_msg), + ]; + let expected: Vec<(Option, String)> = expected + .iter() + .map(|(url, msg)| (Some(url.to_string()), msg.to_string())) + .collect(); + assert_eq!(errors, expected); +} + +#[test] +fn finish_with_unregistered_scheme_records_error() { + let mut rec = crate::typed_record::TypedRecord::::new(); + rec.set_buffer(Box::new(MockBuffer)); + + // No connector builders registered at all + let builders: Vec> = vec![]; + let extensions = crate::extensions::Extensions::new(); + + let mut reg = make_registrar(&mut rec, &builders, &extensions); + reg.link_to("mqtt://broker/topic") + .with_serializer(|_ctx, r: &TestRecord| Ok(r.value.to_le_bytes().to_vec())) + .finish(); + + assert!(rec.outbound_connectors().is_empty()); + let errors = drain_errors(&mut rec); + assert_eq!(errors.len(), 1); + assert!(errors[0] + .message + .contains("No connector registered for scheme 'mqtt'")); + assert_eq!(errors[0].record_key, "test::Record"); +} + +// ==================================================================== +// Writer-exclusivity tests (.source / .transform / .link_from) +// ==================================================================== + +/// Helper: build a `TransformDescriptor` with a no-op spawn function. +fn dummy_transform_descriptor() -> crate::transform::TransformDescriptor { + crate::transform::TransformDescriptor:: { + input_keys: vec![], + input_types: vec![], + build_fn: Box::new(|_p, _db, _output_key, _profiling| { + crate::transform::CollectedTransform { + task_future: Box::pin(async {}), + fanin_futures: vec![], + } + }), + } +} + +#[test] +fn cross_stage_registrations_record_without_setter_errors() { + // Cross-stage exclusivity (.source()/.transform()/.link_from()) is + // validated by build(), not by the setters: conflicting registrations + // are all recorded so build() can report the conflict with the record + // key attached. + let mut rec = crate::typed_record::TypedRecord::::new(); + rec.set_buffer(Box::new(MockBuffer)); + rec.set_producer(|_ctx, _p| async move {}); + + let builders: Vec> = + vec![Box::new(MockConnectorBuilder { + scheme: "mqtt".to_string(), + })]; + let extensions = crate::extensions::Extensions::new(); + + let mut reg = make_registrar(&mut rec, &builders, &extensions); + reg.link_from("mqtt://broker/topic") + .with_deserializer(|_ctx, _b: &[u8]| Ok(TestRecord { value: 0 })) + .finish(); + + assert!(rec.has_producer()); + assert_eq!(rec.inbound_connectors().len(), 1); + assert!( + drain_errors(&mut rec).is_empty(), + "no setter-level cross-stage errors; build() reports the conflict" + ); +} + +#[test] +fn duplicate_source_and_transform_record_errors() { + // Same-stage duplicates are still caught at registration time: a + // second .source()/.transform() would silently overwrite the first. + let mut rec = crate::typed_record::TypedRecord::::new(); + rec.set_buffer(Box::new(MockBuffer)); + + rec.set_producer(|_ctx, _p| async move {}); + rec.set_producer(|_ctx, _p| async move {}); + rec.set_transform(dummy_transform_descriptor()); + rec.set_transform(dummy_transform_descriptor()); + + let errors = drain_errors(&mut rec); + assert_eq!(errors.len(), 2); + assert!(errors[0].message.contains("already has a producer service")); + assert!(errors[1] + .message + .contains("already has a .transform(); only one is allowed")); +} + +#[test] +fn multiple_link_from_allowed() { + let mut rec = crate::typed_record::TypedRecord::::new(); + rec.set_buffer(Box::new(MockBuffer)); + + let builders: Vec> = + vec![Box::new(MockConnectorBuilder { + scheme: "mqtt".to_string(), + })]; + let extensions = crate::extensions::Extensions::new(); + let mut reg = make_registrar(&mut rec, &builders, &extensions); + + // Chained via finish() → &mut RecordRegistrar … + reg.link_from("mqtt://broker/topic-a") + .with_deserializer(|_ctx, _b: &[u8]| Ok(TestRecord { value: 0 })) + .finish() + .link_from("mqtt://broker/topic-b") + .with_deserializer(|_ctx, _b: &[u8]| Ok(TestRecord { value: 0 })) + .finish(); + + // … and as separate statements: each call takes a fresh borrow, so + // the registrar is reusable after a chain ends. + reg.link_from("mqtt://broker/topic-c") + .with_deserializer(|_ctx, _b: &[u8]| Ok(TestRecord { value: 0 })) + .finish(); + reg.with_name("third-link"); + + assert_eq!(rec.inbound_connectors().len(), 3); +} + +/// Registrar methods take fresh borrows: separate +/// statements in a configure-style closure must compile. +#[test] +fn registrar_allows_separate_statements() { + let mut rec = crate::typed_record::TypedRecord::::new(); + rec.set_buffer(Box::new(MockBuffer)); + + let builders: Vec> = vec![]; + let extensions = crate::extensions::Extensions::new(); + let mut reg = make_registrar(&mut rec, &builders, &extensions); + + reg.source(|_ctx, _p| async move {}); + reg.tap(|_ctx, _c| async move {}); + + assert!(rec.has_producer()); + assert_eq!(rec.consumer_count(), 1); +} diff --git a/aimdb-core/src/typed_record/any_record.rs b/aimdb-core/src/typed_record/any_record.rs new file mode 100644 index 00000000..31c920f9 --- /dev/null +++ b/aimdb-core/src/typed_record/any_record.rs @@ -0,0 +1,179 @@ +#[cfg(feature = "remote")] +use crate::JsonRecordAccess; +use crate::TypedRecord; +use alloc::{boxed::Box, string::String, sync::Arc, vec::Vec}; +use core::{any::Any, fmt::Debug}; + +/// Type-erased trait for records — the storage and lifecycle contract. +/// +/// Allows storage of heterogeneous record types in a single collection +/// while maintaining type safety through downcast operations. +/// +/// This trait carries the storage/lifecycle +/// surface, plus graph/metadata introspection and observability counter +/// resets. JSON remote access is the one genuinely optional capability: it +/// lives in `JsonRecordAccess`, reachable via `json_access`, both behind the +/// `remote` feature. +/// +/// Consumers: `AimDbBuilder::build()` (config-error draining, the dependency +/// graph fed to [`crate::graph`], typed downcasts via [`AnyRecordExt`]), +/// the builder's inbound/outbound route collection, `AimDbInner::list_records` +/// (remote introspection metadata), and connectors applying the remote-access +/// security policy (`set_writable_erased`). +/// +/// # Thread Safety Requirements +/// +/// This trait requires both `Send` and `Sync` because: +/// - Records are stored in `Arc>` and shared across threads +/// - The router system needs to access records from multiple connector tasks +/// - Emitter needs to be `Send+Sync` to work in async contexts +/// - The `FnOnce` consumers are moved out during spawning, so they don't affect `Sync` +/// +/// **BREAKING CHANGE (v0.2.0):** Added `Sync` bound to `AnyRecord` trait. +/// Record types must now be both `Send + Sync`. Types that were previously +/// `Send` but not `Sync` can no longer be used as records. This change enables: +/// - Concurrent access to records from multiple connector tasks +/// - Safe sharing of record metadata across thread boundaries +/// - Type-safe routing in the bidirectional connector system +/// +/// **Migration:** If your record type `T` is not `Sync`, wrap non-`Sync` fields +/// in `Arc>` or `Arc>` to achieve interior mutability with +/// thread-safe sharing. +pub trait AnyRecord: Send + Sync { + /// Returns self as Any for downcasting + fn as_any(&self) -> &dyn Any; + + /// Returns self as mutable Any for downcasting + fn as_any_mut(&mut self) -> &mut dyn Any; + + /// Drains the configuration mistakes recorded during registration, plus + /// build-time consistency findings (e.g. remote access without a buffer). + /// + /// Called by `AimDbBuilder::build()`, which fills in the record key and + /// reports every finding via + /// [`DbError::InvalidConfiguration`](crate::DbError::InvalidConfiguration). + fn drain_config_errors(&mut self) -> Vec; + + /// Sets the writable flag for this record (type-erased) + /// + /// Used internally by the builder to apply security policy to records. + fn set_writable_erased(&self, writable: bool); + + /// Binds the instance clock every write to this record is stamped from. + /// + /// Called by `AimDbBuilder::build()` for every record before any task + /// runs (design 058 §3.3). + fn bind_clock(&mut self, clock: Arc); + + /// Returns the record's JSON remote-access surface, if it has one. + /// + /// This accessor is the single place the `remote` cfg-gate lives + /// for consumers: they query the capability here instead of cfg-gating + /// every call site. `TypedRecord` always returns `Some`; the runtime + /// "configured with `.with_remote_access()`" checks stay inside the + /// [`JsonRecordAccess`] methods. + #[cfg(feature = "remote")] + fn json_access(&self) -> Option<&dyn JsonRecordAccess> { + None + } + + // ── Graph and metadata introspection ──────────────────────────────── + + /// Gets the outbound connector links + /// + /// Returns outbound connector configuration list for spawning logic. + fn outbound_connectors(&self) -> &[crate::connector::ConnectorLink]; + + /// Get the inbound connector links for this record + fn inbound_connectors(&self) -> &[crate::connector::InboundConnectorLink]; + + /// The schema the record carries, if one was set while configuring it + fn schema(&self) -> Option<&crate::graph::SchemaInfo>; + + /// Returns the number of registered consumers (tap observers) + fn consumer_count(&self) -> usize; + + /// Returns whether a producer service is registered + fn has_producer(&self) -> bool; + + /// Returns whether a buffer is configured + fn has_buffer(&self) -> bool; + + /// Returns whether a transform is registered for this record + fn has_transform(&self) -> bool; + + /// Returns how this record gets its values (for dependency graph construction) + fn record_origin(&self) -> crate::graph::RecordOrigin; + + /// Returns the buffer type name and capacity (for dependency graph) + /// + /// Returns (buffer_type_name, optional_capacity). + fn buffer_info(&self) -> (String, Option); + + /// Returns the transform input keys (if a transform is registered) + fn transform_input_keys(&self) -> Option>; + + /// Returns each transform input's key and the type it is read as (empty + /// if no transform is registered). `build()` checks them against the + /// input records' types. + fn transform_input_types(&self) -> Vec<(String, core::any::TypeId, &'static str)>; + + /// Returns the name of the record's value type, for error messages. + fn type_name(&self) -> &'static str; + + /// Collects metadata for this record + #[cfg(feature = "remote")] + fn collect_metadata( + &self, + type_id: core::any::TypeId, + key: crate::record_id::StringKey, + id: crate::record_id::RecordId, + ) -> crate::remote::RecordMetadata; + + // ── Observability counter resets ───────────────────────────────────── + + /// Resets this record's stage profiling counters (feature `observability`). + /// + /// Default implementation is a no-op; `TypedRecord` overrides it. + /// Consumers: `AimDb::reset_profiling`, driven by the AimX + /// `control.reset_buffer_metrics` RPC and the MCP buffer-metrics tool. + #[cfg(feature = "observability")] + fn reset_profiling(&self) {} + + /// Resets this record's buffer introspection counters (feature `observability`). + /// + /// Default implementation is a no-op; `TypedRecord` overrides it. + #[cfg(feature = "observability")] + fn reset_buffer_metrics(&self) {} +} + +// Helper extension trait for type-safe downcasting +pub trait AnyRecordExt { + /// Attempts to downcast to a typed record reference + /// + /// # Type Parameters + /// * `T` - The expected record type + /// + /// # Returns + /// `Some(&TypedRecord)` if types match, `None` otherwise + fn as_typed(&self) -> Option<&TypedRecord>; + + /// Attempts to downcast to a mutable typed record reference + /// + /// # Type Parameters + /// * `T` - The expected record type + /// + /// # Returns + /// `Some(&mut TypedRecord)` if types match, `None` otherwise + fn as_typed_mut(&mut self) -> Option<&mut TypedRecord>; +} + +impl AnyRecordExt for Box { + fn as_typed(&self) -> Option<&TypedRecord> { + self.as_any().downcast_ref::>() + } + + fn as_typed_mut(&mut self) -> Option<&mut TypedRecord> { + self.as_any_mut().downcast_mut::>() + } +} diff --git a/aimdb-core/src/typed_record/json_adapters.rs b/aimdb-core/src/typed_record/json_adapters.rs new file mode 100644 index 00000000..3bfcd5a4 --- /dev/null +++ b/aimdb-core/src/typed_record/json_adapters.rs @@ -0,0 +1,161 @@ +use alloc::{boxed::Box, vec::Vec}; +use core::task::{Context, Poll}; + +use super::record::RecordCodec; + +/// Type-erased JSON read/subscribe/write for remote access. +/// +/// Internal to the remote-access protocol — application code reads values +/// via `record.latest()?.as_json()` instead. Obtained from a record through +/// [`AnyRecord::json_access`](crate::AnyRecord::json_access), which is where the `remote` cfg-gate +/// lives for consumers. +/// +/// Consumers: `AimDbInner::try_latest_as_json` / `set_record_from_json` +/// (`record.get` / `record.set`), the AimX session dispatch (`record.subscribe` +/// value drain), and `remote::stream::stream_record_updates`. +pub trait JsonRecordAccess { + /// Returns JSON for type-erased remote access + /// + /// Used internally by remote access protocol. **Users should use `record.latest()?.as_json()`.** + fn latest_json(&self) -> Option>; + + /// Returns owned JSON bytes for type-erased remote access. + /// + /// Existing implementations inherit a compatibility path through + /// [`latest_json`](Self::latest_json), keeping its write metadata. + /// `TypedRecord` overrides this and asks its codec to encode `T` + /// directly. + fn latest_json_bytes(&self) -> Option>> { + crate::buffer::json_tree_to_bytes(self.latest_json()?).ok() + } + + /// Subscribe to record updates as JSON stream + /// + /// Creates a type-erased subscription that emits `serde_json::Value` instead of + /// the concrete type `T`. This enables subscribing to a record without knowing + /// its type at compile time. + /// + /// Used internally by remote access protocol for `record.subscribe` functionality. + /// + /// # Returns + /// - `Ok(Box)` - Successfully created subscription + /// - `Err(DbError)` - If serialization not configured or buffer subscription failed + /// + /// # Errors + /// Returns error if: + /// - Record not configured with `.with_remote_access()` + /// - Buffer subscription fails (shouldn't happen in practice) + fn subscribe_json(&self) -> crate::DbResult>; + + /// Sets a record value from JSON + /// + /// Deserializes JSON and produces the value to the record's buffer. + /// + /// **SAFETY:** This method enforces the "No Producer Override" rule: + /// - Returns error if `producer_count > 0` (prevents overriding application logic) + /// - Only configuration records (no producers) should be settable via remote access + /// + /// Used internally by remote access protocol for `record.set` functionality. + /// + /// # Arguments + /// * `json_value` - JSON representation of the value to set + /// + /// # Returns + /// - `Ok(())` - Successfully set the value + /// - `Err(DbError)` - If deserialization fails, producers exist, or no buffer + /// + /// # Errors + /// Returns error if: + /// - Record has active producers (`producer_count > 0`) - **safety check** + /// - JSON deserialization fails (schema mismatch) + /// - Record not configured with buffer + /// - Record not configured with `.with_remote_access()` + fn set_from_json(&self, json_value: serde_json::Value) -> crate::DbResult<()>; + + /// Sets a record from one complete JSON value encoded as bytes. + /// + /// Existing implementations inherit a parser-backed compatibility path + /// through [`set_from_json`](Self::set_from_json). This accepts the exact + /// record value, not an AimX request/write wrapper; the wire dispatch keeps + /// wrapper extraction on its existing tree path. + fn set_from_json_bytes(&self, bytes: &[u8]) -> crate::DbResult<()> { + let value = serde_json::from_slice(bytes) + .map_err(|_| crate::DbError::runtime_error("Failed to parse JSON value"))?; + self.set_from_json(value) + } +} + +/// Adapter that wraps a typed `BufferReader` and serializes values to JSON. +/// +/// Bridges the gap between typed buffers and type-erased JSON streaming for +/// remote access subscriptions. Each receive: +/// 1. Receives one `Stamped` from the buffer +/// 2. Serializes its value through the configured codec +/// 3. Returns either a JSON tree (compatibility API) or owned JSON bytes, +/// with the write metadata of that same sample +/// +/// Used internally by `TypedRecord::subscribe_json()`. +pub(super) struct JsonReaderAdapter { + /// The underlying typed buffer reader + inner: Box> + Send>, + /// JSON codec (from .with_remote_access()) + codec: RecordCodec, +} + +impl JsonReaderAdapter { + /// Wraps a typed buffer reader; values are encoded through `codec`. + pub(super) fn new( + inner: Box> + Send>, + codec: RecordCodec, + ) -> Self { + Self { inner, codec } + } + + /// Encodes one received sample, keeping its write metadata whole. + fn encode( + &self, + sample: crate::Stamped, + encode: impl FnOnce(&RecordCodec, &T) -> Option, + ) -> Result, crate::DbError> { + sample.as_ref().try_map(|value| { + encode(&self.codec, value) + .ok_or_else(|| crate::DbError::runtime_error("Failed to serialize value to JSON")) + }) + } +} + +impl crate::buffer::JsonBufferReader for JsonReaderAdapter { + fn poll_recv_json( + &mut self, + cx: &mut Context<'_>, + ) -> Poll, crate::DbError>> { + // Poll the inner typed reader (allocation-free), then serialize on the + // ready value — no per-message boxing. + match self.inner.poll_recv(cx) { + Poll::Ready(Ok(sample)) => Poll::Ready(self.encode(sample, |c, v| c.encode(v))), + Poll::Ready(Err(e)) => Poll::Ready(Err(e)), + Poll::Pending => Poll::Pending, + } + } + + fn try_recv_json(&mut self) -> Result, crate::DbError> { + let sample = self.inner.try_recv()?; + self.encode(sample, |c, v| c.encode(v)) + } + + fn poll_recv_json_bytes( + &mut self, + cx: &mut Context<'_>, + ) -> Poll>, crate::DbError>> { + match self.inner.poll_recv(cx) { + Poll::Ready(Ok(sample)) => Poll::Ready(self.encode(sample, |c, v| c.encode_to_vec(v))), + Poll::Ready(Err(error)) => Poll::Ready(Err(error)), + Poll::Pending => Poll::Pending, + } + } + + fn try_recv_json_bytes(&mut self) -> Result>, crate::DbError> { + let sample = self.inner.try_recv()?; + self.encode(sample, |c, v| c.encode_to_vec(v)) + } +} diff --git a/aimdb-core/src/typed_record/mod.rs b/aimdb-core/src/typed_record/mod.rs new file mode 100644 index 00000000..e6de5c86 --- /dev/null +++ b/aimdb-core/src/typed_record/mod.rs @@ -0,0 +1,251 @@ +//! Type-safe record storage using TypeId +//! +//! Provides type-safe record identification using Rust's `TypeId` for compile-time safety. +//! +//! # Feature Support +//! +//! All layers below work on both `std` and `no_std + alloc`; they are gated by +//! capability feature, not by `std`: +//! +//! - **always**: Core API (`TypedRecord`, `latest()`, `RecordValue`, producer/consumer). +//! - **`remote`**: the JSON value codec — `.with_remote_access()` installs it +//! and `record.latest()?.as_json()` reads it. +//! - **`remote`**: record metadata (`collect_metadata` → `RecordMetadata`, +//! the `writable` flag) plus the type-erased JSON read/write/subscribe methods +//! (`latest_json[_bytes]` / `set_from_json[_bytes]` / `subscribe_json`) used +//! by the AimX server. +//! +//! Without `remote`, use `record.latest()` + `Deref` for value access and +//! implement custom serialization for embedded protocols (CBOR, MessagePack, etc.). + +use alloc::boxed::Box; + +mod any_record; +#[cfg(feature = "remote")] +mod events; +#[cfg(feature = "remote")] +mod json_adapters; +mod record; + +pub use crate::typed_record::{ + any_record::{AnyRecord, AnyRecordExt}, + record::{RecordFutureCollector, RecordValue, TypedRecord}, +}; + +#[cfg(feature = "remote")] +pub use crate::typed_record::json_adapters::JsonRecordAccess; + +#[cfg(feature = "std")] +type Mutex = std::sync::Mutex; +#[cfg(not(feature = "std"))] +type Mutex = spin::Mutex; + +/// Locks one of the `TypedRecord` field mutexes, hiding the std/spin API +/// difference (`std::sync::Mutex::lock` returns a `LockResult`; `spin` returns +/// the guard directly). A poisoned std mutex is unrecoverable in this code, so +/// `.unwrap()` is the correct response. The returned guard derefs to `T` on +/// both sides, so call sites are identical. +#[cfg(feature = "std")] +fn lock(m: &Mutex) -> std::sync::MutexGuard<'_, T> { + m.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) +} +#[cfg(not(feature = "std"))] +fn lock(m: &Mutex) -> spin::MutexGuard<'_, T> { + m.lock() +} + +// Type alias for boxed futures +pub(crate) type BoxFuture<'a, T> = + core::pin::Pin + Send + 'a>>; + +/// Type alias for consumer service closure stored in TypedRecord +/// Each consumer receives the [`RuntimeContext`](crate::RuntimeContext) and a +/// Consumer handle for subscribing to the buffer +pub(super) type ConsumerServiceFn = + Box) -> BoxFuture<'static, ()> + Send>; + +/// Type alias for producer service closure stored in TypedRecord +/// Takes (RuntimeContext, Producer) and returns a Future +/// This will be auto-spawned during build(). +/// `Send` only — `Sync` is not required because the closure is taken out of +/// `Mutex>` exactly once via `.take()`, and `Mutex: Sync` +/// already holds when `T: Send`. Matches the consumer-side `ConsumerServiceFn`. +pub(super) type ProducerServiceFn = + Box) -> BoxFuture<'static, ()> + Send>; + +#[cfg(all(test, feature = "remote"))] +mod tests { + use super::*; + use alloc::{boxed::Box, sync::Arc, vec::Vec}; + use core::any::Any; + use core::sync::atomic::{AtomicUsize, Ordering}; + use core::task::{Context, Poll}; + + use super::record::RecordCodec; + use crate::buffer::{BufferReader, DynBuffer}; + use crate::codec::JsonCodec; + use crate::{Stamp, Stamped, WriteMetadata}; + + /// A sample whose stamp equals its value. + fn sample(v: u32) -> Stamped { + Stamped::new(v, WriteMetadata::new(Stamp::from_nanos(u64::from(v)))) + } + + struct OneReader(Option>); + + impl BufferReader> for OneReader { + fn poll_recv( + &mut self, + _cx: &mut Context<'_>, + ) -> Poll, crate::DbError>> { + Poll::Ready(self.try_recv()) + } + + fn try_recv(&mut self) -> Result, crate::DbError> { + self.0.take().ok_or(crate::DbError::BufferEmpty) + } + } + + struct PeekBuffer(u32); + + impl DynBuffer> for PeekBuffer { + fn push(&self, _value: Stamped) {} + + fn subscribe_boxed(&self) -> Box> + Send> { + Box::new(OneReader(Some(sample(self.0)))) + } + + fn as_any(&self) -> &dyn Any { + self + } + + fn peek(&self) -> Option> { + Some(sample(self.0)) + } + } + + struct TrackingCodec { + tree_calls: Arc, + byte_calls: Arc, + } + + impl JsonCodec for TrackingCodec { + fn encode(&self, value: &u32) -> Option { + self.tree_calls.fetch_add(1, Ordering::Relaxed); + Some(serde_json::json!(value)) + } + + fn decode(&self, value: &serde_json::Value) -> Option { + value.as_u64()?.try_into().ok() + } + + fn encode_to_vec(&self, value: &u32) -> Option> { + self.byte_calls.fetch_add(1, Ordering::Relaxed); + serde_json::to_vec(value).ok() + } + } + + /// A buffer where every `peek` sees a newer write: value and stamp both + /// equal the number of peeks so far. + struct AdvancingBuffer(core::sync::atomic::AtomicU32); + + impl DynBuffer> for AdvancingBuffer { + fn push(&self, _value: Stamped) {} + + fn subscribe_boxed(&self) -> Box> + Send> { + Box::new(OneReader(None)) + } + + fn as_any(&self) -> &dyn Any { + self + } + + fn peek(&self) -> Option> { + Some(sample(self.0.fetch_add(1, Ordering::SeqCst) + 1)) + } + } + + /// Design 058 §4.4: payload and stamp come from one buffer read. A path + /// that peeked twice would pair a value with a newer write's stamp. + #[test] + fn json_reads_take_payload_and_stamp_from_one_read() { + let mut record = TypedRecord::::new(); + record.with_remote_access(); + record.buffer = Some(Arc::new(AdvancingBuffer( + core::sync::atomic::AtomicU32::new(0), + ))); + + let tree = record.latest_json().unwrap(); + assert_eq!(tree.stamp(), Stamp::from_nanos(1)); + assert_eq!(tree.value, serde_json::json!(1)); + + let bytes = record.latest_json_bytes().unwrap(); + assert_eq!(bytes.stamp(), Stamp::from_nanos(2)); + assert_eq!(bytes.value, b"2"); + + let latest = record.latest().unwrap(); + assert_eq!((*latest.get(), latest.stamp()), (3, Stamp::from_nanos(3))); + } + + #[test] + fn typed_latest_and_subscription_select_the_codec_byte_path() { + let tree_calls = Arc::new(AtomicUsize::new(0)); + let byte_calls = Arc::new(AtomicUsize::new(0)); + let codec: RecordCodec = Arc::new(TrackingCodec { + tree_calls: tree_calls.clone(), + byte_calls: byte_calls.clone(), + }); + + let mut record = TypedRecord::::new(); + record.remote_codec = Some(codec); + record.buffer = Some(Arc::new(PeekBuffer(17))); + + // Payloads are the codec's output for `T` alone; each carries the + // stamp of the sample it was encoded from. + let latest = record.latest_json_bytes().unwrap(); + assert_eq!( + (latest.value.as_slice(), latest.stamp()), + (&b"17"[..], Stamp::from_nanos(17)) + ); + + let mut reader = record.subscribe_json().unwrap(); + let received = reader.try_recv_json_bytes().unwrap(); + assert_eq!( + (received.value.as_slice(), received.stamp()), + (&b"17"[..], Stamp::from_nanos(17)) + ); + + assert_eq!(byte_calls.load(Ordering::Relaxed), 2); + assert_eq!(tree_calls.load(Ordering::Relaxed), 0); + + let tree = record.latest_json().unwrap(); + assert_eq!( + (tree.stamp(), tree.value), + (Stamp::from_nanos(17), serde_json::json!(17)) + ); + assert_eq!(tree_calls.load(Ordering::Relaxed), 1); + } + + #[test] + fn remote_write_rejection_is_typed() { + use crate::typed_record::events::{capture, RemoteWriteEvent}; + let mut record = TypedRecord::::new(); + record.with_remote_access(); + record.set_producer(|_, _| async {}); + let seen = Arc::new(core::sync::atomic::AtomicBool::new(false)); + let observer = { + let seen = seen.clone(); + Arc::new(move |event: &RemoteWriteEvent<'_>| { + let RemoteWriteEvent::Rejected { + operation, + record_type, + } = event; + assert_eq!(*operation, "set_from_json"); + assert_eq!(*record_type, core::any::type_name::()); + seen.store(true, core::sync::atomic::Ordering::Relaxed); + }) + }; + assert!(capture::with(observer, || record.set_from_json(serde_json::json!(7))).is_err()); + assert!(seen.load(core::sync::atomic::Ordering::Relaxed)); + } +} diff --git a/aimdb-core/src/typed_record.rs b/aimdb-core/src/typed_record/record.rs similarity index 62% rename from aimdb-core/src/typed_record.rs rename to aimdb-core/src/typed_record/record.rs index e5e27474..c3953a8e 100644 --- a/aimdb-core/src/typed_record.rs +++ b/aimdb-core/src/typed_record/record.rs @@ -1,68 +1,34 @@ -//! Type-safe record storage using TypeId -//! -//! Provides type-safe record identification using Rust's `TypeId` for compile-time safety. -//! -//! # Feature Support -//! -//! All layers below work on both `std` and `no_std + alloc`; they are gated by -//! capability feature, not by `std`: -//! -//! - **always**: Core API (`TypedRecord`, `latest()`, `RecordValue`, producer/consumer). -//! - **`remote`**: the JSON value codec — `.with_remote_access()` installs it -//! and `record.latest()?.as_json()` reads it. -//! - **`remote`**: record metadata (`collect_metadata` → `RecordMetadata`, -//! the `writable` flag) plus the type-erased JSON read/write/subscribe methods -//! (`latest_json[_bytes]` / `set_from_json[_bytes]` / `subscribe_json`) used -//! by the AimX server. -//! -//! Without `remote`, use `record.latest()` + `Deref` for value access and -//! implement custom serialization for embedded protocols (CBOR, MessagePack, etc.). - -#[cfg(feature = "remote")] -mod events; - -#[cfg(feature = "remote")] -use crate::typed_record::events::{report, RemoteWriteEvent}; - -use core::any::Any; -use core::fmt::Debug; -#[cfg(feature = "remote")] -use core::task::{Context, Poll}; - use alloc::{ boxed::Box, string::{String, ToString}, sync::Arc, vec::Vec, }; +use core::{any::Any, fmt::Debug}; + +use crate::{ + buffer::DynBuffer, + typed_record::{lock, BoxFuture, ConsumerServiceFn, Mutex, ProducerServiceFn}, + AnyRecord, +}; + +#[cfg(feature = "remote")] +use crate::JsonRecordAccess; + +#[cfg(feature = "remote")] +use crate::typed_record::events::{report, RemoteWriteEvent}; #[cfg(feature = "observability")] use crate::profiling::RecordProfilingMetrics; -#[cfg(feature = "std")] -type Mutex = std::sync::Mutex; -#[cfg(not(feature = "std"))] -type Mutex = spin::Mutex; - -/// Locks one of the `TypedRecord` field mutexes, hiding the std/spin API -/// difference (`std::sync::Mutex::lock` returns a `LockResult`; `spin` returns -/// the guard directly). A poisoned std mutex is unrecoverable in this code, so -/// `.unwrap()` is the correct response. The returned guard derefs to `T` on -/// both sides, so call sites are identical. -#[cfg(feature = "std")] -fn lock(m: &Mutex) -> std::sync::MutexGuard<'_, T> { - m.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) -} -#[cfg(not(feature = "std"))] -fn lock(m: &Mutex) -> spin::MutexGuard<'_, T> { - m.lock() -} +use crate::transform::TransformProfiling; -use crate::buffer::DynBuffer; +#[cfg(feature = "remote")] +use crate::typed_record::json_adapters::JsonReaderAdapter; /// Type alias for a record's type-erased JSON codec (feature `remote`) #[cfg(feature = "remote")] -type RecordCodec = Arc>; +pub(super) type RecordCodec = Arc>; /// Wrapper for a record's latest value with optional serialization. /// @@ -134,352 +100,6 @@ impl core::ops::Deref for RecordValue { } } -/// Adapter that wraps a typed `BufferReader` and serializes values to JSON. -/// -/// Bridges the gap between typed buffers and type-erased JSON streaming for -/// remote access subscriptions. Each receive: -/// 1. Receives one `Stamped` from the buffer -/// 2. Serializes its value through the configured codec -/// 3. Returns either a JSON tree (compatibility API) or owned JSON bytes, -/// with the write metadata of that same sample -/// -/// Used internally by `TypedRecord::subscribe_json()`. -#[cfg(feature = "remote")] -struct JsonReaderAdapter { - /// The underlying typed buffer reader - inner: Box> + Send>, - /// JSON codec (from .with_remote_access()) - codec: RecordCodec, -} - -#[cfg(feature = "remote")] -impl JsonReaderAdapter { - /// Encodes one received sample, keeping its write metadata whole. - fn encode( - &self, - sample: crate::Stamped, - encode: impl FnOnce(&RecordCodec, &T) -> Option, - ) -> Result, crate::DbError> { - sample.as_ref().try_map(|value| { - encode(&self.codec, value) - .ok_or_else(|| crate::DbError::runtime_error("Failed to serialize value to JSON")) - }) - } -} - -#[cfg(feature = "remote")] -impl crate::buffer::JsonBufferReader for JsonReaderAdapter { - fn poll_recv_json( - &mut self, - cx: &mut Context<'_>, - ) -> Poll, crate::DbError>> { - // Poll the inner typed reader (allocation-free), then serialize on the - // ready value — no per-message boxing. - match self.inner.poll_recv(cx) { - Poll::Ready(Ok(sample)) => Poll::Ready(self.encode(sample, |c, v| c.encode(v))), - Poll::Ready(Err(e)) => Poll::Ready(Err(e)), - Poll::Pending => Poll::Pending, - } - } - - fn try_recv_json(&mut self) -> Result, crate::DbError> { - let sample = self.inner.try_recv()?; - self.encode(sample, |c, v| c.encode(v)) - } - - fn poll_recv_json_bytes( - &mut self, - cx: &mut Context<'_>, - ) -> Poll>, crate::DbError>> { - match self.inner.poll_recv(cx) { - Poll::Ready(Ok(sample)) => Poll::Ready(self.encode(sample, |c, v| c.encode_to_vec(v))), - Poll::Ready(Err(error)) => Poll::Ready(Err(error)), - Poll::Pending => Poll::Pending, - } - } - - fn try_recv_json_bytes(&mut self) -> Result>, crate::DbError> { - let sample = self.inner.try_recv()?; - self.encode(sample, |c, v| c.encode_to_vec(v)) - } -} - -// Type alias for boxed futures -pub(crate) type BoxFuture<'a, T> = - core::pin::Pin + Send + 'a>>; - -/// Type alias for consumer service closure stored in TypedRecord -/// Each consumer receives the [`RuntimeContext`](crate::RuntimeContext) and a -/// Consumer handle for subscribing to the buffer -type ConsumerServiceFn = - Box) -> BoxFuture<'static, ()> + Send>; - -/// Type alias for producer service closure stored in TypedRecord -/// Takes (RuntimeContext, Producer) and returns a Future -/// This will be auto-spawned during build(). -/// `Send` only — `Sync` is not required because the closure is taken out of -/// `Mutex>` exactly once via `.take()`, and `Mutex: Sync` -/// already holds when `T: Send`. Matches the consumer-side `ConsumerServiceFn`. -type ProducerServiceFn = - Box) -> BoxFuture<'static, ()> + Send>; - -/// Type-erased trait for records — the storage and lifecycle contract. -/// -/// Allows storage of heterogeneous record types in a single collection -/// while maintaining type safety through downcast operations. -/// -/// This trait carries the storage/lifecycle -/// surface, plus graph/metadata introspection and observability counter -/// resets. JSON remote access is the one genuinely optional capability: it -/// lives in `JsonRecordAccess`, reachable via `json_access`, both behind the -/// `remote` feature. -/// -/// Consumers: `AimDbBuilder::build()` (config-error draining, the dependency -/// graph fed to [`crate::graph`], typed downcasts via [`AnyRecordExt`]), -/// the builder's inbound/outbound route collection, `AimDbInner::list_records` -/// (remote introspection metadata), and connectors applying the remote-access -/// security policy (`set_writable_erased`). -/// -/// # Thread Safety Requirements -/// -/// This trait requires both `Send` and `Sync` because: -/// - Records are stored in `Arc>` and shared across threads -/// - The router system needs to access records from multiple connector tasks -/// - Emitter needs to be `Send+Sync` to work in async contexts -/// - The `FnOnce` consumers are moved out during spawning, so they don't affect `Sync` -/// -/// **BREAKING CHANGE (v0.2.0):** Added `Sync` bound to `AnyRecord` trait. -/// Record types must now be both `Send + Sync`. Types that were previously -/// `Send` but not `Sync` can no longer be used as records. This change enables: -/// - Concurrent access to records from multiple connector tasks -/// - Safe sharing of record metadata across thread boundaries -/// - Type-safe routing in the bidirectional connector system -/// -/// **Migration:** If your record type `T` is not `Sync`, wrap non-`Sync` fields -/// in `Arc>` or `Arc>` to achieve interior mutability with -/// thread-safe sharing. -pub trait AnyRecord: Send + Sync { - /// Returns self as Any for downcasting - fn as_any(&self) -> &dyn Any; - - /// Returns self as mutable Any for downcasting - fn as_any_mut(&mut self) -> &mut dyn Any; - - /// Drains the configuration mistakes recorded during registration, plus - /// build-time consistency findings (e.g. remote access without a buffer). - /// - /// Called by `AimDbBuilder::build()`, which fills in the record key and - /// reports every finding via - /// [`DbError::InvalidConfiguration`](crate::DbError::InvalidConfiguration). - fn drain_config_errors(&mut self) -> Vec; - - /// Sets the writable flag for this record (type-erased) - /// - /// Used internally by the builder to apply security policy to records. - fn set_writable_erased(&self, writable: bool); - - /// Binds the instance clock every write to this record is stamped from. - /// - /// Called by `AimDbBuilder::build()` for every record before any task - /// runs (design 058 §3.3). - fn bind_clock(&mut self, clock: Arc); - - /// Returns the record's JSON remote-access surface, if it has one. - /// - /// This accessor is the single place the `remote` cfg-gate lives - /// for consumers: they query the capability here instead of cfg-gating - /// every call site. `TypedRecord` always returns `Some`; the runtime - /// "configured with `.with_remote_access()`" checks stay inside the - /// [`JsonRecordAccess`] methods. - #[cfg(feature = "remote")] - fn json_access(&self) -> Option<&dyn JsonRecordAccess> { - None - } - - // ── Graph and metadata introspection ──────────────────────────────── - - /// Gets the outbound connector links - /// - /// Returns outbound connector configuration list for spawning logic. - fn outbound_connectors(&self) -> &[crate::connector::ConnectorLink]; - - /// Get the inbound connector links for this record - fn inbound_connectors(&self) -> &[crate::connector::InboundConnectorLink]; - - /// The schema the record carries, if one was set while configuring it - fn schema(&self) -> Option<&crate::graph::SchemaInfo>; - - /// Returns the number of registered consumers (tap observers) - fn consumer_count(&self) -> usize; - - /// Returns whether a producer service is registered - fn has_producer(&self) -> bool; - - /// Returns whether a buffer is configured - fn has_buffer(&self) -> bool; - - /// Returns whether a transform is registered for this record - fn has_transform(&self) -> bool; - - /// Returns how this record gets its values (for dependency graph construction) - fn record_origin(&self) -> crate::graph::RecordOrigin; - - /// Returns the buffer type name and capacity (for dependency graph) - /// - /// Returns (buffer_type_name, optional_capacity). - fn buffer_info(&self) -> (String, Option); - - /// Returns the transform input keys (if a transform is registered) - fn transform_input_keys(&self) -> Option>; - - /// Returns each transform input's key and the type it is read as (empty - /// if no transform is registered). `build()` checks them against the - /// input records' types. - fn transform_input_types(&self) -> Vec<(String, core::any::TypeId, &'static str)>; - - /// Returns the name of the record's value type, for error messages. - fn type_name(&self) -> &'static str; - - /// Collects metadata for this record - #[cfg(feature = "remote")] - fn collect_metadata( - &self, - type_id: core::any::TypeId, - key: crate::record_id::StringKey, - id: crate::record_id::RecordId, - ) -> crate::remote::RecordMetadata; - - // ── Observability counter resets ───────────────────────────────────── - - /// Resets this record's stage profiling counters (feature `observability`). - /// - /// Default implementation is a no-op; `TypedRecord` overrides it. - /// Consumers: `AimDb::reset_profiling`, driven by the AimX - /// `control.reset_buffer_metrics` RPC and the MCP buffer-metrics tool. - #[cfg(feature = "observability")] - fn reset_profiling(&self) {} - - /// Resets this record's buffer introspection counters (feature `observability`). - /// - /// Default implementation is a no-op; `TypedRecord` overrides it. - #[cfg(feature = "observability")] - fn reset_buffer_metrics(&self) {} -} - -/// Type-erased JSON read/subscribe/write for remote access. -/// -/// Internal to the remote-access protocol — application code reads values -/// via `record.latest()?.as_json()` instead. Obtained from a record through -/// [`AnyRecord::json_access`], which is where the `remote` cfg-gate -/// lives for consumers. -/// -/// Consumers: `AimDbInner::try_latest_as_json` / `set_record_from_json` -/// (`record.get` / `record.set`), the AimX session dispatch (`record.subscribe` -/// value drain), and `remote::stream::stream_record_updates`. -#[cfg(feature = "remote")] -pub trait JsonRecordAccess { - /// Returns JSON for type-erased remote access - /// - /// Used internally by remote access protocol. **Users should use `record.latest()?.as_json()`.** - fn latest_json(&self) -> Option>; - - /// Returns owned JSON bytes for type-erased remote access. - /// - /// Existing implementations inherit a compatibility path through - /// [`latest_json`](Self::latest_json), keeping its write metadata. - /// `TypedRecord` overrides this and asks its codec to encode `T` - /// directly. - fn latest_json_bytes(&self) -> Option>> { - crate::buffer::json_tree_to_bytes(self.latest_json()?).ok() - } - - /// Subscribe to record updates as JSON stream - /// - /// Creates a type-erased subscription that emits `serde_json::Value` instead of - /// the concrete type `T`. This enables subscribing to a record without knowing - /// its type at compile time. - /// - /// Used internally by remote access protocol for `record.subscribe` functionality. - /// - /// # Returns - /// - `Ok(Box)` - Successfully created subscription - /// - `Err(DbError)` - If serialization not configured or buffer subscription failed - /// - /// # Errors - /// Returns error if: - /// - Record not configured with `.with_remote_access()` - /// - Buffer subscription fails (shouldn't happen in practice) - fn subscribe_json(&self) -> crate::DbResult>; - - /// Sets a record value from JSON - /// - /// Deserializes JSON and produces the value to the record's buffer. - /// - /// **SAFETY:** This method enforces the "No Producer Override" rule: - /// - Returns error if `producer_count > 0` (prevents overriding application logic) - /// - Only configuration records (no producers) should be settable via remote access - /// - /// Used internally by remote access protocol for `record.set` functionality. - /// - /// # Arguments - /// * `json_value` - JSON representation of the value to set - /// - /// # Returns - /// - `Ok(())` - Successfully set the value - /// - `Err(DbError)` - If deserialization fails, producers exist, or no buffer - /// - /// # Errors - /// Returns error if: - /// - Record has active producers (`producer_count > 0`) - **safety check** - /// - JSON deserialization fails (schema mismatch) - /// - Record not configured with buffer - /// - Record not configured with `.with_remote_access()` - fn set_from_json(&self, json_value: serde_json::Value) -> crate::DbResult<()>; - - /// Sets a record from one complete JSON value encoded as bytes. - /// - /// Existing implementations inherit a parser-backed compatibility path - /// through [`set_from_json`](Self::set_from_json). This accepts the exact - /// record value, not an AimX request/write wrapper; the wire dispatch keeps - /// wrapper extraction on its existing tree path. - fn set_from_json_bytes(&self, bytes: &[u8]) -> crate::DbResult<()> { - let value = serde_json::from_slice(bytes) - .map_err(|_| crate::DbError::runtime_error("Failed to parse JSON value"))?; - self.set_from_json(value) - } -} - -// Helper extension trait for type-safe downcasting -pub trait AnyRecordExt { - /// Attempts to downcast to a typed record reference - /// - /// # Type Parameters - /// * `T` - The expected record type - /// - /// # Returns - /// `Some(&TypedRecord)` if types match, `None` otherwise - fn as_typed(&self) -> Option<&TypedRecord>; - - /// Attempts to downcast to a mutable typed record reference - /// - /// # Type Parameters - /// * `T` - The expected record type - /// - /// # Returns - /// `Some(&mut TypedRecord)` if types match, `None` otherwise - fn as_typed_mut(&mut self) -> Option<&mut TypedRecord>; -} - -impl AnyRecordExt for Box { - fn as_typed(&self) -> Option<&TypedRecord> { - self.as_any().downcast_ref::>() - } - - fn as_typed_mut(&mut self) -> Option<&mut TypedRecord> { - self.as_any_mut().downcast_mut::>() - } -} - /// Helper for collecting all build-time futures for a specific record type. /// /// Captures record type `T` via PhantomData so `AnyRecord` stays object-safe. @@ -558,7 +178,7 @@ pub struct TypedRecord { /// /// Stored as `Arc` (not `Box`) so `Producer` and `Consumer` can hold /// a pre-resolved handle to the same buffer. - buffer: Option>>>, + pub(super) buffer: Option>>>, /// The instance clock, bound by `build()` before any writer exists. clock: Option>, @@ -598,7 +218,7 @@ pub struct TypedRecord { /// subscribe paths route through it. Built from a `SerdeJsonCodec` where /// the `T: RemoteSerialize` bound is known at the call site. #[cfg(feature = "remote")] - remote_codec: Option>, + pub(super) remote_codec: Option>, /// Configuration mistakes recorded during registration instead of /// panicking. Drained by `AimDbBuilder::build()`, which fills @@ -831,6 +451,44 @@ impl TypedRecord { .unwrap_or_default() } + /// Attaches transform profiling for [`Self::collect_transform_futures`]. + /// + /// A join gets its metrics attached to `producer` directly; a single-input + /// transform gets them back as the forwarder's profiling arg. + #[cfg(feature = "observability")] + fn with_transform_profiling( + &self, + mut producer: crate::Producer, + is_single_input: bool, + db: &Arc, + ) -> (crate::Producer, TransformProfiling) { + let profiling_entry = self.profiling.transforms().first(); + if !is_single_input { + // Join: producer cadence is the throughput proxy — attach it directly. + if let Some(entry) = profiling_entry { + producer.set_profiling(entry.metrics.clone(), db.profiling_clock().clone()); + } + } + + let profiling_arg = if is_single_input { + profiling_entry.map(|entry| (entry.metrics.clone(), db.profiling_clock().clone())) + } else { + None + }; + (producer, profiling_arg) + } + + /// No-op without `observability`: returns `producer` unchanged. + #[cfg(not(feature = "observability"))] + fn with_transform_profiling( + &self, + producer: crate::Producer, + _is_single_input: bool, + _db: &Arc, + ) -> (crate::Producer, TransformProfiling) { + (producer, ()) + } + /// Collects the transform task future and any fan-in forwarder futures. /// /// Single-input transforms return one future; join transforms return the @@ -855,32 +513,10 @@ impl TypedRecord { ); // Create Producer bound to a pre-resolved write handle for this record. - #[allow(unused_mut)] - let mut producer = crate::typed_api::Producer::new(self.writer_handle()?); - - #[cfg(feature = "observability")] - let profiling_arg = { - let is_single_input = desc.input_keys.len() == 1; - - let profiling_entry = self.profiling.transforms().first(); - - if !is_single_input { - // Join: producer cadence is the throughput proxy — attach it directly. - if let Some(entry) = profiling_entry { - producer.set_profiling(entry.metrics.clone(), db.profiling_clock().clone()); - } - } - - if is_single_input { - profiling_entry - .map(|entry| (entry.metrics.clone(), db.profiling_clock().clone())) - } else { - None - } - }; - #[cfg(not(feature = "observability"))] - let profiling_arg: crate::transform::TransformProfiling = (); - + let producer = crate::Producer::new(self.writer_handle()?); + let is_single_input = desc.input_keys.len() == 1; + let (producer, profiling_arg) = + self.with_transform_profiling(producer, is_single_input, db); let collected = (desc.build_fn)(producer, db.clone(), record_key, profiling_arg); let mut out = Vec::with_capacity(1 + collected.fanin_futures.len()); @@ -1118,6 +754,34 @@ impl TypedRecord { lock(&self.consumers).len() } + /// Attaches the `i`-th tap's profiling to `consumer`, for + /// [`Self::collect_consumer_futures`]. + #[cfg(feature = "observability")] + fn set_consumers_profiling( + &self, + consumer: &mut crate::Consumer, + i: usize, + db: &crate::AimDb, + ) where + T: Sync, + { + if let Some(entry) = self.profiling.tap(i) { + consumer.set_profiling(entry.metrics.clone(), db.profiling_clock().clone()); + } + } + + /// No-op without `observability`. + #[cfg(not(feature = "observability"))] + fn set_consumers_profiling( + &self, + _consumer: &mut crate::Consumer, + _i: usize, + _db: &crate::AimDb, + ) where + T: Sync, + { + } + /// Collects all registered consumer (`.tap()`) futures. /// /// Consumes registered consumers (FnOnce) — can only be called once. The returned @@ -1161,16 +825,10 @@ impl TypedRecord { )) })?; - #[cfg_attr(not(feature = "observability"), allow(unused_variables))] for (i, consumer_fn) in consumers.into_iter().enumerate() { // Create a Consumer bound to a pre-resolved buffer handle. - #[allow(unused_mut)] let mut consumer = crate::typed_api::Consumer::new(buffer_arc.clone()); - - #[cfg(feature = "observability")] - if let Some(entry) = self.profiling.tap(i) { - consumer.set_profiling(entry.metrics.clone(), db.profiling_clock().clone()); - } + self.set_consumers_profiling(&mut consumer, i, db); futures.push(consumer_fn(db.runtime_ctx(), consumer)); } @@ -1178,6 +836,26 @@ impl TypedRecord { Ok(futures) } + /// Attaches the source's profiling metrics to `producer`, for + /// [`Self::collect_producer_future`]. + #[cfg(feature = "observability")] + fn set_source_profiling(&self, producer: &mut crate::Producer, db: &Arc) + where + T: Sync, + { + if let Some(entry) = self.profiling.source(0) { + producer.set_profiling(entry.metrics.clone(), db.profiling_clock().clone()); + } + } + + /// No-op without `observability`. + #[cfg(not(feature = "observability"))] + fn set_source_profiling(&self, _producer: &mut crate::Producer, _db: &Arc) + where + T: Sync, + { + } + /// Collects the producer-service future, if one is registered. pub fn collect_producer_future( &self, @@ -1200,13 +878,8 @@ impl TypedRecord { let _ = record_key; // Create Producer bound to a pre-resolved write handle for this record. - #[allow(unused_mut)] let mut producer = crate::typed_api::Producer::new(self.writer_handle()?); - - #[cfg(feature = "observability")] - if let Some(entry) = self.profiling.source(0) { - producer.set_profiling(entry.metrics.clone(), db.profiling_clock().clone()); - } + self.set_source_profiling(&mut producer, db); Ok(Some(service_fn(db.runtime_ctx(), producer))) } else { @@ -1250,6 +923,32 @@ impl TypedRecord { Some(RecordValue::new(sample, None)) } } + + /// The build error for a remote-access record without a buffer, for + /// [`AnyRecord::drain_config_errors`]. + /// + /// A remote-access record has no fallback storage — reads/writes go + /// straight to the buffer. With no buffer, `record.get`/`latest()` return + /// not_found and `record.set` silently discards the value. Fail at build() + /// so the buffer is added explicitly instead of surfacing as a silent + /// runtime no-op. + #[cfg(feature = "remote")] + fn missing_remote_buffer_error(&self) -> Option { + (self.remote_codec.is_some() && !self.has_buffer()).then(|| { + crate::error::ConfigError::new( + "", + None, + "record has .with_remote_access() but no buffer; \ + add a buffer (e.g. .buffer(BufferCfg::SingleLatest)) so record.get/set work", + ) + }) + } + + /// No-op without `remote`. + #[cfg(not(feature = "remote"))] + fn missing_remote_buffer_error(&self) -> Option { + None + } } impl Default for TypedRecord { @@ -1276,24 +975,8 @@ impl AnyRecord for TypedRecord { } fn drain_config_errors(&mut self) -> Vec { - #[allow(unused_mut)] let mut errors = core::mem::take(&mut self.config_errors); - - // A remote-access record has no fallback storage — reads/writes go - // straight to the buffer. With - // no buffer, `record.get`/`latest()` return not_found and `record.set` - // silently discards the value. Fail at build() so the buffer is added - // explicitly instead of surfacing as a silent runtime no-op. - #[cfg(feature = "remote")] - if self.remote_codec.is_some() && !self.has_buffer() { - errors.push(crate::error::ConfigError::new( - "", - None, - "record has .with_remote_access() but no buffer; \ - add a buffer (e.g. .buffer(BufferCfg::SingleLatest)) so record.get/set work", - )); - } - + errors.extend(self.missing_remote_buffer_error()); errors } @@ -1511,10 +1194,7 @@ impl JsonRecordAccess for TypedRecord< .ok_or_else(|| DbError::missing_configuration("buffer"))?; // 3. Wrap in JsonReaderAdapter - let json_reader = JsonReaderAdapter { - inner: buffer.subscribe_boxed(), - codec, - }; + let json_reader = JsonReaderAdapter::new(buffer.subscribe_boxed(), codec); log_debug!( "Successfully created JSON subscription for type: {}", @@ -1565,176 +1245,3 @@ impl JsonRecordAccess for TypedRecord< self.commit_remote_write(value) } } - -#[cfg(all(test, feature = "remote"))] -mod tests { - use super::*; - use core::sync::atomic::{AtomicUsize, Ordering}; - - use crate::buffer::{BufferReader, DynBuffer}; - use crate::codec::JsonCodec; - use crate::{Stamp, Stamped, WriteMetadata}; - - /// A sample whose stamp equals its value. - fn sample(v: u32) -> Stamped { - Stamped::new(v, WriteMetadata::new(Stamp::from_nanos(u64::from(v)))) - } - - struct OneReader(Option>); - - impl BufferReader> for OneReader { - fn poll_recv( - &mut self, - _cx: &mut Context<'_>, - ) -> Poll, crate::DbError>> { - Poll::Ready(self.try_recv()) - } - - fn try_recv(&mut self) -> Result, crate::DbError> { - self.0.take().ok_or(crate::DbError::BufferEmpty) - } - } - - struct PeekBuffer(u32); - - impl DynBuffer> for PeekBuffer { - fn push(&self, _value: Stamped) {} - - fn subscribe_boxed(&self) -> Box> + Send> { - Box::new(OneReader(Some(sample(self.0)))) - } - - fn as_any(&self) -> &dyn Any { - self - } - - fn peek(&self) -> Option> { - Some(sample(self.0)) - } - } - - struct TrackingCodec { - tree_calls: Arc, - byte_calls: Arc, - } - - impl JsonCodec for TrackingCodec { - fn encode(&self, value: &u32) -> Option { - self.tree_calls.fetch_add(1, Ordering::Relaxed); - Some(serde_json::json!(value)) - } - - fn decode(&self, value: &serde_json::Value) -> Option { - value.as_u64()?.try_into().ok() - } - - fn encode_to_vec(&self, value: &u32) -> Option> { - self.byte_calls.fetch_add(1, Ordering::Relaxed); - serde_json::to_vec(value).ok() - } - } - - /// A buffer where every `peek` sees a newer write: value and stamp both - /// equal the number of peeks so far. - struct AdvancingBuffer(core::sync::atomic::AtomicU32); - - impl DynBuffer> for AdvancingBuffer { - fn push(&self, _value: Stamped) {} - - fn subscribe_boxed(&self) -> Box> + Send> { - Box::new(OneReader(None)) - } - - fn as_any(&self) -> &dyn Any { - self - } - - fn peek(&self) -> Option> { - Some(sample(self.0.fetch_add(1, Ordering::SeqCst) + 1)) - } - } - - /// Design 058 §4.4: payload and stamp come from one buffer read. A path - /// that peeked twice would pair a value with a newer write's stamp. - #[test] - fn json_reads_take_payload_and_stamp_from_one_read() { - let mut record = TypedRecord::::new(); - record.with_remote_access(); - record.buffer = Some(Arc::new(AdvancingBuffer( - core::sync::atomic::AtomicU32::new(0), - ))); - - let tree = record.latest_json().unwrap(); - assert_eq!(tree.stamp(), Stamp::from_nanos(1)); - assert_eq!(tree.value, serde_json::json!(1)); - - let bytes = record.latest_json_bytes().unwrap(); - assert_eq!(bytes.stamp(), Stamp::from_nanos(2)); - assert_eq!(bytes.value, b"2"); - - let latest = record.latest().unwrap(); - assert_eq!((*latest.get(), latest.stamp()), (3, Stamp::from_nanos(3))); - } - - #[test] - fn typed_latest_and_subscription_select_the_codec_byte_path() { - let tree_calls = Arc::new(AtomicUsize::new(0)); - let byte_calls = Arc::new(AtomicUsize::new(0)); - let codec: RecordCodec = Arc::new(TrackingCodec { - tree_calls: tree_calls.clone(), - byte_calls: byte_calls.clone(), - }); - - let mut record = TypedRecord::::new(); - record.remote_codec = Some(codec); - record.buffer = Some(Arc::new(PeekBuffer(17))); - - // Payloads are the codec's output for `T` alone; each carries the - // stamp of the sample it was encoded from. - let latest = record.latest_json_bytes().unwrap(); - assert_eq!( - (latest.value.as_slice(), latest.stamp()), - (&b"17"[..], Stamp::from_nanos(17)) - ); - - let mut reader = record.subscribe_json().unwrap(); - let received = reader.try_recv_json_bytes().unwrap(); - assert_eq!( - (received.value.as_slice(), received.stamp()), - (&b"17"[..], Stamp::from_nanos(17)) - ); - - assert_eq!(byte_calls.load(Ordering::Relaxed), 2); - assert_eq!(tree_calls.load(Ordering::Relaxed), 0); - - let tree = record.latest_json().unwrap(); - assert_eq!( - (tree.stamp(), tree.value), - (Stamp::from_nanos(17), serde_json::json!(17)) - ); - assert_eq!(tree_calls.load(Ordering::Relaxed), 1); - } - - #[test] - fn remote_write_rejection_is_typed() { - use events::{capture, RemoteWriteEvent}; - let mut record = TypedRecord::::new(); - record.with_remote_access(); - record.set_producer(|_, _| async {}); - let seen = Arc::new(core::sync::atomic::AtomicBool::new(false)); - let observer = { - let seen = seen.clone(); - Arc::new(move |event: &RemoteWriteEvent<'_>| { - let RemoteWriteEvent::Rejected { - operation, - record_type, - } = event; - assert_eq!(*operation, "set_from_json"); - assert_eq!(*record_type, core::any::type_name::()); - seen.store(true, core::sync::atomic::Ordering::Relaxed); - }) - }; - assert!(capture::with(observer, || record.set_from_json(serde_json::json!(7))).is_err()); - assert!(seen.load(core::sync::atomic::Ordering::Relaxed)); - } -} diff --git a/aimdb-data-contracts/tests/compile-fail-links/input_wrong_direction.stderr b/aimdb-data-contracts/tests/compile-fail-links/input_wrong_direction.stderr index bc6c63e1..7dee5a1b 100644 --- a/aimdb-data-contracts/tests/compile-fail-links/input_wrong_direction.stderr +++ b/aimdb-data-contracts/tests/compile-fail-links/input_wrong_direction.stderr @@ -9,19 +9,19 @@ error[E0277]: `OutboundLinkBuilder` cannot be the input of a `Te = help: the trait `aimdb_core::Input` is not implemented for `OutboundLinkBuilder` = note: an input implements `Input`; device inputs usually do so for every `T: From` help: the following other types implement trait `aimdb_core::Input` - --> $WORKSPACE/aimdb-core/src/typed_api.rs + --> $WORKSPACE/aimdb-core/src/typed_api/link_inbound.rs | - | / impl Input for InboundLink + | / impl Input for ContractInboundLink | | where | | T: Send + Sync + 'static + Debug + Clone, - | |_____________________________________________^ `InboundLinkBuilder` + | |_____________________________________________^ `InboundLinkBuilder` ... - | / impl Input for ContractInboundLink + | / impl Input for InboundLink | | where | | T: Send + Sync + 'static + Debug + Clone, - | |_____________________________________________^ `InboundLinkBuilder` + | |_____________________________________________^ `InboundLinkBuilder` note: required by a bound in `RecordRegistrar::<'a, T, S>::input` - --> $WORKSPACE/aimdb-core/src/typed_api.rs + --> $WORKSPACE/aimdb-core/src/typed_api/registrar.rs | | pub fn input(&mut self, input: impl Input) -> &mut Self { | ^^^^^^^^^^^ required by this bound in `RecordRegistrar::<'a, T, S>::input` diff --git a/aimdb-data-contracts/tests/compile-fail-links/output_wrong_record.stderr b/aimdb-data-contracts/tests/compile-fail-links/output_wrong_record.stderr index ff78993d..494c870b 100644 --- a/aimdb-data-contracts/tests/compile-fail-links/output_wrong_record.stderr +++ b/aimdb-data-contracts/tests/compile-fail-links/output_wrong_record.stderr @@ -8,19 +8,19 @@ error[E0277]: `OutboundLinkBuilder` cannot be an output of a `Ot | = help: the trait `aimdb_core::Output` is not implemented for `OutboundLinkBuilder` help: the following other types implement trait `aimdb_core::Output` - --> $WORKSPACE/aimdb-core/src/typed_api.rs + --> $WORKSPACE/aimdb-core/src/typed_api/link_outbound.rs | - | / impl Output for OutboundLink + | / impl Output for ContractOutboundLink | | where | | T: Send + Sync + 'static + Debug + Clone, - | |_____________________________________________^ `OutboundLinkBuilder` + | |_____________________________________________^ `OutboundLinkBuilder` ... - | / impl Output for ContractOutboundLink + | / impl Output for OutboundLink | | where | | T: Send + Sync + 'static + Debug + Clone, - | |_____________________________________________^ `OutboundLinkBuilder` + | |_____________________________________________^ `OutboundLinkBuilder` note: required by a bound in `RecordRegistrar::<'a, T, S>::output` - --> $WORKSPACE/aimdb-core/src/typed_api.rs + --> $WORKSPACE/aimdb-core/src/typed_api/registrar.rs | | pub fn output(&mut self, output: impl Output) -> &mut Self { | ^^^^^^^^^^^^ required by this bound in `RecordRegistrar::<'a, T, S>::output` diff --git a/aimdb-data-contracts/tests/compile-fail/typed_key_contract_verbs_on_name.stderr b/aimdb-data-contracts/tests/compile-fail/typed_key_contract_verbs_on_name.stderr index 133090b3..4e2797ed 100644 --- a/aimdb-data-contracts/tests/compile-fail/typed_key_contract_verbs_on_name.stderr +++ b/aimdb-data-contracts/tests/compile-fail/typed_key_contract_verbs_on_name.stderr @@ -77,7 +77,7 @@ help: the trait `ContractDeclared` is implemented for `Declared` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ = note: required for `OutboundLinkBuilder` to implement `aimdb_core::Output` note: required by a bound in `RecordRegistrar::<'a, T, S>::output` - --> $WORKSPACE/aimdb-core/src/typed_api.rs + --> $WORKSPACE/aimdb-core/src/typed_api/registrar.rs | | pub fn output(&mut self, output: impl Output) -> &mut Self { | ^^^^^^^^^^^^ required by this bound in `RecordRegistrar::<'a, T, S>::output` @@ -98,7 +98,7 @@ help: the trait `ContractDeclared` is implemented for `Declared` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ = note: required for `InboundLinkBuilder` to implement `aimdb_core::Input` note: required by a bound in `RecordRegistrar::<'a, T, S>::input` - --> $WORKSPACE/aimdb-core/src/typed_api.rs + --> $WORKSPACE/aimdb-core/src/typed_api/registrar.rs | | pub fn input(&mut self, input: impl Input) -> &mut Self { | ^^^^^^^^^^^ required by this bound in `RecordRegistrar::<'a, T, S>::input` diff --git a/aimdb-data-contracts/tests/compile-fail/typed_key_payload_access.stderr b/aimdb-data-contracts/tests/compile-fail/typed_key_payload_access.stderr index 063d8874..1297d89a 100644 --- a/aimdb-data-contracts/tests/compile-fail/typed_key_payload_access.stderr +++ b/aimdb-data-contracts/tests/compile-fail/typed_key_payload_access.stderr @@ -75,7 +75,7 @@ error[E0631]: type mismatch in closure arguments = note: expected closure signature `for<'a> fn(RuntimeContext, &'a V2) -> _` found closure signature `fn(RuntimeContext, &V1) -> _` note: required by a bound in `OutboundLinkBuilder::::with_serializer` - --> $WORKSPACE/aimdb-core/src/typed_api.rs + --> $WORKSPACE/aimdb-core/src/typed_api/link_outbound.rs | | pub fn with_serializer(mut self, f: F) -> Self | --------------- required by a bound in this associated function