From 45b869e32f348e96578ad63c636d863589116e1b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 19:43:10 +0000 Subject: [PATCH 1/3] feat(cli): show the record key in aimdb record list Add a Key column as the first column of the record list table, so the list shows what to pass to aimdb record get / set and aimdb watch. The Name column (the Rust type name) stays beside it. Closes #455 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WGkDJAA2rC3Yn2KLShtuvP --- tools/aimdb-cli/CHANGELOG.md | 5 +++++ tools/aimdb-cli/README.md | 24 +++++++++++++----------- tools/aimdb-cli/src/output/table.rs | 26 ++++++++++++++------------ 3 files changed, 32 insertions(+), 23 deletions(-) diff --git a/tools/aimdb-cli/CHANGELOG.md b/tools/aimdb-cli/CHANGELOG.md index 9861bb4e..bcba3d34 100644 --- a/tools/aimdb-cli/CHANGELOG.md +++ b/tools/aimdb-cli/CHANGELOG.md @@ -9,6 +9,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- **`aimdb record list` shows a `Key` column (#455)** as its first column: + the record key that `aimdb record get` / `set` and `aimdb watch` take. The + `Name` column (the Rust type name) stays beside it. JSON output is + unchanged: it already carries `record_key`. + - **`aimdb record list` shows a `Schema` column** with the record's declared data contract (`name vN`, `-` when none), as the graph table already does. JSON output is unchanged: it already carries `schema_type` / diff --git a/tools/aimdb-cli/README.md b/tools/aimdb-cli/README.md index f237e73a..51055708 100644 --- a/tools/aimdb-cli/README.md +++ b/tools/aimdb-cli/README.md @@ -47,17 +47,19 @@ aimdb record list Example output: ``` -┌─────────────────────┬────────────────────────────────────────────┬────────────────┬───────────────┬───────────┬───────────┬──────────┬────────┐ -│ Name │ Type ID │ Schema │ Buffer Type │ Producers │ Consumers │ Writable │ Signal │ -├─────────────────────┼────────────────────────────────────────────┼────────────────┼───────────────┼───────────┼───────────┼──────────┼────────┤ -│ server::Temperature │ TypeId(0xaee15e261d918c67cee5a96c2f604ce0) │ temperature v2 │ single_latest │ 1 │ 2 │ no │ - │ -├─────────────────────┼────────────────────────────────────────────┼────────────────┼───────────────┼───────────┼───────────┼──────────┼────────┤ -│ server::Config │ TypeId(0xc2af5c8376864a24e916c87f88505fac) │ - │ mailbox │ 0 │ 3 │ yes │ - │ -└─────────────────────┴────────────────────────────────────────────┴────────────────┴───────────────┴───────────┴───────────┴──────────┴────────┘ -``` - -`Schema` is the record's declared data contract (`name vN`), or `-` when the -record was configured without one. `--format json` carries it as +┌─────────────────────┬─────────────────────┬────────────────────────────────────────────┬────────────────┬───────────────┬───────────┬───────────┬──────────┬────────┐ +│ Key │ Name │ Type ID │ Schema │ Buffer Type │ Producers │ Consumers │ Writable │ Signal │ +├─────────────────────┼─────────────────────┼────────────────────────────────────────────┼────────────────┼───────────────┼───────────┼───────────┼──────────┼────────┤ +│ server::Temperature │ server::Temperature │ TypeId(0xaee15e261d918c67cee5a96c2f604ce0) │ temperature v2 │ single_latest │ 1 │ 2 │ no │ - │ +├─────────────────────┼─────────────────────┼────────────────────────────────────────────┼────────────────┼───────────────┼───────────┼───────────┼──────────┼────────┤ +│ server::Config │ server::Config │ TypeId(0xc2af5c8376864a24e916c87f88505fac) │ - │ mailbox │ 0 │ 3 │ yes │ - │ +└─────────────────────┴─────────────────────┴────────────────────────────────────────────┴────────────────┴───────────────┴───────────┴───────────┴──────────┴────────┘ +``` + +`Key` is the record key that `aimdb record get`, `aimdb record set` and +`aimdb watch` take; `Name` is the record's Rust type name, which can differ +from the key. `Schema` is the record's declared data contract (`name vN`), or +`-` when the record was configured without one. `--format json` carries it as `schema_type` / `schema_version`. ### 3. Get Current Record Value diff --git a/tools/aimdb-cli/src/output/table.rs b/tools/aimdb-cli/src/output/table.rs index ce13c061..af9c6e15 100644 --- a/tools/aimdb-cli/src/output/table.rs +++ b/tools/aimdb-cli/src/output/table.rs @@ -50,6 +50,7 @@ pub fn format_records_table(records: &[RecordMetadata]) -> String { // Add header builder.push_record(vec![ + "Key", "Name", "Type ID", "Schema", @@ -98,6 +99,7 @@ pub fn format_records_table(records: &[RecordMetadata]) -> String { .unwrap_or_else(|| "-".dimmed().to_string()); builder.push_record(vec![ + record.record_key.clone(), record.name.clone(), record.type_id.clone(), schema_str, @@ -608,13 +610,13 @@ Permissions: assert_eq!( table, "\ -┌─────────────┬──────────────────┬────────────────┬─────────────┬───────────┬───────────┬──────────┬───────────────────────────────┐ -│ Name │ Type ID │ Schema │ Buffer Type │ Producers │ Consumers │ Writable │ Signal │ -├─────────────┼──────────────────┼────────────────┼─────────────┼───────────┼───────────┼──────────┼───────────────────────────────┤ -│ Temperature │ type-temperature │ temperature v2 │ spmc_ring │ 1 │ 2 │ no │ 21.5 C (18..24, avg 20.25) +1 │ -├─────────────┼──────────────────┼────────────────┼─────────────┼───────────┼───────────┼──────────┼───────────────────────────────┤ -│ Config │ type-config │ - │ mailbox │ 0 │ 3 │ yes │ - │ -└─────────────┴──────────────────┴────────────────┴─────────────┴───────────┴───────────┴──────────┴───────────────────────────────┘" +┌────────────────────┬─────────────┬──────────────────┬────────────────┬─────────────┬───────────┬───────────┬──────────┬───────────────────────────────┐ +│ Key │ Name │ Type ID │ Schema │ Buffer Type │ Producers │ Consumers │ Writable │ Signal │ +├────────────────────┼─────────────┼──────────────────┼────────────────┼─────────────┼───────────┼───────────┼──────────┼───────────────────────────────┤ +│ sensor.temperature │ Temperature │ type-temperature │ temperature v2 │ spmc_ring │ 1 │ 2 │ no │ 21.5 C (18..24, avg 20.25) +1 │ +├────────────────────┼─────────────┼──────────────────┼────────────────┼─────────────┼───────────┼───────────┼──────────┼───────────────────────────────┤ +│ app.config │ Config │ type-config │ - │ mailbox │ 0 │ 3 │ yes │ - │ +└────────────────────┴─────────────┴──────────────────┴────────────────┴─────────────┴───────────┴───────────┴──────────┴───────────────────────────────┘" ); } @@ -656,11 +658,11 @@ Permissions: assert_eq!( table, "\ -┌──────┬───────────┬────────┬───────────────┬───────────┬───────────┬──────────┬──────────────────────────┐ -│ Name │ Type ID │ Schema │ Buffer Type │ Producers │ Consumers │ Writable │ Signal │ -├──────┼───────────┼────────┼───────────────┼───────────┼───────────┼──────────┼──────────────────────────┤ -│ Load │ type-load │ - │ single_latest │ 1 │ 0 │ no │ 0.75 (0.5..1, avg 0.625) │ -└──────┴───────────┴────────┴───────────────┴───────────┴───────────┴──────────┴──────────────────────────┘" +┌─────────────┬──────┬───────────┬────────┬───────────────┬───────────┬───────────┬──────────┬──────────────────────────┐ +│ Key │ Name │ Type ID │ Schema │ Buffer Type │ Producers │ Consumers │ Writable │ Signal │ +├─────────────┼──────┼───────────┼────────┼───────────────┼───────────┼───────────┼──────────┼──────────────────────────┤ +│ system.load │ Load │ type-load │ - │ single_latest │ 1 │ 0 │ no │ 0.75 (0.5..1, avg 0.625) │ +└─────────────┴──────┴───────────┴────────┴───────────────┴───────────┴───────────┴──────────┴──────────────────────────┘" ); } From a9dceeb8cbd6c508cdae0a9d0cde6199d6b89451 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 19:50:22 +0000 Subject: [PATCH 2/3] fix(core): tidy two leftovers from the typed_api split (#500) Restore the line break between the two bullets in the Input docs, so rustdoc renders them as separate list items, and drop the empty test module left in typed_api/link_inbound.rs. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WGkDJAA2rC3Yn2KLShtuvP --- aimdb-core/src/typed_api/link_inbound.rs | 3 --- aimdb-core/src/typed_api/mod.rs | 3 ++- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/aimdb-core/src/typed_api/link_inbound.rs b/aimdb-core/src/typed_api/link_inbound.rs index 172ff7a5..bbf49f6e 100644 --- a/aimdb-core/src/typed_api/link_inbound.rs +++ b/aimdb-core/src/typed_api/link_inbound.rs @@ -427,6 +427,3 @@ where reg.push_inbound(self); } } - -#[cfg(test)] -mod tests {} diff --git a/aimdb-core/src/typed_api/mod.rs b/aimdb-core/src/typed_api/mod.rs index e4482c08..fe318475 100644 --- a/aimdb-core/src/typed_api/mod.rs +++ b/aimdb-core/src/typed_api/mod.rs @@ -110,7 +110,8 @@ pub struct DetachedContract; /// /// - **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 +/// 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`. /// From 3a08c1ded1eeafd2056e3382ab83d4a9f07a5002 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 19:55:10 +0000 Subject: [PATCH 3/3] refactor(core): optional cleanups after the typed_api split (#500) - Rename TypedRecord::set_consumers_profiling to set_consumer_profiling; it attaches profiling to a single consumer. - Move typed_record's inline tests into typed_record/tests.rs, as typed_api/tests/ and session/client/tests.rs already do. - Replace the #[allow(unused_mut)] in the outbound-link consumer factory with a link_consumer helper that has an observability variant and a no-op variant. - Narrow ConsumerServiceFn / ProducerServiceFn from pub(super) to pub(in crate::typed_record). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WGkDJAA2rC3Yn2KLShtuvP --- aimdb-core/src/typed_api/registrar.rs | 45 ++++++- aimdb-core/src/typed_record/mod.rs | 180 +------------------------- aimdb-core/src/typed_record/record.rs | 12 +- aimdb-core/src/typed_record/tests.rs | 170 ++++++++++++++++++++++++ 4 files changed, 215 insertions(+), 192 deletions(-) create mode 100644 aimdb-core/src/typed_record/tests.rs diff --git a/aimdb-core/src/typed_api/registrar.rs b/aimdb-core/src/typed_api/registrar.rs index 150f1322..8dd39f88 100644 --- a/aimdb-core/src/typed_api/registrar.rs +++ b/aimdb-core/src/typed_api/registrar.rs @@ -20,6 +20,40 @@ use crate::typed_api::{ use crate::typed_record::TypedRecord; use crate::AimDb; +/// Builds the [`Consumer`] an outbound link reads from, timed against the +/// link's profiling stage. +#[cfg(feature = "observability")] +fn link_consumer( + buffer: Arc>>, + link_metrics: &Arc, + db: &AimDb, +) -> Consumer +where + T: Send + Sync + 'static + Debug + Clone, +{ + let mut consumer = Consumer::new(buffer); + consumer.set_profiling(link_metrics.clone(), db.profiling_clock().clone()); + consumer +} + +/// Stands in for a link's stage metrics without `observability`. +#[cfg(not(feature = "observability"))] +#[derive(Clone, Copy)] +struct NoLinkMetrics; + +/// Without `observability` there is no stage to time: a plain consumer. +#[cfg(not(feature = "observability"))] +fn link_consumer( + buffer: Arc>>, + _link_metrics: &NoLinkMetrics, + _db: &AimDb, +) -> Consumer +where + T: Send + Sync + 'static + Debug + Clone, +{ + Consumer::new(buffer) +} + // ============================================================================ // RecordRegistrar - Fluent registration API // ============================================================================ @@ -556,9 +590,10 @@ where metrics }; #[cfg(not(feature = "observability"))] - { + let link_metrics = { self.last_stage = Some((StageKind::Link, 0)); - } + NoLinkMetrics + }; // Resolves the record and builds a `Consumer` bound to its buffer // handle, once per route (not per message) — same pattern as the @@ -590,11 +625,7 @@ where ) }); - #[allow(unused_mut)] - let mut consumer = Consumer::::new(buffer); - #[cfg(feature = "observability")] - consumer.set_profiling(link_metrics.clone(), db.profiling_clock().clone()); - consumer + link_consumer(buffer, &link_metrics, db) }) }; diff --git a/aimdb-core/src/typed_record/mod.rs b/aimdb-core/src/typed_record/mod.rs index e6de5c86..a3e9eb42 100644 --- a/aimdb-core/src/typed_record/mod.rs +++ b/aimdb-core/src/typed_record/mod.rs @@ -61,7 +61,7 @@ pub(crate) type BoxFuture<'a, T> = /// 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 = +pub(in crate::typed_record) type ConsumerServiceFn = Box) -> BoxFuture<'static, ()> + Send>; /// Type alias for producer service closure stored in TypedRecord @@ -70,182 +70,8 @@ pub(super) type ConsumerServiceFn = /// `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 = +pub(in crate::typed_record) 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)); - } -} +mod tests; diff --git a/aimdb-core/src/typed_record/record.rs b/aimdb-core/src/typed_record/record.rs index c3953a8e..683eae62 100644 --- a/aimdb-core/src/typed_record/record.rs +++ b/aimdb-core/src/typed_record/record.rs @@ -757,12 +757,8 @@ impl TypedRecord { /// 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 + fn set_consumer_profiling(&self, consumer: &mut crate::Consumer, i: usize, db: &crate::AimDb) + where T: Sync, { if let Some(entry) = self.profiling.tap(i) { @@ -772,7 +768,7 @@ impl TypedRecord { /// No-op without `observability`. #[cfg(not(feature = "observability"))] - fn set_consumers_profiling( + fn set_consumer_profiling( &self, _consumer: &mut crate::Consumer, _i: usize, @@ -828,7 +824,7 @@ impl TypedRecord { for (i, consumer_fn) in consumers.into_iter().enumerate() { // Create a Consumer bound to a pre-resolved buffer handle. let mut consumer = crate::typed_api::Consumer::new(buffer_arc.clone()); - self.set_consumers_profiling(&mut consumer, i, db); + self.set_consumer_profiling(&mut consumer, i, db); futures.push(consumer_fn(db.runtime_ctx(), consumer)); } diff --git a/aimdb-core/src/typed_record/tests.rs b/aimdb-core/src/typed_record/tests.rs new file mode 100644 index 00000000..1ade43b6 --- /dev/null +++ b/aimdb-core/src/typed_record/tests.rs @@ -0,0 +1,170 @@ +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)); +}