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::future::Future;
9use core::pin::Pin;
10
11#[cfg(not(feature = "std"))]
12extern crate alloc;
13
14#[cfg(not(feature = "std"))]
15use alloc::boxed::Box;
16
17#[cfg(feature = "std")]
18use std::boxed::Box;
19
20use super::BufferCfg;
21use crate::DbError;
22
23/// Static buffer trait for concrete implementations
24///
25/// Provides push/subscribe operations for typed buffers. Readers are owned
26/// and can outlive the subscription call (required for spawned tasks).
27///
28/// Trait bounds ensure thread-safety and `'static` lifetime for async runtimes.
29///
30/// See `aimdb_tokio_adapter::TokioRingBuffer` for implementation example.
31pub trait Buffer<T: Clone + Send>: Send + Sync + 'static {
32 /// Reader type for consuming values
33 ///
34 /// Each `subscribe()` call returns an independent owned reader.
35 type Reader: BufferReader<T> + 'static;
36
37 /// Creates a new buffer with the given configuration
38 ///
39 /// # Panics
40 /// May panic if configuration is invalid (call `cfg.validate()` first)
41 fn new(cfg: &BufferCfg) -> Self
42 where
43 Self: Sized;
44
45 /// Push a value into the buffer (non-blocking)
46 ///
47 /// Behavior depends on buffer type:
48 /// - **SPMC Ring**: Overwrites oldest value if full
49 /// - **SingleLatest**: Overwrites previous value
50 /// - **Mailbox**: Overwrites pending value if not consumed
51 fn push(&self, value: T);
52
53 /// Create a new independent reader for a consumer
54 ///
55 /// Each reader maintains its own position and can consume at its own pace.
56 /// The returned reader is owned and can outlive this reference.
57 fn subscribe(&self) -> Self::Reader;
58}
59
60/// Dynamic buffer trait for trait objects (object-safe)
61///
62/// Type-erased interface for buffers that can be stored as trait objects.
63/// Automatically implemented for all `Buffer<T>` types via blanket impl.
64///
65/// Used when storing heterogeneous buffer types (e.g., in `TypedRecord`).
66pub trait DynBuffer<T: Clone + Send>: Send + Sync {
67 /// Push a value into the buffer (non-blocking)
68 fn push(&self, value: T);
69
70 /// Create a boxed reader for consuming values
71 ///
72 /// Returns a type-erased reader. Each reader maintains its own position.
73 fn subscribe_boxed(&self) -> Box<dyn BufferReader<T> + Send>;
74
75 /// Returns self as Any for downcasting to concrete buffer types
76 fn as_any(&self) -> &dyn core::any::Any;
77
78 /// Get buffer metrics snapshot (metrics feature only)
79 ///
80 /// Returns `Some(snapshot)` if the buffer implementation supports metrics,
81 /// `None` otherwise. Default implementation returns `None`.
82 #[cfg(feature = "metrics")]
83 fn metrics_snapshot(&self) -> Option<BufferMetricsSnapshot> {
84 None
85 }
86}
87
88/// Reader trait for consuming values from a buffer
89///
90/// All read operations are async. Each reader is independent with its own state.
91///
92/// # Error Handling
93/// - `Ok(value)` - Successfully received a value
94/// - `Err(BufferLagged)` - Missed messages (SPMC ring only, can continue)
95/// - `Err(BufferClosed)` - Buffer closed (graceful shutdown)
96pub trait BufferReader<T: Clone + Send>: Send {
97 /// Receive the next value (async)
98 ///
99 /// Waits for the next available value. Returns immediately if buffered.
100 ///
101 /// # Behavior by Buffer Type
102 /// - **SPMC Ring**: Returns next value, or `Lagged(n)` if fell behind
103 /// - **SingleLatest**: Waits for value change, returns most recent
104 /// - **Mailbox**: Waits for slot value, takes and clears it
105 fn recv(&mut self) -> Pin<Box<dyn Future<Output = Result<T, DbError>> + Send + '_>>;
106}
107
108/// Reader trait for consuming JSON-serialized values from a buffer (std only)
109///
110/// Type-erased reader that subscribes to a typed buffer and emits values as
111/// `serde_json::Value`. Used by remote access protocol for subscriptions.
112///
113/// This trait enables subscribing to a buffer without knowing the concrete type `T`
114/// at compile time, by serializing values to JSON on each `recv_json()` call.
115///
116/// # Requirements
117/// - Record must be configured with `.with_serialization()`
118/// - Only available with `std` feature (requires serde_json)
119///
120/// # Example
121/// ```rust,ignore
122/// // Internal use in remote access handler
123/// let json_reader: Box<dyn JsonBufferReader> = record.subscribe_json()?;
124/// while let Ok(json_val) = json_reader.recv_json().await {
125/// // Forward JSON value to remote client...
126/// }
127/// ```
128#[cfg(feature = "std")]
129pub trait JsonBufferReader: Send {
130 /// Receive the next value as JSON (async)
131 ///
132 /// Waits for the next value from the underlying buffer and serializes it to JSON.
133 ///
134 /// # Returns
135 /// - `Ok(JsonValue)` - Successfully received and serialized value
136 /// - `Err(BufferLagged)` - Missed messages (can continue reading)
137 /// - `Err(BufferClosed)` - Buffer closed (graceful shutdown)
138 /// - `Err(SerializationFailed)` - Failed to serialize value to JSON
139 fn recv_json(
140 &mut self,
141 ) -> Pin<Box<dyn Future<Output = Result<serde_json::Value, DbError>> + Send + '_>>;
142}
143
144/// Snapshot of buffer metrics at a point in time
145///
146/// Used for introspection and diagnostics. All counters are monotonically
147/// increasing (except after reset).
148#[cfg(feature = "metrics")]
149#[derive(Debug, Clone, Default)]
150pub struct BufferMetricsSnapshot {
151 /// Total items pushed to this buffer since creation
152 pub produced_count: u64,
153
154 /// Total items successfully consumed from this buffer (aggregate across all readers)
155 pub consumed_count: u64,
156
157 /// Total items dropped due to overflow/lag (SPMC ring only)
158 ///
159 /// **Note**: When multiple readers lag simultaneously on a broadcast buffer,
160 /// each reader reports its own dropped count independently. This means the
161 /// aggregate dropped_count may exceed the actual number of unique items that
162 /// overflowed from the ring buffer (each lagged reader adds its own lag count).
163 /// This is intentional: it reflects total "missed reads" across all consumers,
164 /// which is useful for diagnosing per-consumer backpressure issues.
165 pub dropped_count: u64,
166
167 /// Current buffer occupancy: (items_in_buffer, capacity)
168 /// Returns (0, 0) for SingleLatest/Mailbox where occupancy is not meaningful
169 pub occupancy: (usize, usize),
170}
171
172/// Optional buffer metrics for introspection (std only, feature-gated)
173///
174/// Implemented by buffer types when the `metrics` feature is enabled.
175/// Provides counters for diagnosing producer-consumer imbalances.
176///
177/// # Example
178/// ```rust,ignore
179/// use aimdb_core::buffer::BufferMetrics;
180///
181/// // After enabling `metrics` feature
182/// let metrics = buffer.metrics();
183/// if metrics.produced_count > metrics.consumed_count + 1000 {
184/// println!("Warning: consumer is {} items behind",
185/// metrics.produced_count - metrics.consumed_count);
186/// }
187/// if metrics.dropped_count > 0 {
188/// println!("Warning: {} items dropped due to overflow", metrics.dropped_count);
189/// }
190/// ```
191#[cfg(feature = "metrics")]
192pub trait BufferMetrics {
193 /// Get a snapshot of current buffer metrics
194 ///
195 /// Returns counters for produced, consumed, and dropped items,
196 /// plus current buffer occupancy.
197 fn metrics(&self) -> BufferMetricsSnapshot;
198
199 /// Reset all metrics counters to zero
200 ///
201 /// Useful for windowed metrics collection. Note that this affects
202 /// all observers of this buffer's metrics.
203 fn reset_metrics(&self);
204}
205
206#[cfg(test)]
207mod tests {
208 use super::*;
209
210 // Mock implementation for testing trait bounds
211 struct MockBuffer<T: Clone + Send + Sync> {
212 _phantom: core::marker::PhantomData<T>,
213 }
214
215 struct MockReader<T: Clone + Send> {
216 _phantom: core::marker::PhantomData<T>,
217 }
218
219 impl<T: Clone + Send + Sync + 'static> Buffer<T> for MockBuffer<T> {
220 type Reader = MockReader<T>;
221
222 fn new(_cfg: &BufferCfg) -> Self {
223 Self {
224 _phantom: core::marker::PhantomData,
225 }
226 }
227
228 fn push(&self, _value: T) {
229 // No-op for testing
230 }
231
232 fn subscribe(&self) -> Self::Reader {
233 MockReader {
234 _phantom: core::marker::PhantomData,
235 }
236 }
237 }
238
239 // Explicit DynBuffer implementation for MockBuffer
240 // (no blanket impl - adapters provide their own)
241 impl<T: Clone + Send + Sync + 'static> DynBuffer<T> for MockBuffer<T> {
242 fn push(&self, value: T) {
243 <Self as Buffer<T>>::push(self, value)
244 }
245
246 fn subscribe_boxed(&self) -> Box<dyn BufferReader<T> + Send> {
247 Box::new(self.subscribe())
248 }
249
250 fn as_any(&self) -> &dyn core::any::Any {
251 self
252 }
253
254 #[cfg(feature = "metrics")]
255 fn metrics_snapshot(&self) -> Option<BufferMetricsSnapshot> {
256 None // Mock doesn't track metrics
257 }
258 }
259
260 impl<T: Clone + Send> BufferReader<T> for MockReader<T> {
261 fn recv(&mut self) -> Pin<Box<dyn Future<Output = Result<T, DbError>> + Send + '_>> {
262 Box::pin(async {
263 // Return closed for testing
264 Err(DbError::BufferClosed {
265 #[cfg(feature = "std")]
266 buffer_name: "mock".to_string(),
267 #[cfg(not(feature = "std"))]
268 _buffer_name: (),
269 })
270 })
271 }
272 }
273
274 #[test]
275 fn test_buffer_trait_bounds() {
276 // Verify trait bounds compile
277 fn assert_send<T: Send>() {}
278 fn assert_sync<T: Sync>() {}
279
280 assert_send::<MockBuffer<i32>>();
281 assert_sync::<MockBuffer<i32>>();
282 assert_send::<MockReader<i32>>();
283 }
284
285 #[test]
286 fn test_dyn_buffer_impl() {
287 // Verify DynBuffer can be used as trait object
288 let buffer = MockBuffer::<i32> {
289 _phantom: core::marker::PhantomData,
290 };
291
292 // Should be able to use as DynBuffer
293 let _: &dyn DynBuffer<i32> = &buffer;
294 }
295}