Skip to main content

merry_runtime/events/
journal_stream.rs

1//! Runtime journal event stream wrapper.
2//!
3//! The stream owns the lifetime of one active runtime step. Polling yields
4//! provider-neutral [`RuntimeJournalEvent`] values after session state has been
5//! recorded. The runtime updates read-model observers before enqueueing each
6//! batch, so consuming this stream is not required to keep projections current.
7//! Dropping the stream cancels and aborts the producer; the active step permit
8//! is released when that producer future stops and drops its state.
9
10use futures_core::Stream;
11use merry_core::RuntimeJournalEvent;
12use std::{
13    pin::Pin,
14    sync::{
15        Arc,
16        atomic::{AtomicBool, Ordering},
17    },
18    task::{Context, Poll},
19};
20use tokio::sync::watch;
21use tokio::task::JoinHandle;
22use tokio_stream::wrappers::ReceiverStream;
23use tokio_stream::wrappers::WatchStream;
24use tokio_util::sync::CancellationToken;
25
26/// One atomic enqueue item in the internal semantic journal channel.
27pub(crate) struct RuntimeJournalEventBatch(RuntimeJournalEventBatchKind);
28
29pub(crate) type RuntimeRateUpdateSender = watch::Sender<Option<RuntimeJournalEvent>>;
30
31pub(crate) fn runtime_rate_update_channel() -> (
32    RuntimeRateUpdateSender,
33    watch::Receiver<Option<RuntimeJournalEvent>>,
34) {
35    watch::channel(None)
36}
37
38// The single-event path is hot; boxing it would add an allocation to every journal emission.
39#[allow(clippy::large_enum_variant)]
40enum RuntimeJournalEventBatchKind {
41    Single(RuntimeJournalEvent),
42    Multiple(Vec<RuntimeJournalEvent>),
43}
44
45impl RuntimeJournalEventBatch {
46    pub(crate) fn pair(first: RuntimeJournalEvent, second: RuntimeJournalEvent) -> Self {
47        Self(RuntimeJournalEventBatchKind::Multiple(vec![first, second]))
48    }
49
50    pub(crate) fn from_events(mut events: Vec<RuntimeJournalEvent>) -> Option<Self> {
51        match events.len() {
52            0 => None,
53            1 => Some(Self(RuntimeJournalEventBatchKind::Single(
54                events.pop().expect("one event remains"),
55            ))),
56            _ => Some(Self(RuntimeJournalEventBatchKind::Multiple(events))),
57        }
58    }
59
60    /// Visits events without consuming the batch before it enters the channel.
61    pub(crate) fn for_each(&self, mut visit: impl FnMut(&RuntimeJournalEvent)) {
62        match &self.0 {
63            RuntimeJournalEventBatchKind::Single(event) => visit(event),
64            RuntimeJournalEventBatchKind::Multiple(events) => {
65                for event in events {
66                    visit(event);
67                }
68            }
69        }
70    }
71
72    fn first_sequence(&self) -> u64 {
73        match &self.0 {
74            RuntimeJournalEventBatchKind::Single(event) => event.sequence,
75            RuntimeJournalEventBatchKind::Multiple(events) => {
76                events.first().map_or(0, |event| event.sequence)
77            }
78        }
79    }
80
81    fn into_iter(self) -> RuntimeJournalEventBatchIter {
82        match self.0 {
83            RuntimeJournalEventBatchKind::Single(event) => {
84                RuntimeJournalEventBatchIter::Single(Some(event))
85            }
86            RuntimeJournalEventBatchKind::Multiple(events) => {
87                RuntimeJournalEventBatchIter::Multiple(events.into_iter())
88            }
89        }
90    }
91}
92
93impl From<RuntimeJournalEvent> for RuntimeJournalEventBatch {
94    fn from(event: RuntimeJournalEvent) -> Self {
95        Self(RuntimeJournalEventBatchKind::Single(event))
96    }
97}
98
99#[allow(clippy::large_enum_variant)]
100enum RuntimeJournalEventBatchIter {
101    Single(Option<RuntimeJournalEvent>),
102    Multiple(std::vec::IntoIter<RuntimeJournalEvent>),
103}
104
105impl Iterator for RuntimeJournalEventBatchIter {
106    type Item = RuntimeJournalEvent;
107
108    fn next(&mut self) -> Option<Self::Item> {
109        match self {
110            Self::Single(event) => event.take(),
111            Self::Multiple(events) => events.next(),
112        }
113    }
114}
115
116/// Stream of provider-neutral runtime journal events.
117///
118/// A stream is returned by [`crate::Runtime::step`] and
119/// [`crate::Runtime::journal_stream`]. It should be driven until completion
120/// when callers want the producer to finish normally. Dropping it is the
121/// cancellation path for the active step. The permit may remain active after
122/// the producer stops while an in-flight persistence transaction finishes
123/// discarding staged state or installing a durable commit. Semantic events are
124/// delivered in sequence order; replaceable output-rate observations use a
125/// latest-only channel and intermediate samples may be skipped.
126pub struct RuntimeJournalEventStream {
127    inner: Option<ReceiverStream<RuntimeJournalEventBatch>>,
128    pending: Option<RuntimeJournalEventBatchIter>,
129    pending_sequence: Option<u64>,
130    pending_batch_started: bool,
131    rate_updates: WatchStream<Option<RuntimeJournalEvent>>,
132    pending_rate_update: Option<RuntimeJournalEvent>,
133    rate_updates_closed: bool,
134    cancellation_token: CancellationToken,
135    producer_handle: Option<JoinHandle<()>>,
136}
137
138impl RuntimeJournalEventStream {
139    pub(crate) fn new(
140        inner: ReceiverStream<RuntimeJournalEventBatch>,
141        rate_updates: watch::Receiver<Option<RuntimeJournalEvent>>,
142        cancellation_token: CancellationToken,
143        producer_handle: JoinHandle<()>,
144    ) -> Self {
145        Self {
146            inner: Some(inner),
147            pending: None,
148            pending_sequence: None,
149            pending_batch_started: false,
150            rate_updates: WatchStream::from_changes(rate_updates),
151            pending_rate_update: None,
152            rate_updates_closed: false,
153            cancellation_token,
154            producer_handle: Some(producer_handle),
155        }
156    }
157}
158
159impl Stream for RuntimeJournalEventStream {
160    type Item = RuntimeJournalEvent;
161
162    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
163        loop {
164            if !self.rate_updates_closed {
165                match Pin::new(&mut self.rate_updates).poll_next(cx) {
166                    Poll::Ready(Some(Some(event))) => self.pending_rate_update = Some(event),
167                    Poll::Ready(Some(None)) => {}
168                    Poll::Ready(None) => self.rate_updates_closed = true,
169                    Poll::Pending => {}
170                }
171            }
172
173            let rate_precedes_pending_batch = !self.pending_batch_started
174                && self.pending_rate_update.as_ref().is_some_and(|rate| {
175                    self.pending_sequence
176                        .is_some_and(|sequence| rate.sequence < sequence)
177                });
178            if let Some(pending) = self.pending.as_mut() {
179                if rate_precedes_pending_batch {
180                    return Poll::Ready(self.pending_rate_update.take());
181                }
182                let event = pending.next();
183                if event.is_some() {
184                    self.pending_batch_started = true;
185                    return Poll::Ready(event);
186                }
187                self.pending = None;
188                self.pending_sequence = None;
189                self.pending_batch_started = false;
190            }
191
192            if let Some(inner) = self.inner.as_mut() {
193                match Pin::new(inner).poll_next(cx) {
194                    Poll::Ready(Some(batch)) => {
195                        self.pending_sequence = Some(batch.first_sequence());
196                        self.pending = Some(batch.into_iter());
197                        self.pending_batch_started = false;
198                        continue;
199                    }
200                    Poll::Ready(None) => {
201                        self.inner = None;
202                    }
203                    Poll::Pending => {
204                        if let Some(rate) = self.pending_rate_update.take() {
205                            return Poll::Ready(Some(rate));
206                        }
207                    }
208                }
209            }
210
211            if let Some(rate) = self.pending_rate_update.take() {
212                return Poll::Ready(Some(rate));
213            }
214
215            if self.inner.is_none() && self.rate_updates_closed {
216                self.producer_handle.take();
217                return Poll::Ready(None);
218            }
219            return Poll::Pending;
220        }
221    }
222}
223
224impl Drop for RuntimeJournalEventStream {
225    fn drop(&mut self) {
226        self.inner.take();
227        self.cancellation_token.cancel();
228
229        if let Some(handle) = self.producer_handle.take() {
230            handle.abort();
231        }
232    }
233}
234
235pub(crate) struct ActiveStepPermit {
236    inner: Arc<ActiveStepPermitInner>,
237}
238
239impl ActiveStepPermit {
240    pub(crate) fn acquire(active: Arc<AtomicBool>) -> Option<Self> {
241        active
242            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
243            .ok()?;
244
245        Some(Self {
246            inner: Arc::new(ActiveStepPermitInner { active }),
247        })
248    }
249}
250
251impl Clone for ActiveStepPermit {
252    fn clone(&self) -> Self {
253        Self {
254            inner: Arc::clone(&self.inner),
255        }
256    }
257}
258
259impl Drop for ActiveStepPermitInner {
260    fn drop(&mut self) {
261        self.active.store(false, Ordering::Release);
262    }
263}
264
265struct ActiveStepPermitInner {
266    active: Arc<AtomicBool>,
267}
268
269#[cfg(test)]
270mod tests {
271    use super::*;
272    use futures_util::StreamExt;
273    use merry_core::{RuntimeJournalPayload, SessionId};
274    use tokio::sync::mpsc;
275
276    fn event(sequence: u64) -> RuntimeJournalEvent {
277        RuntimeJournalEvent::new(
278            SessionId::new("journal-event-batch-test").expect("valid session id"),
279            sequence,
280            RuntimeJournalPayload::StepStarted,
281        )
282    }
283
284    fn rate_event(sequence: u64) -> RuntimeJournalEvent {
285        RuntimeJournalEvent::new(
286            SessionId::new("journal-event-batch-test").expect("valid session id"),
287            sequence,
288            RuntimeJournalPayload::ModelOutputRateUpdated { rate: None },
289        )
290    }
291
292    #[test]
293    fn event_batch_rejects_empty_and_preserves_all_events_in_order() {
294        assert!(RuntimeJournalEventBatch::from_events(Vec::new()).is_none());
295
296        let events = RuntimeJournalEventBatch::from_events(vec![event(4), event(5), event(6)])
297            .expect("non-empty batch");
298        assert_eq!(
299            events
300                .into_iter()
301                .map(|event| event.sequence)
302                .collect::<Vec<_>>(),
303            [4, 5, 6]
304        );
305    }
306
307    #[tokio::test]
308    async fn rate_updates_replace_unread_values_instead_of_accumulating() {
309        let (rate_sender, rate_receiver) = runtime_rate_update_channel();
310        let (event_sender, event_receiver) = mpsc::channel(1);
311        event_sender
312            .send(
313                RuntimeJournalEventBatch::from_events(vec![event(1)])
314                    .expect("non-empty event batch"),
315            )
316            .await
317            .expect("event stream should be open");
318        rate_sender.send_replace(Some(rate_event(2)));
319        rate_sender.send_replace(Some(rate_event(3)));
320        drop(rate_sender);
321        drop(event_sender);
322
323        let producer_handle = tokio::spawn(async {});
324        let mut stream = RuntimeJournalEventStream::new(
325            ReceiverStream::new(event_receiver),
326            rate_receiver,
327            CancellationToken::new(),
328            producer_handle,
329        );
330        let events: Vec<_> = stream.by_ref().collect().await;
331
332        assert_eq!(
333            events
334                .iter()
335                .map(|event| event.sequence)
336                .collect::<Vec<_>>(),
337            vec![1, 3]
338        );
339        assert!(matches!(
340            events[1].payload,
341            RuntimeJournalPayload::ModelOutputRateUpdated { rate: None }
342        ));
343    }
344
345    #[tokio::test]
346    async fn a_new_rate_replaces_a_pending_rate_before_rendering_it() {
347        let (rate_sender, rate_receiver) = runtime_rate_update_channel();
348        let (event_sender, event_receiver) = mpsc::channel(1);
349        event_sender
350            .send(
351                RuntimeJournalEventBatch::from_events(vec![event(1), event(2)])
352                    .expect("non-empty event batch"),
353            )
354            .await
355            .expect("event stream should be open");
356        drop(event_sender);
357        rate_sender.send_replace(Some(rate_event(3)));
358
359        let producer_handle = tokio::spawn(async {});
360        let mut stream = RuntimeJournalEventStream::new(
361            ReceiverStream::new(event_receiver),
362            rate_receiver,
363            CancellationToken::new(),
364            producer_handle,
365        );
366
367        assert_eq!(
368            stream.next().await.expect("first semantic event").sequence,
369            1
370        );
371        rate_sender.send_replace(Some(rate_event(4)));
372        assert_eq!(
373            stream.next().await.expect("second semantic event").sequence,
374            2
375        );
376        assert_eq!(stream.next().await.expect("latest rate event").sequence, 4);
377        drop(rate_sender);
378        assert!(stream.next().await.is_none());
379    }
380}