Skip to main content

merry_runtime/events/
public_stream.rs

1//! Public runtime event stream wrapper.
2
3use super::{RuntimeEventProjector, RuntimeJournalEventStream};
4use crate::Runtime;
5use futures_core::Stream;
6use futures_util::StreamExt;
7use merry_core::RuntimeEvent;
8use std::{
9    pin::Pin,
10    task::{Context, Poll},
11};
12use tokio::sync::watch;
13use tokio::{sync::mpsc, task::JoinHandle};
14use tokio_stream::wrappers::ReceiverStream;
15use tokio_stream::wrappers::WatchStream;
16
17/// Stream of SDK-facing runtime events.
18///
19/// Dropping this stream aborts its projection task. The projection task owns the
20/// underlying journal stream, so aborting it drops the journal stream and
21/// preserves existing runtime-step cancellation behavior. Semantic events are
22/// buffered in order; output-rate events are latest-only telemetry and may be
23/// coalesced while the consumer is busy.
24pub struct RuntimeEventStream {
25    inner: Option<ReceiverStream<RuntimeEvent>>,
26    rate_updates: WatchStream<Option<RuntimeEvent>>,
27    rate_updates_closed: bool,
28    pending_rate_update: Option<RuntimeEvent>,
29    producer_handle: Option<JoinHandle<()>>,
30}
31
32impl RuntimeEventStream {
33    pub(crate) fn new(
34        journal_stream: RuntimeJournalEventStream,
35        runtime: Runtime,
36        buffer_size: usize,
37    ) -> Self {
38        let (sender, receiver) = mpsc::channel(buffer_size);
39        let (rate_sender, rate_receiver) = watch::channel(None);
40        let producer_handle = tokio::spawn(async move {
41            project_journal_stream(journal_stream, runtime, sender, rate_sender).await;
42        });
43
44        Self {
45            inner: Some(ReceiverStream::new(receiver)),
46            rate_updates: WatchStream::from_changes(rate_receiver),
47            rate_updates_closed: false,
48            pending_rate_update: None,
49            producer_handle: Some(producer_handle),
50        }
51    }
52}
53
54impl Stream for RuntimeEventStream {
55    type Item = RuntimeEvent;
56
57    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
58        if !self.rate_updates_closed {
59            match Pin::new(&mut self.rate_updates).poll_next(cx) {
60                Poll::Ready(Some(Some(event))) => self.pending_rate_update = Some(event),
61                Poll::Ready(Some(None)) => {}
62                Poll::Ready(None) => self.rate_updates_closed = true,
63                Poll::Pending => {}
64            }
65        }
66
67        if let Some(inner) = self.inner.as_mut() {
68            match Pin::new(inner).poll_next(cx) {
69                Poll::Ready(Some(event)) => return Poll::Ready(Some(event)),
70                Poll::Ready(None) => self.inner = None,
71                Poll::Pending => {
72                    if let Some(event) = self.pending_rate_update.take() {
73                        return Poll::Ready(Some(event));
74                    }
75                }
76            }
77        }
78
79        if let Some(event) = self.pending_rate_update.take() {
80            return Poll::Ready(Some(event));
81        }
82        if self.inner.is_none() && self.rate_updates_closed {
83            self.producer_handle.take();
84            return Poll::Ready(None);
85        }
86        Poll::Pending
87    }
88}
89
90impl Drop for RuntimeEventStream {
91    fn drop(&mut self) {
92        self.inner.take();
93
94        if let Some(handle) = self.producer_handle.take() {
95            handle.abort();
96        }
97    }
98}
99
100async fn project_journal_stream(
101    mut journal_stream: RuntimeJournalEventStream,
102    runtime: Runtime,
103    sender: mpsc::Sender<RuntimeEvent>,
104    rate_sender: watch::Sender<Option<RuntimeEvent>>,
105) {
106    let mut projector = RuntimeEventProjector::new();
107
108    while let Some(journal_event) = journal_stream.next().await {
109        let public_event = projector.project(journal_event, &runtime).await;
110
111        let Ok(Some(public_event)) = public_event else {
112            continue;
113        };
114
115        if matches!(&public_event, RuntimeEvent::ModelOutputRateUpdated { .. }) {
116            rate_sender.send_replace(Some(public_event));
117        } else if sender.send(public_event).await.is_err() {
118            break;
119        }
120    }
121}