Skip to main content

aimdb_core/buffer/
traits.rs

1//! Runtime-agnostic buffer traits
2//!
3//! Defines `Buffer<T>` (static trait) and `DynBuffer<T>` (trait object) for
4//! buffer implementations. Adapters (tokio, embassy) provide concrete types.
5//!
6//! See `aimdb-tokio-adapter` and `aimdb-embassy-adapter` for implementations.
7
8use core::task::{Context, Poll};
9
10use alloc::boxed::Box;
11#[cfg(feature = "remote")]
12use alloc::vec::Vec;
13
14use super::BufferCfg;
15use crate::DbError;
16#[cfg(feature = "remote")]
17use crate::Stamped;
18
19/// Static buffer trait for concrete implementations
20///
21/// Provides push/subscribe operations for typed buffers. Readers are owned
22/// and can outlive the subscription call (required for spawned tasks).
23///
24/// Trait bounds ensure thread-safety and `'static` lifetime for async runtimes.
25///
26/// See `aimdb_tokio_adapter::TokioRingBuffer` for implementation example.
27pub trait Buffer<T: Clone + Send>: Send + Sync + 'static {
28    /// Reader type for consuming values
29    ///
30    /// Each `subscribe()` call returns an independent owned reader.
31    type Reader: BufferReader<T> + 'static;
32
33    /// Creates a new buffer with the given configuration
34    ///
35    /// # Panics
36    /// May panic if configuration is invalid (call `cfg.validate()` first)
37    fn new(cfg: &BufferCfg) -> Self
38    where
39        Self: Sized;
40
41    /// Push a value into the buffer (non-blocking)
42    ///
43    /// Behavior depends on buffer type:
44    /// - **SPMC Ring**: Overwrites oldest value if full
45    /// - **SingleLatest**: Overwrites previous value
46    /// - **Mailbox**: Overwrites pending value if not consumed
47    fn push(&self, value: T);
48
49    /// Create a new independent reader for a consumer
50    ///
51    /// Each reader maintains its own position and can consume at its own pace.
52    /// The returned reader is owned and can outlive this reference.
53    ///
54    /// # Fresh-subscriber semantics (SingleLatest)
55    ///
56    /// For a [`SingleLatest`](BufferCfg::SingleLatest) buffer, a fresh
57    /// subscriber observes the buffer's current value once, as if it had been
58    /// pushed right after subscription; if nothing has been produced yet, it
59    /// waits. A late subscriber to state wants the current state, not just
60    /// future changes. This rule holds identically across every runtime adapter
61    /// and is enforced by
62    /// [`test_support::assert_single_latest_contract`](super::test_support::assert_single_latest_contract).
63    ///
64    /// `SpmcRing` and `Mailbox` readers have no such replay: a fresh subscriber
65    /// only sees values produced after it subscribes.
66    fn subscribe(&self) -> Self::Reader;
67}
68
69/// Dynamic buffer trait for trait objects (object-safe)
70///
71/// Type-erased interface for buffers that can be stored as trait objects.
72/// Automatically implemented for all `Buffer<T>` types via blanket impl.
73///
74/// Used when storing heterogeneous buffer types (e.g., in `TypedRecord`).
75pub trait DynBuffer<T: Clone + Send>: Send + Sync {
76    /// Push a value into the buffer (non-blocking)
77    fn push(&self, value: T);
78
79    /// Create a boxed reader for consuming values
80    ///
81    /// Returns a type-erased reader. Each reader maintains its own position.
82    fn subscribe_boxed(&self) -> Box<dyn BufferReader<T> + Send>;
83
84    /// Returns self as Any for downcasting to concrete buffer types
85    fn as_any(&self) -> &dyn core::any::Any;
86
87    /// Non-destructive read of the buffer's current value.
88    ///
89    /// Returns `Some(T)` if the buffer holds a current value that can be read
90    /// without affecting any consumer's position. Returns `None` if the buffer
91    /// type has no canonical "current value" concept (e.g., SPMC Ring) or if
92    /// no value has been produced yet.
93    ///
94    /// This is the buffer-native point-in-time read used by AimX `record.get`
95    ///. Implementations must not advance any reader position.
96    ///
97    /// The default returns `None`, which is the correct behaviour for buffers
98    /// without a canonical latest value.
99    fn peek(&self) -> Option<T> {
100        None
101    }
102
103    /// Get buffer metrics snapshot (metrics feature only)
104    ///
105    /// Returns `Some(snapshot)` if the buffer implementation supports metrics,
106    /// `None` otherwise. Default implementation returns `None`.
107    #[cfg(feature = "observability")]
108    fn metrics_snapshot(&self) -> Option<BufferMetricsSnapshot> {
109        None
110    }
111
112    /// Reset buffer metrics counters (metrics feature only)
113    ///
114    /// Default implementation is a no-op so buffers without metrics support are
115    /// safe to call. Implementations that track counters should override this
116    /// to zero them.
117    #[cfg(feature = "observability")]
118    fn reset_metrics(&self) {}
119}
120
121/// Non-blocking push error — carries the rejected value back to the caller.
122///
123/// Returned by [`Producer::try_produce`](crate::typed_api::Producer::try_produce).
124/// Both variants own the value so the caller can retry, escalate, or drop it.
125#[derive(Debug)]
126pub enum TryProduceError<T> {
127    /// Buffer is at capacity and configured not to overwrite. Transient.
128    Full(T),
129    /// Buffer / record has been torn down (e.g. shutdown). Terminal.
130    Closed(T),
131}
132
133// `Display` describes the failure mode only; the rejected value is the payload,
134// not part of the message, so this carries no `T: Display` bound.
135impl<T> core::fmt::Display for TryProduceError<T> {
136    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
137        match self {
138            Self::Full(_) => f.write_str("buffer is at capacity and configured not to overwrite"),
139            Self::Closed(_) => f.write_str("buffer or record has been torn down"),
140        }
141    }
142}
143
144// `Error: Debug + Display`; the derived `Debug` needs `T: Debug`, which every
145// `Producer<T>` already requires. Gated on `std` to match the crate's other
146// local error types (`PublishError`, `SerializeError`).
147#[cfg(feature = "std")]
148impl<T: core::fmt::Debug> std::error::Error for TryProduceError<T> {}
149
150/// Write-side handle for a single record.
151///
152/// `Producer<T>` holds an `Arc<dyn WriteHandle<T>>` so it can be parameterised
153/// over `T` alone — no runtime adapter `R` and no per-call record-key string
154/// lookup on the produce hot path. The implementor (`RecordWriter<T>`)
155/// pre-binds the underlying buffer, the latest-snapshot slot, and the metadata
156/// tracker at build time.
157///
158/// Crate-private on purpose. `Producer<T>::new` is the only construction path;
159/// external test code that needs a fake Producer should go through a future
160/// `Producer::for_testing(...)` helper rather than implementing `WriteHandle`
161/// directly.
162pub(crate) trait WriteHandle<T: Clone + Send + 'static>: Send + Sync {
163    /// Push a value into the buffer, update the latest-snapshot cache, and
164    /// (when a buffer is present) mark the metadata `last_update` timestamp.
165    /// Infallible — all three operations are synchronous and lock-free or
166    /// spin-locked.
167    fn push(&self, value: T);
168
169    /// Default: delegate to `push` and return `Ok(())`. Overwriting buffers
170    /// cannot fail, so the value is always accepted. Bounded / non-overwriting
171    /// buffers override this to return `Full(value)` or `Closed(value)`.
172    fn try_push(&self, value: T) -> Result<(), TryProduceError<T>> {
173        self.push(value);
174        Ok(())
175    }
176}
177
178/// Reader trait for consuming values from a buffer
179///
180/// This is the object-safe **service-provider interface** that runtime adapters
181/// implement. It is poll-based — and therefore object-safe and zero-allocation —
182/// rather than `async`: an `async fn` on an erased trait forces a
183/// `Pin<Box<dyn Future>>` heap allocation on every call.
184/// Consumers do not call this directly; they use the [`Reader<T>`](super::Reader)
185/// handle returned by `Consumer::subscribe`, whose `recv()` is `async` and wraps
186/// [`poll_recv`](BufferReader::poll_recv) via `core::future::poll_fn` with no
187/// allocation.
188///
189/// Each reader is independent with its own state.
190///
191/// # Error Handling
192/// - `Ok(value)` - Successfully received a value
193/// - `Err(BufferLagged)` - Missed messages (SPMC ring only, can continue)
194/// - `Err(BufferClosed)` - Buffer closed (graceful shutdown)
195///
196/// # Contract (poll/try_recv interleaving and cancellation)
197///
198/// Every implementation in this workspace (tokio/embassy/wasm adapters)
199/// conforms — this section makes the contract explicit for future
200/// implementors.
201///
202/// 1. `try_recv` MAY be called between `Pending` `poll_recv` calls;
203///    implementations MUST NOT lose values or wakeups across the
204///    interleaving.
205/// 2. A value claimed internally just before caller cancellation MUST be
206///    delivered on the next `poll_recv`/`try_recv` call — this is why, e.g.,
207///    the tokio broadcast/watch readers keep a persistent `ReusableBoxFuture`
208///    across calls rather than dropping and recreating it per call.
209/// 3. `poll_recv` MUST register the *latest* waker on every `Pending`
210///    return; spurious wakes are permitted (a registered waker firing with
211///    no corresponding new value is not a bug — callers must re-poll and
212///    tolerate a no-op).
213/// 4. Lag MUST surface as `Err(DbError::BufferLagged)` plus a metrics
214///    `add_dropped` call on **both** `poll_recv` and `try_recv`.
215pub trait BufferReader<T: Clone + Send>: Send {
216    /// Poll for the next value.
217    ///
218    /// Returns `Poll::Ready(Ok(value))` when a value is available,
219    /// `Poll::Ready(Err(..))` on lag/closure, or `Poll::Pending` after
220    /// registering `cx.waker()` to be woken when the next value arrives.
221    ///
222    /// # Behavior by Buffer Type
223    /// - **SPMC Ring**: Returns next value, or `Lagged(n)` if fell behind
224    /// - **SingleLatest**: Waits for value change, returns most recent
225    /// - **Mailbox**: Waits for slot value, takes and clears it
226    fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll<Result<T, DbError>>;
227
228    /// Non-blocking receive — returns immediately.
229    ///
230    /// Returns `Err(DbError::BufferEmpty)` if no pending values.
231    ///
232    /// # Behavior by Buffer Type
233    /// - **SPMC Ring**: Returns next buffered value, or `BufferEmpty` if caught up
234    /// - **SingleLatest**: Returns value if changed since last read, or `BufferEmpty`
235    /// - **Mailbox**: Takes and returns slot value, or `BufferEmpty` if empty
236    fn try_recv(&mut self) -> Result<T, DbError>;
237}
238
239/// Reader trait for consuming JSON-serialized values from a buffer.
240///
241/// Type-erased reader that subscribes to a typed buffer and emits either
242/// `serde_json::Value` or already-serialized JSON bytes. Used by the remote
243/// access protocol for subscriptions.
244///
245/// This trait enables subscribing to a buffer without knowing the concrete type `T`
246/// at compile time, by serializing values to JSON on each poll.
247///
248/// Object-safe and poll-based for the same reason as [`BufferReader`].
249/// Consumers use the [`JsonReader`](super::JsonReader) handle, whose
250/// receive methods are `async` wrappers over the corresponding poll methods
251/// and do not box a per-message future.
252///
253/// # Requirements
254/// - Record must be configured with `.with_remote_access()`
255/// - Only available with the `remote` feature (requires serde_json)
256#[cfg(feature = "remote")]
257pub trait JsonBufferReader: Send {
258    /// Poll for the next value, serialized to JSON.
259    ///
260    /// Returns `Poll::Ready(Ok(json))` when a value is available and
261    /// serializes successfully, `Poll::Ready(Err(..))` on lag/closure/serialize
262    /// failure, or `Poll::Pending` after registering `cx.waker()`.
263    ///
264    /// # Returns
265    /// - `Ok(JsonValue)` - Successfully received and serialized value
266    /// - `Err(BufferLagged)` - Missed messages (can continue reading)
267    /// - `Err(BufferClosed)` - Buffer closed (graceful shutdown)
268    /// - `Err(SerializationFailed)` - Failed to serialize value to JSON
269    fn poll_recv_json(
270        &mut self,
271        cx: &mut Context<'_>,
272    ) -> Poll<Result<Stamped<serde_json::Value>, DbError>>;
273
274    /// Non-blocking receive as JSON — returns immediately.
275    ///
276    /// Returns `Err(DbError::BufferEmpty)` if no pending values.
277    fn try_recv_json(&mut self) -> Result<Stamped<serde_json::Value>, DbError>;
278
279    /// Poll for the next value as owned JSON bytes.
280    ///
281    /// Existing implementations inherit a compatibility path that calls
282    /// [`poll_recv_json`](Self::poll_recv_json) and serializes the returned
283    /// tree, keeping its write metadata. Typed record readers override this to
284    /// encode `T` directly.
285    fn poll_recv_json_bytes(
286        &mut self,
287        cx: &mut Context<'_>,
288    ) -> Poll<Result<Stamped<Vec<u8>>, DbError>> {
289        match self.poll_recv_json(cx) {
290            Poll::Ready(Ok(sample)) => Poll::Ready(json_tree_to_bytes(sample)),
291            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
292            Poll::Pending => Poll::Pending,
293        }
294    }
295
296    /// Non-blocking receive as owned JSON bytes.
297    ///
298    /// Existing implementations inherit a compatibility path through
299    /// [`try_recv_json`](Self::try_recv_json).
300    fn try_recv_json_bytes(&mut self) -> Result<Stamped<Vec<u8>>, DbError> {
301        json_tree_to_bytes(self.try_recv_json()?)
302    }
303}
304
305/// Serializes a JSON tree to bytes, keeping the sample's write metadata whole.
306#[cfg(feature = "remote")]
307pub(crate) fn json_tree_to_bytes(
308    sample: Stamped<serde_json::Value>,
309) -> Result<Stamped<Vec<u8>>, DbError> {
310    sample.try_map(|value| {
311        serde_json::to_vec(&value)
312            .map_err(|_| DbError::runtime_error("Failed to serialize value to JSON"))
313    })
314}
315
316/// Snapshot of buffer metrics at a point in time
317///
318/// Used for introspection and diagnostics. All counters are monotonically
319/// increasing (except after reset).
320#[cfg(feature = "observability")]
321#[derive(Debug, Clone, Default)]
322pub struct BufferMetricsSnapshot {
323    /// Total items pushed to this buffer since creation
324    pub produced_count: u64,
325
326    /// Total items successfully consumed from this buffer (aggregate across all readers)
327    pub consumed_count: u64,
328
329    /// Total items dropped due to overflow/lag (SPMC ring only)
330    ///
331    /// **Note**: When multiple readers lag simultaneously on a broadcast buffer,
332    /// each reader reports its own dropped count independently. This means the
333    /// aggregate dropped_count may exceed the actual number of unique items that
334    /// overflowed from the ring buffer (each lagged reader adds its own lag count).
335    /// This is intentional: it reflects total "missed reads" across all consumers,
336    /// which is useful for diagnosing per-consumer backpressure issues.
337    pub dropped_count: u64,
338
339    /// Current buffer occupancy: (items_in_buffer, capacity)
340    /// Returns (0, 0) for SingleLatest/Mailbox where occupancy is not meaningful
341    pub occupancy: (usize, usize),
342}
343
344/// Optional buffer metrics for introspection (std only, feature-gated)
345///
346/// Implemented by buffer types when the `observability` feature is enabled.
347/// Provides counters for diagnosing producer-consumer imbalances.
348#[cfg(feature = "observability")]
349pub trait BufferMetrics {
350    /// Get a snapshot of current buffer metrics
351    ///
352    /// Returns counters for produced, consumed, and dropped items,
353    /// plus current buffer occupancy.
354    fn metrics(&self) -> BufferMetricsSnapshot;
355
356    /// Reset all metrics counters to zero
357    ///
358    /// Useful for windowed metrics collection. Note that this affects
359    /// all observers of this buffer's metrics.
360    fn reset_metrics(&self);
361}
362
363#[cfg(test)]
364mod tests {
365    use super::*;
366    use alloc::string::ToString;
367
368    // Mock implementation for testing trait bounds
369    struct MockBuffer<T: Clone + Send + Sync> {
370        _phantom: core::marker::PhantomData<T>,
371    }
372
373    struct MockReader<T: Clone + Send> {
374        _phantom: core::marker::PhantomData<T>,
375    }
376
377    impl<T: Clone + Send + Sync + 'static> Buffer<T> for MockBuffer<T> {
378        type Reader = MockReader<T>;
379
380        fn new(_cfg: &BufferCfg) -> Self {
381            Self {
382                _phantom: core::marker::PhantomData,
383            }
384        }
385
386        fn push(&self, _value: T) {
387            // No-op for testing
388        }
389
390        fn subscribe(&self) -> Self::Reader {
391            MockReader {
392                _phantom: core::marker::PhantomData,
393            }
394        }
395    }
396
397    // Explicit DynBuffer implementation for MockBuffer
398    // (no blanket impl - adapters provide their own)
399    impl<T: Clone + Send + Sync + 'static> DynBuffer<T> for MockBuffer<T> {
400        fn push(&self, value: T) {
401            <Self as Buffer<T>>::push(self, value)
402        }
403
404        fn subscribe_boxed(&self) -> Box<dyn BufferReader<T> + Send> {
405            Box::new(self.subscribe())
406        }
407
408        fn as_any(&self) -> &dyn core::any::Any {
409            self
410        }
411
412        #[cfg(feature = "observability")]
413        fn metrics_snapshot(&self) -> Option<BufferMetricsSnapshot> {
414            None // Mock doesn't track metrics
415        }
416    }
417
418    impl<T: Clone + Send> BufferReader<T> for MockReader<T> {
419        fn poll_recv(&mut self, _cx: &mut Context<'_>) -> Poll<Result<T, DbError>> {
420            // Return closed for testing
421            Poll::Ready(Err(DbError::BufferClosed {
422                buffer_name: "mock".to_string(),
423            }))
424        }
425
426        fn try_recv(&mut self) -> Result<T, DbError> {
427            Err(DbError::BufferEmpty)
428        }
429    }
430
431    #[test]
432    fn test_buffer_trait_bounds() {
433        // Verify trait bounds compile
434        fn assert_send<T: Send>() {}
435        fn assert_sync<T: Sync>() {}
436
437        assert_send::<MockBuffer<i32>>();
438        assert_sync::<MockBuffer<i32>>();
439        assert_send::<MockReader<i32>>();
440    }
441
442    #[test]
443    fn test_dyn_buffer_impl() {
444        // Verify DynBuffer can be used as trait object
445        let buffer = MockBuffer::<i32> {
446            _phantom: core::marker::PhantomData,
447        };
448
449        // Should be able to use as DynBuffer
450        let _: &dyn DynBuffer<i32> = &buffer;
451    }
452
453    // WriteHandle impl that always rejects with the buffer full. Used to verify that when
454    // try_push fails, it returns the value that it failed to push.
455    struct FullWriteHandle;
456
457    impl WriteHandle<i32> for FullWriteHandle {
458        fn push(&self, _value: i32) {}
459        fn try_push(&self, value: i32) -> Result<(), TryProduceError<i32>> {
460            Err(TryProduceError::Full(value))
461        }
462    }
463
464    // WriteHandle impl that always rejects because the record is closed. Mirrors
465    // `FullWriteHandle` for the terminal arm.
466    struct ClosedWriteHandle;
467
468    impl WriteHandle<i32> for ClosedWriteHandle {
469        fn push(&self, _value: i32) {}
470        fn try_push(&self, value: i32) -> Result<(), TryProduceError<i32>> {
471            Err(TryProduceError::Closed(value))
472        }
473    }
474
475    #[test]
476    fn try_push_full_round_trips_value_through_producer() {
477        use alloc::sync::Arc;
478        let producer = crate::typed_api::Producer::new(Arc::new(FullWriteHandle));
479        let result = producer.try_produce(42_i32);
480        assert!(
481            matches!(result, Err(TryProduceError::Full(42))),
482            "expected Full(42), got {result:?}",
483        );
484    }
485
486    #[test]
487    fn try_push_closed_round_trips_value_through_producer() {
488        use alloc::sync::Arc;
489        let producer = crate::typed_api::Producer::new(Arc::new(ClosedWriteHandle));
490        let result = producer.try_produce(42_i32);
491        assert!(
492            matches!(result, Err(TryProduceError::Closed(42))),
493            "expected Closed(42), got {result:?}",
494        );
495    }
496
497    #[cfg(feature = "std")]
498    #[test]
499    fn try_produce_error_displays_failure_mode_without_value() {
500        use alloc::string::ToString;
501        assert_eq!(
502            TryProduceError::Full(42_i32).to_string(),
503            "buffer is at capacity and configured not to overwrite",
504        );
505        assert_eq!(
506            TryProduceError::Closed(42_i32).to_string(),
507            "buffer or record has been torn down",
508        );
509    }
510}