Skip to main content

subc_client_rs/consumer/
catalog.rs

1use super::*;
2use subc_control::{CatalogWatchRequest, CatalogWatchResponse};
3
4impl SubcConsumer {
5    /// Target authority captured on this live route's open reply. An older
6    /// daemon, an incomplete target, or a retired handle provides no target authority.
7    /// Catalog entries are discovery facts, not a substitute for this value.
8    pub fn route_target(&self, handle: &RouteHandle) -> Option<RouteOpenTarget> {
9        let inner = self.shared.lock_inner();
10        if inner.writer.is_none()
11            || inner.route_epochs.get(&handle.channel) != Some(handle)
12            || inner.retired_routes.contains(handle)
13        {
14            return None;
15        }
16        inner.route_targets.get(handle).cloned()
17    }
18
19    /// Follow catalog generations on channel 0. The first response carries the
20    /// current generation; later advances may coalesce. Reconnect ends the feed:
21    /// open a new watch and refresh the catalog rather than assuming no changes.
22    pub async fn catalog_watch(&self) -> Result<CatalogSubscription, CallError> {
23        let deadline = Instant::now() + self.shared.opts.call_timeout;
24        let body = serde_json::to_vec(&CatalogWatchRequest::new())
25            .map_err(|err| CallError::not_sent(err.to_string()))?;
26        loop {
27            self.shared.ensure_connected_for_call(deadline).await?;
28            let permit = Arc::new(Semaphore::new(1))
29                .acquire_owned()
30                .await
31                .map_err(|_| CallError::not_sent("catalog subscription permit closed"))?;
32            match self
33                .shared
34                .send_subscription(SubscriptionSend {
35                    expected_handle: None,
36                    channel: 0,
37                    epoch: 0,
38                    body: body.clone(),
39                    priority: Priority::Interactive,
40                    admission_class: AdmissionClass::Normal,
41                    event_buffer: DEFAULT_SUBSCRIPTION_EVENT_BUFFER,
42                    deadline,
43                    permit: RoutePermit::legacy(permit),
44                })
45                .await
46            {
47                Ok(inner) => {
48                    return Ok(CatalogSubscription {
49                        inner,
50                        finished: false,
51                    })
52                }
53                Err(err) if err.is_not_sent() && Instant::now() < deadline => continue,
54                Err(err) => return Err(err),
55            }
56        }
57    }
58}
59
60/// A held catalog generation feed. Drop or unsubscribe to cancel it. Queued
61/// generations are delivered before a terminal refusal or connection failure.
62pub struct CatalogSubscription {
63    inner: Subscription,
64    finished: bool,
65}
66
67impl CatalogSubscription {
68    /// Read the next generation, retaining daemon refusal codes in `CallError`.
69    /// Once the feed ends, subsequent reads return `Ok(None)`.
70    pub async fn next(&mut self) -> Result<Option<CatalogWatchResponse>, CallError> {
71        if self.finished {
72            return Ok(None);
73        }
74        if let Some(body) = self.inner.events().recv().await {
75            return serde_json::from_slice(&body).map(Some).map_err(|err| {
76                self.finished = true;
77                let _ = self.inner.unsubscribe();
78                CallError::invalid_response(format!("invalid catalog.watch response: {err}"))
79            });
80        }
81        self.finished = true;
82        self.inner.closed().await.map(|()| None)
83    }
84
85    pub fn unsubscribe(&self) -> Result<(), CallError> {
86        self.inner.unsubscribe()
87    }
88}
89
90pub(super) fn decode_route_open_response(
91    body: &[u8],
92) -> serde_json::Result<(ClientControlResponse, RouteOpenReplyExt)> {
93    let value = serde_json::from_slice(body)?;
94    let authority = RouteOpenReplyExt::read_from(&value)?;
95    Ok((serde_json::from_value(value)?, authority))
96}