cortexkit_claustrum_client/
watch.rs1use super::*;
2use serde::{Deserialize, Deserializer};
3use tokio::sync::{mpsc, oneshot};
4
5#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
6#[serde(rename_all = "snake_case")]
7pub enum ScopedWatchKind {
8 Changed,
9}
10
11#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
12#[serde(deny_unknown_fields)]
13pub struct ScopedWatchNotice {
14 pub kind: ScopedWatchKind,
15 #[serde(deserialize_with = "nonempty_epoch")]
16 pub epoch: String,
17 #[serde(deserialize_with = "positive_safe_seq")]
18 pub seq: u64,
19 pub view: String,
20 pub keys: String,
21}
22
23pub type WatchNotice = ScopedWatchNotice;
25
26impl ScopedWatchNotice {
27 pub fn decode(bytes: &[u8]) -> Result<Self, serde_json::Error> {
28 serde_json::from_slice(bytes)
29 }
30}
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum WatchAction {
34 Reread { inventory: bool, keys: bool },
35 ResubscribeAndReread,
36 ReadListOnce,
37 ReconnectAndReread,
38 Fallback,
39 RetryLater,
40 Stop,
41}
42
43#[derive(Debug, Default)]
46pub struct WatchTracker {
47 view: Option<String>,
48 keys: Option<String>,
49 last: Option<(String, u64)>,
50 notices: bool,
51 closed: bool,
52 awaiting_list: bool,
53}
54
55impl WatchTracker {
56 pub fn inventory_read(&mut self, view: impl Into<String>) {
57 self.view = Some(view.into());
58 }
59 pub fn keys_read(&mut self, keys: impl Into<String>) {
60 self.keys = Some(keys.into());
61 }
62
63 pub fn opened(&mut self) {
64 self.notices = false;
65 self.closed = false;
66 self.awaiting_list = false;
67 self.last = None;
68 }
69
70 pub fn notice(&mut self, notice: &WatchNotice) -> WatchAction {
71 if self.closed {
72 return WatchAction::Stop;
73 }
74 let discontinuity = self.last.as_ref().is_none_or(|(epoch, seq)| {
75 epoch != ¬ice.epoch || seq.checked_add(1) != Some(notice.seq)
76 });
77 let inventory = discontinuity || self.view.as_deref() != Some(¬ice.view);
78 let keys = self.keys.as_deref() != Some(¬ice.keys);
79 self.last = Some((notice.epoch.clone(), notice.seq));
80 self.notices = true;
81 WatchAction::Reread { inventory, keys }
82 }
83
84 pub fn closed(&mut self) -> WatchAction {
85 if self.closed {
86 return WatchAction::Stop;
87 }
88 self.closed = true;
89 self.awaiting_list = !self.notices;
90 if self.notices {
91 WatchAction::ResubscribeAndReread
92 } else {
93 WatchAction::ReadListOnce
94 }
95 }
96
97 pub fn list_result(&mut self, accepted: bool) -> WatchAction {
100 if !self.awaiting_list {
101 return WatchAction::Stop;
102 }
103 self.awaiting_list = false;
104 self.closed = true;
105 if accepted {
106 WatchAction::RetryLater
107 } else {
108 WatchAction::Stop
109 }
110 }
111
112 pub fn route_lost(&mut self) -> WatchAction {
113 if self.closed && !self.awaiting_list {
114 return WatchAction::Stop;
115 }
116 self.awaiting_list = false;
117 self.closed = true;
118 WatchAction::ReconnectAndReread
119 }
120
121 pub fn unknown_method(&mut self) -> WatchAction {
122 self.awaiting_list = false;
123 self.closed = true;
124 WatchAction::Fallback
125 }
126
127 pub fn refused(&mut self) -> WatchAction {
128 self.awaiting_list = false;
129 self.closed = true;
130 WatchAction::Stop
131 }
132}
133
134fn nonempty_epoch<'de, D: Deserializer<'de>>(decoder: D) -> Result<String, D::Error> {
135 let epoch = String::deserialize(decoder)?;
136 if epoch.is_empty() {
137 return Err(serde::de::Error::custom("empty watch epoch"));
138 }
139 Ok(epoch)
140}
141
142fn positive_safe_seq<'de, D: Deserializer<'de>>(decoder: D) -> Result<u64, D::Error> {
143 let seq = u64::deserialize(decoder)?;
144 if seq == 0 || seq > 9_007_199_254_740_991 {
145 return Err(serde::de::Error::custom(
146 "watch seq is not a positive safe integer",
147 ));
148 }
149 Ok(seq)
150}
151
152#[derive(Debug)]
153pub enum ScopedWatchOutcome {
154 Refused(CredentialResolverError),
155 Ended,
156 NotAccepting,
157 TransportLost(CredentialResolverError),
158 Unsupported,
159 InvalidNotice,
160 InvalidResponse(CredentialResolverError),
161 Stopped,
162}
163
164pub struct ScopedWatch {
167 events: mpsc::Receiver<ScopedWatchNotice>,
168 closed: oneshot::Receiver<ScopedWatchOutcome>,
169 stop: Option<oneshot::Sender<()>>,
170}
171
172impl ScopedWatch {
173 pub async fn next(&mut self) -> Option<ScopedWatchNotice> {
174 self.events.recv().await
175 }
176
177 pub fn stop(&mut self) {
178 if let Some(stop) = self.stop.take() {
179 let _ = stop.send(());
180 }
181 }
182
183 pub async fn closed(&mut self) -> ScopedWatchOutcome {
184 (&mut self.closed).await.unwrap_or_else(|_| {
185 ScopedWatchOutcome::TransportLost(CredentialResolverError::transport(
186 "scoped watch task ended without an outcome",
187 ))
188 })
189 }
190}
191
192impl Drop for ScopedWatch {
193 fn drop(&mut self) {
194 self.stop();
195 }
196}
197
198fn params(enrollment_token: Option<&str>) -> Value {
199 enrollment_token.map_or_else(|| json!({}), |token| json!({"enrollment_token": token}))
200}
201
202impl ClaustrumConsumer {
203 pub(super) async fn start_scoped_watch(
204 mut self,
205 enrollment_token: Option<String>,
206 ) -> Result<ScopedWatch, CredentialResolverError> {
207 let corr = self.next_correlation();
208 self.write_request(
209 self.route_channel,
210 self.route_epoch,
211 corr,
212 Priority::Interactive,
213 json!({"method":"auth.watch_scoped", "params":params(enrollment_token.as_deref())}),
214 )
215 .await?;
216 let (events, receiver) = mpsc::channel(32);
217 let (closed, outcome) = oneshot::channel();
218 let (stop, mut stopped) = oneshot::channel();
219 tokio::spawn(async move {
220 let result = tokio::select! {
221 biased;
222 _ = &mut stopped => ScopedWatchOutcome::Stopped,
223 result = self.read_scoped_watch(corr, enrollment_token.as_deref(), &events) => result,
224 };
225 if let Ok(cancel) = Frame::build(
227 FrameType::Cancel,
228 Flags::new(false, Priority::Interactive, false),
229 self.route_channel,
230 self.route_epoch,
231 corr,
232 vec![],
233 ) {
234 let _ = tokio::time::timeout(
235 CREDENTIAL_READ_TIMEOUT,
236 write_frame(&mut self.stream, &cancel),
237 )
238 .await;
239 }
240 drop(events);
241 let _ = closed.send(result);
242 });
243 Ok(ScopedWatch {
244 events: receiver,
245 closed: outcome,
246 stop: Some(stop),
247 })
248 }
249
250 async fn read_scoped_watch(
251 &mut self,
252 corr: u64,
253 enrollment_token: Option<&str>,
254 events: &mpsc::Sender<ScopedWatchNotice>,
255 ) -> ScopedWatchOutcome {
256 let mut tracker = WatchTracker::default();
257 loop {
258 let frame = match read_frame(&mut self.stream).await {
259 Ok(Some(frame)) => frame,
260 _ => {
261 return ScopedWatchOutcome::TransportLost(CredentialResolverError::transport(
262 "scoped watch connection lost",
263 ))
264 }
265 };
266 if frame.header.channel != self.route_channel || frame.header.epoch != self.route_epoch
267 {
268 continue;
269 }
270 if frame.header.ty == FrameType::Goodbye {
271 return ScopedWatchOutcome::TransportLost(CredentialResolverError::unclassified(
272 "route_closed",
273 "scoped watch route closed",
274 ));
275 }
276 if frame.header.corr != corr {
277 continue;
278 }
279 match frame.header.ty {
280 FrameType::StreamData => {
281 let notice = match WatchNotice::decode(&frame.body) {
282 Ok(notice) => notice,
283 Err(_) => return ScopedWatchOutcome::InvalidNotice,
284 };
285 tracker.notice(¬ice);
286 if events.try_send(notice).is_err() {
287 return ScopedWatchOutcome::TransportLost(
288 CredentialResolverError::transport("scoped watch consumer lagged"),
289 );
290 }
291 }
292 FrameType::Response => {
293 let value = serde_json::from_slice(&frame.body).unwrap_or(Value::Null);
294 if value.get("result").and_then(|r| r.get("error")).is_some() {
295 tracker.refused();
296 return ScopedWatchOutcome::Refused(
297 decode_list_scoped_reply(value).unwrap_err(),
298 );
299 }
300 return ScopedWatchOutcome::InvalidResponse(invalid_listing(
301 "unexpected watch response",
302 ));
303 }
304 FrameType::StreamEnd => {
305 if tracker.closed() == WatchAction::ResubscribeAndReread {
306 return ScopedWatchOutcome::Ended;
307 }
308 let response = self.credential_request(json!({"method":CREDENTIAL_LIST_SCOPED_OP, "params":params(enrollment_token)}), CREDENTIAL_LIST_SCOPED_OP).await;
309 return match response {
310 Ok(value) => {
311 let refused =
312 value.get("result").and_then(|r| r.get("error")).is_some();
313 match decode_list_scoped_reply(value) {
314 Ok(_) => {
315 tracker.list_result(true);
316 ScopedWatchOutcome::NotAccepting
317 }
318 Err(error) if refused => {
319 tracker.list_result(false);
320 ScopedWatchOutcome::Refused(error)
321 }
322 Err(error) => ScopedWatchOutcome::InvalidResponse(error),
323 }
324 }
325 Err(error) => ScopedWatchOutcome::TransportLost(error),
326 };
327 }
328 FrameType::Error => {
329 let value = serde_json::from_slice::<Value>(&frame.body).unwrap_or(Value::Null);
330 if value.get("code").and_then(Value::as_str) == Some("unknown_method") {
331 tracker.unknown_method();
332 return ScopedWatchOutcome::Unsupported;
333 }
334 tracker.route_lost();
335 return ScopedWatchOutcome::TransportLost(decode_wire_error(&frame.body));
336 }
337 _ => {}
338 }
339 }
340 }
341}
342
343#[cfg(test)]
344mod tests;