Skip to main content

aimdb_core/buffer/
reader.rs

1//! Consumer-facing reader handles.
2//!
3//! The [`BufferReader`] / [`JsonBufferReader`] SPIs are object-safe and
4//! poll-based so adapters can implement them without a per-message
5//! `Pin<Box<dyn Future>>` allocation. These handles restore the ergonomic
6//! `async fn recv().await` surface for consumers by wrapping the erased
7//! reader's `poll_*` method in [`core::future::poll_fn`] — which is `core`-only
8//! (no_std-clean), allocation-free, and `unsafe`-free.
9//!
10//! The wrapped future is `Send` because the boxed reader is `Send`.
11
12use alloc::boxed::Box;
13#[cfg(feature = "remote")]
14use alloc::vec::Vec;
15use core::future::poll_fn;
16use core::task::{Context, Poll};
17
18use crate::buffer::BufferReader;
19use crate::{DbError, Stamped};
20
21#[cfg(feature = "remote")]
22use crate::buffer::JsonBufferReader;
23
24/// Owned, ergonomic handle over an erased [`BufferReader`].
25///
26/// Returned by `Consumer::subscribe`. This is the "boxed lane": one indirect
27/// call per `recv`, zero AimDB-added heap allocations per message. (The generic
28/// monomorphized `Reader<T, B>` fast lane remains dormant.)
29///
30/// Every value comes with the metadata of the write that stored it
31/// ([`Stamped`]); read `.value` for the value alone.
32pub struct Reader<T: Clone + Send> {
33    inner: Box<dyn BufferReader<Stamped<T>> + Send>,
34}
35
36impl<T: Clone + Send> Reader<T> {
37    /// Wrap an erased reader in an ergonomic handle.
38    pub fn new(inner: Box<dyn BufferReader<Stamped<T>> + Send>) -> Self {
39        Self { inner }
40    }
41
42    /// Receive the next value, awaiting until one is available.
43    ///
44    /// Allocation-free: wraps the erased reader's
45    /// [`poll_recv`](BufferReader::poll_recv) via `core::future::poll_fn`.
46    ///
47    /// # Behavior by Buffer Type
48    /// - **SPMC Ring**: Returns next value, or `Lagged(n)` if fell behind
49    /// - **SingleLatest**: Waits for value change, returns most recent
50    /// - **Mailbox**: Waits for slot value, takes and clears it
51    pub async fn recv(&mut self) -> Result<Stamped<T>, DbError> {
52        poll_fn(|cx| self.inner.poll_recv(cx)).await
53    }
54
55    /// Poll for the next value, for hand-written `poll` code.
56    ///
57    /// Follows the [`BufferReader::poll_recv`] contract: on `Pending` the
58    /// waker in `cx` is registered (the latest one wins), and spurious
59    /// wake-ups are allowed. `Pending` does not always mean the buffer is
60    /// empty: on Tokio a broadcast reader also returns it, with a self-wake,
61    /// once the task's cooperative budget is spent.
62    pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll<Result<Stamped<T>, DbError>> {
63        self.inner.poll_recv(cx)
64    }
65
66    /// Non-blocking receive — returns immediately.
67    ///
68    /// Returns `Err(DbError::BufferEmpty)` if no pending values.
69    pub fn try_recv(&mut self) -> Result<Stamped<T>, DbError> {
70        self.inner.try_recv()
71    }
72}
73
74/// Owned, ergonomic handle over an erased [`JsonBufferReader`].
75///
76/// Returned by `subscribe_json`. Awaiting `recv_json` or
77/// `recv_json_bytes` wraps the corresponding poll method via
78/// `core::future::poll_fn` — no extra per-message future box.
79#[cfg(feature = "remote")]
80pub struct JsonReader {
81    inner: Box<dyn JsonBufferReader + Send>,
82}
83
84#[cfg(feature = "remote")]
85impl JsonReader {
86    /// Wrap an erased JSON reader in an ergonomic handle.
87    pub fn new(inner: Box<dyn JsonBufferReader + Send>) -> Self {
88        Self { inner }
89    }
90
91    /// Receive the next value as JSON, awaiting until one is available.
92    pub async fn recv_json(&mut self) -> Result<Stamped<serde_json::Value>, DbError> {
93        poll_fn(|cx| self.inner.poll_recv_json(cx)).await
94    }
95
96    /// Receive the next value as owned JSON bytes.
97    pub async fn recv_json_bytes(&mut self) -> Result<Stamped<Vec<u8>>, DbError> {
98        poll_fn(|cx| self.inner.poll_recv_json_bytes(cx)).await
99    }
100
101    /// Non-blocking receive as JSON — returns immediately.
102    ///
103    /// Returns `Err(DbError::BufferEmpty)` if no pending values.
104    pub fn try_recv_json(&mut self) -> Result<Stamped<serde_json::Value>, DbError> {
105        self.inner.try_recv_json()
106    }
107
108    /// Non-blocking receive as owned JSON bytes — returns immediately.
109    ///
110    /// Returns `Err(DbError::BufferEmpty)` if no pending values.
111    pub fn try_recv_json_bytes(&mut self) -> Result<Stamped<Vec<u8>>, DbError> {
112        self.inner.try_recv_json_bytes()
113    }
114}
115
116#[cfg(test)]
117mod tests {
118    use super::*;
119    use alloc::sync::Arc;
120    use alloc::task::Wake;
121    use core::sync::atomic::{AtomicBool, AtomicU32, Ordering};
122    use futures_util::task::AtomicWaker;
123
124    /// One-slot buffer: `0` is empty. Its reader registers the waker on
125    /// `Pending`, and `produce` wakes it.
126    #[derive(Default)]
127    struct Slot {
128        value: AtomicU32,
129        waker: AtomicWaker,
130    }
131
132    impl Slot {
133        fn produce(&self, v: u32) {
134            self.value.store(v, Ordering::Release);
135            self.waker.wake();
136        }
137    }
138
139    struct SlotReader(Arc<Slot>);
140
141    /// A sample whose stamp equals its value.
142    fn sample(v: u32) -> Stamped<u32> {
143        Stamped::new(
144            v,
145            crate::WriteMetadata::new(crate::Stamp::from_nanos(u64::from(v))),
146        )
147    }
148
149    impl BufferReader<Stamped<u32>> for SlotReader {
150        fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll<Result<Stamped<u32>, DbError>> {
151            self.0.waker.register(cx.waker());
152            match self.0.value.swap(0, Ordering::AcqRel) {
153                0 => Poll::Pending,
154                v => Poll::Ready(Ok(sample(v))),
155            }
156        }
157
158        fn try_recv(&mut self) -> Result<Stamped<u32>, DbError> {
159            match self.0.value.swap(0, Ordering::AcqRel) {
160                0 => Err(DbError::BufferEmpty),
161                v => Ok(sample(v)),
162            }
163        }
164    }
165
166    #[derive(Default)]
167    struct Flag(AtomicBool);
168
169    impl Wake for Flag {
170        fn wake(self: Arc<Self>) {
171            self.0.store(true, Ordering::Release);
172        }
173    }
174
175    #[test]
176    fn poll_recv_registers_the_waker_and_is_woken_by_a_produce() {
177        let slot = Arc::new(Slot::default());
178        let mut reader = Reader::new(Box::new(SlotReader(Arc::clone(&slot))));
179        let flag = Arc::new(Flag::default());
180        let waker = Arc::clone(&flag).into();
181        let mut cx = Context::from_waker(&waker);
182
183        assert!(reader.poll_recv(&mut cx).is_pending());
184        assert!(!flag.0.load(Ordering::Acquire));
185
186        slot.produce(7);
187        assert!(flag.0.load(Ordering::Acquire));
188        assert!(matches!(reader.poll_recv(&mut cx), Poll::Ready(Ok(ref s)) if *s == sample(7)));
189    }
190}