Skip to main content

cortexkit_bus_client/
hub.rs

1use std::{sync::Arc, time::Duration};
2
3use async_nats::jetstream;
4use subc_client_rs::SubcConsumer;
5use tokio::sync::watch;
6
7use crate::{
8    credentials::{self, CredentialManager, HUB_DOMAIN},
9    BusClientOptions, Error, ManagedConnection, Result,
10};
11
12/// A module's separate federation-account connection to the hub.
13///
14/// Opening a [`crate::BusClient`] does not request a hub credential. Open a
15/// `HubClient` only when the module needs the hub. Dropping it stops its
16/// credential maintenance without affecting the box connection.
17pub struct HubClient {
18    managed: ManagedConnection,
19    manager: Arc<CredentialManager>,
20}
21
22impl HubClient {
23    /// Requests a hub credential over the module's existing daemon route.
24    ///
25    /// [`Error::HubUnavailable`] can be retried when the module next needs the
26    /// hub. [`Error::HubNotGranted`] is terminal. Neither refusal is retried here.
27    pub async fn connect(subc: Arc<SubcConsumer>, opts: BusClientOptions) -> Result<Self> {
28        let manager = credentials::module_manager(subc, &opts, true).await?;
29        Self::connect_manager(manager, opts.request_timeout).await
30    }
31
32    pub(crate) async fn connect_manager(
33        manager: Arc<CredentialManager>,
34        timeout: Duration,
35    ) -> Result<Self> {
36        let managed = ManagedConnection::connect(manager.clone(), timeout).await?;
37        Ok(Self { managed, manager })
38    }
39
40    /// Returns the current raw NATS client for core publishes. A held snapshot
41    /// does not follow credential replacements; get a new one after a change.
42    pub fn client(&self) -> Result<async_nats::Client> {
43        let stopped = self.managed.changes.has_changed().is_err();
44        self.manager.check_hub_refusal()?;
45        if stopped {
46            return Err(Error::Reply("hub credential maintenance stopped"));
47        }
48        Ok(self.managed.snapshot().client())
49    }
50
51    /// Returns a JetStream context on the current connection, in the `hub`
52    /// domain. Like [`Self::client`], it must be reopened after replacement.
53    pub fn jetstream(&self) -> Result<jetstream::Context> {
54        Ok(jetstream::with_domain(self.client()?, HUB_DOMAIN))
55    }
56
57    /// Notifies after a replacement connection is ready. The receiver closes
58    /// when maintenance stops, including after a hub refusal. Get a fresh
59    /// snapshot with [`Self::client`] to check for a typed refusal on closure;
60    /// after [`Error::HubUnavailable`], call [`Self::connect`] when ready to retry.
61    pub fn connection_changes(&self) -> watch::Receiver<u64> {
62        self.managed.changes.clone()
63    }
64}