tembra_runtime/portable/stream.rs
1//! A host-issued byte stream end at the native portable boundary.
2//!
3//! An issuing executor wraps its bounded producer in a [`ByteSource`] and returns the end as a
4//! payload attachment, together with the call's physical work in an [`super::Outcome`]. The
5//! receiving caller decodes one [`ByteStream`]. The end belongs to the root that received it:
6//! the root's end closes it and makes it refuse reads, and the root's cancellation fails it
7//! with that cancellation at once, including a read that is already waiting. It never carries
8//! the producer's physical work: dropping or closing it only asks the producer to stop, and the
9//! producer's call keeps settling under its own invocation.
10use crate::{Error, Result, core, core::Reason};
11use std::{
12 cell::RefCell,
13 pin::Pin,
14 rc::Rc,
15 task::{Context, Poll, Waker},
16};
17
18/// The producing side of one byte stream, supplied by its issuer.
19///
20/// A writer learns that the consumer stopped only at its next stream operation; the source
21/// cannot cancel an idle producer, which ends at its call's own timeout.
22///
23/// # Issuer obligations
24///
25/// - **Termination.** Whenever the issuer's physical work ends, for any reason (return, error,
26/// panic, or the work being dropped), the source must resolve both sides: a waiting or later
27/// [`poll_next`](ByteSource::poll_next) yields `Err` unless the producer had already ended
28/// cleanly, and [`poll_closed`](ByteSource::poll_closed) becomes `Ready`. The framework
29/// cannot do this itself: it has no link from the physical work to the source. The issuer
30/// needs a drop guard on its physical side for this.
31/// - **Failure is never a clean end.** A failed, trapped or timed-out producer yields `Err`,
32/// never `None`. The `Err` item is terminal; reads after it yield `None`.
33/// - **A clean end is only the body's end.** It does not mean the producer's call succeeded; a
34/// later failure reaches `Host::errors` and the result of [`ByteStream::close`]. A close the
35/// consumer asked for should settle as `Ok` unless the producer itself failed, since every
36/// recorded failure also fails `Host::close`.
37/// - **No re-entry.** Every method runs while the stream end is borrowed. A source must not call
38/// back into the host synchronously (for example through actions that end or cancel a
39/// root); it may only store wakers and buffer state, and wake them.
40pub trait ByteSource: 'static {
41 /// The next chunk, `None` once the producer ended cleanly, or the producer's failure.
42 /// Returns `Pending` with the waker stored when no chunk is buffered.
43 fn poll_next(&mut self, context: &mut Context<'_>) -> Poll<Option<Result<Vec<u8>>>>;
44
45 /// The consumer will read no more. Called at most once.
46 fn close(&mut self);
47
48 /// Ready once the producer has physically stopped after [`ByteSource::close`] or its own
49 /// end, with its final outcome (an error or a timeout of the producer's call, for example).
50 fn poll_closed(&mut self, context: &mut Context<'_>) -> Poll<Result<()>>;
51}
52
53enum State {
54 Open,
55 /// The producer ended cleanly or failed; the error was reported once.
56 Finished,
57 /// The receiving root ended: the end is unusable.
58 Expired,
59 /// The receiving root was cancelled.
60 Cancelled,
61}
62
63struct Shared {
64 source: Box<dyn ByteSource>,
65 state: State,
66 /// The close request was given to the source.
67 closed: bool,
68 reader: Option<Waker>,
69}
70
71impl Shared {
72 fn close_once(&mut self) {
73 if !self.closed {
74 self.closed = true;
75 self.source.close();
76 }
77 }
78}
79
80/// One end of a host-issued byte stream. It is linear: not `Clone`, and dropping it asks the
81/// producer to stop exactly once.
82pub struct ByteStream(Rc<RefCell<Shared>>);
83
84impl ByteStream {
85 /// Issue a stream end over `source`. Only its first decoded holder can read it.
86 pub fn new(source: impl ByteSource) -> Self {
87 Self(Rc::new(RefCell::new(Shared {
88 source: Box::new(source),
89 state: State::Open,
90 closed: false,
91 reader: None,
92 })))
93 }
94
95 /// Stop reading and wait until the producer has physically stopped, returning its final
96 /// outcome. Nothing is read after the close request.
97 pub async fn close(self) -> Result<()> {
98 self.0.borrow_mut().close_once();
99 let shared = self.0.clone();
100 futures::future::poll_fn(move |context| shared.borrow_mut().source.poll_closed(context))
101 .await
102 }
103
104 pub(crate) fn root_stream(&self) -> std::rc::Weak<dyn RootStream> {
105 let shared: Rc<dyn RootStream> = self.0.clone();
106 Rc::downgrade(&shared)
107 }
108}
109
110impl futures::Stream for ByteStream {
111 type Item = Result<Vec<u8>>;
112
113 /// Chunks in order, then `None` after a clean end. A cancelled or expired end yields an
114 /// error, never a clean end.
115 fn poll_next(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Option<Self::Item>> {
116 let mut shared = self.0.borrow_mut();
117 match shared.state {
118 State::Open => {}
119 State::Finished => return Poll::Ready(None),
120 State::Expired => return Poll::Ready(Some(Err(expired()))),
121 State::Cancelled => return Poll::Ready(Some(Err(cancelled()))),
122 }
123 shared.reader = Some(context.waker().clone());
124 let next = shared.source.poll_next(context);
125 if matches!(next, Poll::Ready(None | Some(Err(_)))) {
126 shared.state = State::Finished;
127 }
128 next
129 }
130}
131
132impl Drop for ByteStream {
133 fn drop(&mut self) {
134 self.0.borrow_mut().close_once();
135 }
136}
137
138/// Root events reaching a delivered stream end through the host's root registry.
139pub(crate) trait RootStream {
140 /// The root ended: close the producer and refuse every later read.
141 fn end_root(&self);
142 /// The root was cancelled: close the producer and fail reads with the cancellation.
143 fn cancel_root(&self);
144}
145
146impl RootStream for RefCell<Shared> {
147 fn end_root(&self) {
148 settle(self, State::Expired);
149 }
150
151 fn cancel_root(&self) {
152 settle(self, State::Cancelled);
153 }
154}
155
156/// Move an open end into a terminal root state, close its producer and wake a waiting read.
157fn settle(cell: &RefCell<Shared>, state: State) {
158 let reader = {
159 let mut shared = cell.borrow_mut();
160 if matches!(shared.state, State::Open) {
161 shared.state = state;
162 }
163 shared.close_once();
164 shared.reader.take()
165 };
166 if let Some(reader) = reader {
167 reader.wake();
168 }
169}
170
171fn expired() -> Error {
172 Error::new(
173 core::Code::Expired,
174 Reason::Root,
175 "the stream's root has ended",
176 )
177}
178
179fn cancelled() -> Error {
180 Error::new(
181 core::Code::Cancelled,
182 Reason::Root,
183 "the stream's root was cancelled",
184 )
185}