Skip to main content

subc_client_rs/
module_subscription.rs

1//! Bounded channel-zero streams on a module's registered connection.
2
3use super::*;
4use subc_control::ScopeWatchRequest;
5
6pub(crate) struct ControlStreamSender {
7    events: mpsc::Sender<Frame>,
8    terminal: oneshot::Sender<Result<(), ScopeCallError>>,
9}
10
11struct ModuleControlSubscription {
12    shared: Arc<ModuleHandleShared>,
13    corr: u64,
14    events: mpsc::Receiver<Frame>,
15    terminal: Option<oneshot::Receiver<Result<(), ScopeCallError>>>,
16    finished: bool,
17}
18
19impl ModuleHandle {
20    /// Watch scope epochs on this registered connection. The initial snapshot
21    /// closes the gap for endings before open; subsequent events are terminal
22    /// for each selector. Drop or unsubscribe, then reopen to replace the set.
23    /// A lost connection ends the feed; open a new watch after registering again.
24    pub async fn scope_watch(
25        &self,
26        scopes: Vec<ScopeWatchSelector>,
27    ) -> Result<ScopeSubscription, ScopeCallError> {
28        let shared = self.shared();
29        crate::live_upgrade::ScopeRequest::check_fence(&shared)?;
30        if !shared.supports_scope_watch {
31            return Err(ScopeCallError::NotSupported {
32                op: subc_control::ops::SCOPE_WATCH,
33            });
34        }
35        let body = serde_json::to_vec(&ScopeWatchRequest::new(scopes))
36            .map_err(|err| ScopeCallError::Protocol(err.to_string()))?;
37        // One snapshot and at most 256 terminal events can arrive before the
38        // caller next polls; the reader must never block module RPC dispatch.
39        let mut inner = Self::control_subscribe(shared, body, 257).await?;
40        let first = timeout(CATALOG_UPDATE_TIMEOUT, inner.next())
41            .await
42            .map_err(|_| ScopeCallError::Timeout)??
43            .ok_or_else(|| {
44                ScopeCallError::Protocol("scope.watch ended before its snapshot".into())
45            })?;
46        if first.header.ty != FrameType::Response {
47            return Err(ScopeCallError::Protocol(
48                "scope.watch did not open with a snapshot RESPONSE".into(),
49            ));
50        }
51        let initial = serde_json::from_slice(&first.body).map_err(|err| {
52            ScopeCallError::Protocol(format!("invalid scope.watch snapshot: {err}"))
53        })?;
54        Ok(ScopeSubscription { initial, inner })
55    }
56
57    async fn control_subscribe(
58        shared: Arc<ModuleHandleShared>,
59        body: Vec<u8>,
60        capacity: usize,
61    ) -> Result<ModuleControlSubscription, ScopeCallError> {
62        let (events, rx) = mpsc::channel(capacity);
63        let (terminal, closed) = oneshot::channel();
64        let (corr, writer) = {
65            let mut state = shared.lock_inner();
66            if state.closed {
67                return Err(ScopeCallError::ConnectionClosed);
68            }
69            let writer = state
70                .writer
71                .clone()
72                .ok_or(ScopeCallError::ConnectionClosed)?;
73            let corr =
74                next_module_control_corr(&mut state).ok_or(ScopeCallError::ConnectionClosed)?;
75            state
76                .pending_control_streams
77                .insert(corr, ControlStreamSender { events, terminal });
78            (corr, writer)
79        };
80        let stream = ModuleControlSubscription {
81            shared: Arc::clone(&shared),
82            corr,
83            events: rx,
84            terminal: Some(closed),
85            finished: false,
86        };
87        let frame = Frame::build_with_version(
88            shared.negotiated_ver,
89            FrameType::Request,
90            Flags(control_flags().0 | subc_protocol::FLAG_SUBSCRIPTION),
91            0,
92            0,
93            corr,
94            body,
95        )
96        .map_err(|err| ScopeCallError::Protocol(err.to_string()))?;
97        timeout(CATALOG_UPDATE_TIMEOUT, shared.queue_request(&writer, frame))
98            .await
99            .map_err(|_| ScopeCallError::Timeout)?
100            .map_err(ScopeCallError::from_control_error)?;
101        Ok(stream)
102    }
103
104    pub(crate) fn handle_control_stream_frame(&self, frame: Frame) -> Option<Frame> {
105        let shared = self.shared();
106        let mut state = shared.lock_inner();
107        let corr = frame.header.corr;
108        let Some(stream) = state.pending_control_streams.remove(&corr) else {
109            return Some(frame);
110        };
111        let mut cancel = false;
112        let terminal = match frame.header.ty {
113            FrameType::Error => Err(match serde_json::from_slice::<ErrorBody>(&frame.body) {
114                Ok(body) => ScopeCallError::Refused {
115                    code: body.code,
116                    message: body.message,
117                },
118                Err(err) => ScopeCallError::Protocol(err.to_string()),
119            }),
120            FrameType::StreamEnd => Ok(()),
121            FrameType::Response | FrameType::StreamData => {
122                let last = frame.header.flags.is_last();
123                if stream.events.try_send(frame).is_err() {
124                    cancel = true;
125                    Err(ScopeCallError::Protocol(
126                        "module control subscription event buffer exhausted".into(),
127                    ))
128                } else if last {
129                    Ok(())
130                } else {
131                    state.pending_control_streams.insert(corr, stream);
132                    return None;
133                }
134            }
135            _ => {
136                state.pending_control_streams.insert(corr, stream);
137                return Some(frame);
138            }
139        };
140        let _ = stream.terminal.send(terminal);
141        let writer = cancel.then(|| state.writer.clone()).flatten();
142        drop(state);
143        if let Some(writer) = writer {
144            send_cancel(&shared, corr, writer);
145        }
146        None
147    }
148}
149
150impl ModuleControlSubscription {
151    async fn next(&mut self) -> Result<Option<Frame>, ScopeCallError> {
152        if self.finished {
153            return Ok(None);
154        }
155        if let Some(frame) = self.events.recv().await {
156            return Ok(Some(frame));
157        }
158        self.finished = true;
159        match self.terminal.take() {
160            Some(terminal) => terminal
161                .await
162                .unwrap_or(Err(ScopeCallError::ConnectionClosed))
163                .map(|()| None),
164            None => Ok(None),
165        }
166    }
167
168    fn cancel(&mut self) {
169        self.finished = true;
170        let writer = {
171            let mut state = self.shared.lock_inner();
172            if state.pending_control_streams.remove(&self.corr).is_none() {
173                return;
174            }
175            state.writer.clone()
176        };
177        if let Some(writer) = writer {
178            send_cancel(&self.shared, self.corr, writer);
179        }
180    }
181}
182
183fn send_cancel(shared: &ModuleHandleShared, corr: u64, writer: mpsc::Sender<Frame>) {
184    if let Ok(frame) = Frame::build_with_version(
185        shared.negotiated_ver,
186        FrameType::Cancel,
187        control_flags(),
188        0,
189        0,
190        corr,
191        vec![],
192    ) {
193        shared.connection_runtime.spawn(async move {
194            let _ = timeout(CATALOG_UPDATE_TIMEOUT, writer.send(frame)).await;
195        });
196    }
197}
198
199impl Drop for ModuleControlSubscription {
200    fn drop(&mut self) {
201        self.cancel();
202    }
203}
204
205/// A scope lifecycle feed on the module's registered connection. Initial
206/// states are available before any push; queued pushes precede terminal errors.
207pub struct ScopeSubscription {
208    pub initial: ScopeWatchResponse,
209    inner: ModuleControlSubscription,
210}
211
212impl ScopeSubscription {
213    pub async fn next(&mut self) -> Result<Option<ScopeWatchPush>, ScopeCallError> {
214        let Some(frame) = self.inner.next().await? else {
215            return Ok(None);
216        };
217        serde_json::from_slice(&frame.body)
218            .map(Some)
219            .map_err(|err| {
220                self.inner.cancel();
221                ScopeCallError::Protocol(format!("invalid scope.watch event: {err}"))
222            })
223    }
224
225    pub fn unsubscribe(&mut self) {
226        self.inner.cancel();
227    }
228}