Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 0 additions & 3 deletions aimdb-core/src/typed_api/link_inbound.rs
Original file line number Diff line number Diff line change
Expand Up @@ -427,6 +427,3 @@ where
reg.push_inbound(self);
}
}

#[cfg(test)]
mod tests {}
3 changes: 2 additions & 1 deletion aimdb-core/src/typed_api/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,8 @@ pub struct DetachedContract;
///
/// - **An input yields an event, and records are built with `From`.** A
/// device input implements `Input<T>` for every `T: From<Event>`, 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`.
///
Expand Down
45 changes: 38 additions & 7 deletions aimdb-core/src/typed_api/registrar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,40 @@ use crate::typed_api::{
use crate::typed_record::TypedRecord;
use crate::AimDb;

/// Builds the [`Consumer<T>`] an outbound link reads from, timed against the
/// link's profiling stage.
#[cfg(feature = "observability")]
fn link_consumer<T>(
buffer: Arc<dyn crate::buffer::DynBuffer<crate::Stamped<T>>>,
link_metrics: &Arc<crate::profiling::StageMetrics>,
db: &AimDb,
) -> Consumer<T>
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<T>(
buffer: Arc<dyn crate::buffer::DynBuffer<crate::Stamped<T>>>,
_link_metrics: &NoLinkMetrics,
_db: &AimDb,
) -> Consumer<T>
where
T: Send + Sync + 'static + Debug + Clone,
{
Consumer::new(buffer)
}

// ============================================================================
// RecordRegistrar - Fluent registration API
// ============================================================================
Expand Down Expand Up @@ -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<T>` bound to its buffer
// handle, once per route (not per message) — same pattern as the
Expand Down Expand Up @@ -590,11 +625,7 @@ where
)
});

#[allow(unused_mut)]
let mut consumer = Consumer::<T>::new(buffer);
#[cfg(feature = "observability")]
consumer.set_profiling(link_metrics.clone(), db.profiling_clock().clone());
consumer
link_consumer(buffer, &link_metrics, db)
})
};

Expand Down
180 changes: 3 additions & 177 deletions aimdb-core/src/typed_record/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<T> handle for subscribing to the buffer
pub(super) type ConsumerServiceFn<T> =
pub(in crate::typed_record) type ConsumerServiceFn<T> =
Box<dyn FnOnce(crate::RuntimeContext, crate::Consumer<T>) -> BoxFuture<'static, ()> + Send>;

/// Type alias for producer service closure stored in TypedRecord
Expand All @@ -70,182 +70,8 @@ pub(super) type ConsumerServiceFn<T> =
/// `Send` only — `Sync` is not required because the closure is taken out of
/// `Mutex<Option<...>>` exactly once via `.take()`, and `Mutex<T>: Sync`
/// already holds when `T: Send`. Matches the consumer-side `ConsumerServiceFn`.
pub(super) type ProducerServiceFn<T> =
pub(in crate::typed_record) type ProducerServiceFn<T> =
Box<dyn FnOnce(crate::RuntimeContext, crate::Producer<T>) -> 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<u32> {
Stamped::new(v, WriteMetadata::new(Stamp::from_nanos(u64::from(v))))
}

struct OneReader(Option<Stamped<u32>>);

impl BufferReader<Stamped<u32>> for OneReader {
fn poll_recv(
&mut self,
_cx: &mut Context<'_>,
) -> Poll<Result<Stamped<u32>, crate::DbError>> {
Poll::Ready(self.try_recv())
}

fn try_recv(&mut self) -> Result<Stamped<u32>, crate::DbError> {
self.0.take().ok_or(crate::DbError::BufferEmpty)
}
}

struct PeekBuffer(u32);

impl DynBuffer<Stamped<u32>> for PeekBuffer {
fn push(&self, _value: Stamped<u32>) {}

fn subscribe_boxed(&self) -> Box<dyn BufferReader<Stamped<u32>> + Send> {
Box::new(OneReader(Some(sample(self.0))))
}

fn as_any(&self) -> &dyn Any {
self
}

fn peek(&self) -> Option<Stamped<u32>> {
Some(sample(self.0))
}
}

struct TrackingCodec {
tree_calls: Arc<AtomicUsize>,
byte_calls: Arc<AtomicUsize>,
}

impl JsonCodec<u32> for TrackingCodec {
fn encode(&self, value: &u32) -> Option<serde_json::Value> {
self.tree_calls.fetch_add(1, Ordering::Relaxed);
Some(serde_json::json!(value))
}

fn decode(&self, value: &serde_json::Value) -> Option<u32> {
value.as_u64()?.try_into().ok()
}

fn encode_to_vec(&self, value: &u32) -> Option<Vec<u8>> {
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<Stamped<u32>> for AdvancingBuffer {
fn push(&self, _value: Stamped<u32>) {}

fn subscribe_boxed(&self) -> Box<dyn BufferReader<Stamped<u32>> + Send> {
Box::new(OneReader(None))
}

fn as_any(&self) -> &dyn Any {
self
}

fn peek(&self) -> Option<Stamped<u32>> {
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::<u32>::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<u32> = Arc::new(TrackingCodec {
tree_calls: tree_calls.clone(),
byte_calls: byte_calls.clone(),
});

let mut record = TypedRecord::<u32>::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::<u32>::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::<u32>());
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;
12 changes: 4 additions & 8 deletions aimdb-core/src/typed_record/record.rs
Original file line number Diff line number Diff line change
Expand Up @@ -757,12 +757,8 @@ impl<T: Send + 'static + Debug + Clone> TypedRecord<T> {
/// 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<T>,
i: usize,
db: &crate::AimDb,
) where
fn set_consumer_profiling(&self, consumer: &mut crate::Consumer<T>, i: usize, db: &crate::AimDb)
where
T: Sync,
{
if let Some(entry) = self.profiling.tap(i) {
Expand All @@ -772,7 +768,7 @@ impl<T: Send + 'static + Debug + Clone> TypedRecord<T> {

/// No-op without `observability`.
#[cfg(not(feature = "observability"))]
fn set_consumers_profiling(
fn set_consumer_profiling(
&self,
_consumer: &mut crate::Consumer<T>,
_i: usize,
Expand Down Expand Up @@ -828,7 +824,7 @@ impl<T: Send + 'static + Debug + Clone> TypedRecord<T> {
for (i, consumer_fn) in consumers.into_iter().enumerate() {
// Create a Consumer<T> 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));
}
Expand Down
Loading