1
use std::future::Future;
2

            
3
use futures::FutureExt;
4

            
5
use crate::{Frame, Framer, Protocol};
6

            
7
pub struct RpcCall<P: Protocol> {
8
    pub tag: u16,
9
    pub future: RpcFuture<P>,
10
}
11

            
12
/// Either a call that reached the lane, or one that could not.
13
///
14
/// r[impl jetstream.subscription.dispatch.issue-order]
15
/// Queuing the request is what fixes issue order, and queuing can fail
16
/// when the lane is closed. That has to resolve the caller's future as
17
/// an error rather than panic in a detached task, which is what the
18
/// spawned send used to do.
19
pub enum RpcFuture<P: Protocol> {
20
    Waiting(
21
        tokio::sync::oneshot::Receiver<
22
            jetstream_error::Result<Frame<P::Response>>,
23
        >,
24
    ),
25
    Failed(Option<jetstream_error::Error>),
26
}
27

            
28
impl<P: Protocol> Future for RpcCall<P> {
29
    type Output = jetstream_error::Result<Frame<P::Response>>;
30

            
31
1152
    fn poll(
32
1152
        self: std::pin::Pin<&mut Self>,
33
1152
        cx: &mut std::task::Context<'_>,
34
1152
    ) -> std::task::Poll<Self::Output> {
35
1152
        let this = self.get_mut();
36
1152
        let rx = match &mut this.future {
37
1152
            RpcFuture::Waiting(rx) => rx,
38
            RpcFuture::Failed(err) => {
39
                let err = err.take().unwrap_or_else(|| {
40
                    jetstream_error::Error::new("the lane is closed")
41
                });
42
                return std::task::Poll::Ready(Err(err));
43
            }
44
        };
45
1152
        match rx.poll_unpin(cx) {
46
            std::task::Poll::Ready(Ok(result)) => {
47
343
                std::task::Poll::Ready(result)
48
            }
49
            std::task::Poll::Ready(Err(err)) => {
50
                std::task::Poll::Ready(Err(jetstream_error::Error::with_code(
51
                    err.to_string(),
52
                    "jetstream::mux::error",
53
                )))
54
            }
55
809
            std::task::Poll::Pending => std::task::Poll::Pending,
56
        }
57
1152
    }
58
}
59

            
60
/// The caller's end of a subscription: many responses under one tag.
61
///
62
/// r[impl jetstream.subscription.surface]
63
/// A `Stream`, because that is what Rust callers already know how to
64
/// consume, and `r[jetstream.subscription.surface]` requires the
65
/// language's idiomatic asynchronous sequence rather than a JetStream
66
/// shape they must learn.
67
///
68
/// r[impl jetstream.subscription.surface.cancellation]
69
/// Dropping it abandons the subscription. Sending the cancellation frame
70
/// that tells the *producer* is not done here yet — see the note on
71
/// `Drop` below — so this is not yet the whole of what `cancel`
72
/// requires.
73
pub struct RpcStream<P: Protocol> {
74
    pub tag: u16,
75
    /// r[impl jetstream.subscription.identity]
76
    /// Which subscription this stream is, independent of the tag it
77
    /// happens to occupy. A tag is reused once its terminator frees it,
78
    /// so identity cannot be the number alone.
79
    pub(crate) binding: u64,
80
    pub(crate) items: tokio::sync::mpsc::Receiver<
81
        jetstream_error::Result<Frame<P::Response>>,
82
    >,
83
    pub(crate) in_flight: crate::mux::InFlight<P>,
84
    /// Where a dropped subscription's tag goes to be cancelled.
85
    ///
86
    /// A `u16` rather than a built request, because `Drop` is
87
    /// synchronous: building the cancellation needs nothing async, but
88
    /// *sending* it needs a tag of its own, and acquiring one may wait.
89
    /// The `Mux`'s cancellation task does the waiting.
90
    pub(crate) cancels: tokio::sync::mpsc::UnboundedSender<u16>,
91
    /// Whether the terminator has already arrived. A subscription that
92
    /// ended has nothing to cancel, and cancelling it anyway costs a tag
93
    /// and a round trip on every completed subscription.
94
    pub(crate) finished: bool,
95
    /// A request that never reached the lane, delivered as the stream's
96
    /// one item so the caller does not read a failure as a clean end.
97
    pub(crate) failed: Option<jetstream_error::Error>,
98
}
99

            
100
impl<P: Protocol> futures::Stream for RpcStream<P> {
101
    type Item = jetstream_error::Result<Frame<P::Response>>;
102

            
103
1550
    fn poll_next(
104
1550
        mut self: std::pin::Pin<&mut Self>,
105
1550
        cx: &mut std::task::Context<'_>,
106
1550
    ) -> std::task::Poll<Option<Self::Item>> {
107
        // A request that never reached the lane. There is no producer
108
        // to cancel and no terminator coming, so this is also the end.
109
1550
        if let Some(err) = self.failed.take() {
110
            self.finished = true;
111
            return std::task::Poll::Ready(Some(Err(err)));
112
1550
        }
113
1550
        let polled = self.items.poll_recv(cx);
114
        // r[impl jetstream.subscription.termination]
115
1550
        if let std::task::Poll::Ready(end) = &polled {
116
450
            self.finished = match end {
117
                Some(Ok(frame)) => {
118
449
                    frame.msg.message_type() == crate::subscription::RDONE
119
                }
120
                // An error item, or the channel closed under us: either
121
                // way no terminator is coming and there is nothing left
122
                // to cancel.
123
1
                _ => true,
124
            };
125
1100
        }
126
1550
        polled
127
1550
    }
128
}
129

            
130
impl<P: Protocol> Drop for RpcStream<P> {
131
628
    fn drop(&mut self) {
132
        // r[impl jetstream.subscription.identity]
133
        // Mark the tag abandoned rather than freeing it. The producer may
134
        // still be emitting under it, and an in-lane item carries no
135
        // binding identifier, so a tag rebound now would collect the old
136
        // subscription's frames. The terminator frees it.
137
        //
138
        // `Drop` is synchronous, so this cannot await the map. A
139
        // `try_lock` that fails leaves the waiter in place, which is the
140
        // safe direction: frames are delivered to a receiver nobody
141
        // reads, and the terminator still frees the tag.
142
        //
143
        // r[impl jetstream.subscription.identity]
144
        // And only if the slot is still *this* subscription's. Once a
145
        // terminator frees a tag the number goes back to the pool and
146
        // another subscription can take it, so a stream dropped after
147
        // its terminator would otherwise abandon a stranger's waiter and
148
        // silence a subscription that had done nothing wrong. Matching
149
        // on the binding rather than the tag is what makes the drop
150
        // safe; a stale holder finds no match and leaves the slot alone.
151
628
        if let Ok(mut map) = self.in_flight.try_lock() {
152
628
            let ours = matches!(
153
628
                map.get(&self.tag),
154
                Some(crate::mux::Waiter::Streaming { binding, .. })
155
624
                    if *binding == self.binding
156
            );
157
628
            if ours {
158
624
                map.insert(self.tag, crate::mux::Waiter::Abandoned);
159
4
            }
160
        }
161

            
162
        // r[impl jetstream.subscription.surface.cancellation]
163
        // r[impl jetstream.subscription.cancel]
164
        // Marking the tag abandoned only stops *delivery*. The producer
165
        // is still working, and cancellation is required to reach the
166
        // work — so the drop a Rust caller uses to cancel has to send the
167
        // cancellation, not merely stop reading. Without this the rule
168
        // was unimplemented end to end: the service never heard.
169
628
        if self.finished {
170
3
            return;
171
625
        }
172
625
        if self.cancels.send(self.tag).is_err() {
173
            // The client is shutting down, or more subscriptions were
174
            // dropped at once than the queue holds. The producer learns
175
            // when the lane closes, which is the same conclusion by a
176
            // slower route.
177
            tracing::debug!(tag = self.tag, "cancellation not queued");
178
625
        }
179
628
    }
180
}