Skip to main content

aft_base/
registration.rs

1//! Consumer identity readiness shared with the daemon registration channel.
2
3use std::path::Path;
4use std::sync::atomic::{AtomicBool, Ordering};
5use std::sync::OnceLock;
6use std::time::Duration;
7
8use subc_client_rs::registration::ClaimError;
9use subc_client_rs::{ConsumerError, ConsumerOptions, SubcConsumer};
10use tokio::sync::Notify;
11
12const READY_BUDGET: Duration = Duration::from_secs(5);
13
14static REGISTRATION: OnceLock<IdentityReady> = OnceLock::new();
15
16#[derive(Default)]
17struct IdentityReady {
18    installed: AtomicBool,
19    changed: Notify,
20}
21
22impl IdentityReady {
23    fn install(&self) {
24        self.installed.store(true, Ordering::Release);
25        self.changed.notify_waiters();
26    }
27
28    fn is_ready(&self) -> bool {
29        self.installed.load(Ordering::Acquire)
30    }
31
32    async fn wait(&self, budget: Duration) -> Result<(), ClaimError> {
33        tokio::time::timeout(budget, async {
34            // Subscribe before checking state so installation cannot be missed.
35            let changed = self.changed.notified();
36            if !self.is_ready() {
37                changed.await;
38            }
39        })
40        .await
41        .map_err(|_| ClaimError::Unavailable)
42    }
43}
44
45pub fn identity_ready() -> bool {
46    REGISTRATION
47        .get()
48        .map_or_else(crate::launch_nonce::was_captured, IdentityReady::is_ready)
49}
50
51pub fn module_id() -> Option<String> {
52    std::env::var(subc_protocol::SUBC_MODULE_ID_ENV)
53        .ok()
54        .filter(|value| !value.trim().is_empty())
55}
56
57/// Can use module identity now, or wait until the daemon can issue claims for consumers.
58/// Preserve the legacy gate for processes not launched with module identity.
59pub fn module_consumer_allowed() -> bool {
60    module_id().is_some() && (REGISTRATION.get().is_some() || identity_ready())
61}
62
63/// Open a daemon consumer connection on behalf of `owner`, a fixed label naming
64/// the part of AFT that holds it (see [`track_consumer`]).
65pub async fn connect_consumer(
66    owner: &'static str,
67    path: &Path,
68    options: ConsumerOptions,
69) -> Result<SubcConsumer, ConsumerError> {
70    if let Some(ready) = REGISTRATION.get() {
71        ready
72            .wait(READY_BUDGET)
73            .await
74            .map_err(|error| ConsumerError::Connect {
75                path: path.to_path_buf(),
76                endpoint: "claim binding".into(),
77                source: std::io::Error::other(error),
78            })?;
79    }
80    match SubcConsumer::connect(path, options).await {
81        Ok(consumer) => {
82            track_consumer(owner, &consumer);
83            Ok(consumer)
84        }
85        Err(error) => {
86            log_claim_connect_failure(owner, &error);
87            Err(error)
88        }
89    }
90}
91
92/// The claim failure behind a consumer connect error, if it was one. The SDK
93/// wraps every claim failure as a `Connect` error whose source is the
94/// [`ClaimError`], and its message reads the same for every cause.
95fn connect_claim_error(error: &ConsumerError) -> Option<&ClaimError> {
96    match error {
97        ConsumerError::Connect { source, .. } => source.get_ref()?.downcast_ref::<ClaimError>(),
98        _ => None,
99    }
100}
101
102/// A short fixed label for a claim failure, for logs only. The daemon's
103/// refusal code is a fixed identifier, never a message or secret.
104pub fn claim_cause(error: &ClaimError) -> String {
105    match error {
106        ClaimError::Refused { code } => format!("refused code={code}"),
107        ClaimError::Unavailable => "unavailable".into(),
108        ClaimError::Timeout => "timeout".into(),
109        ClaimError::Protocol => "protocol".into(),
110        ClaimError::Handoff => "handoff".into(),
111        ClaimError::PrefixChildConsumer => "prefix_child_consumer".into(),
112        _ => "other".into(),
113    }
114}
115
116/// Log why a consumer connection failed to bind its claim. Callers' own error
117/// text stays unchanged; this line only records the cause the SDK's message hides.
118pub fn log_claim_connect_failure(owner: &'static str, error: &ConsumerError) {
119    if let Some(claim) = connect_claim_error(error) {
120        log::info!(
121            "subc consumer claim failed: owner={owner} cause={}",
122            claim_cause(claim)
123        );
124    }
125}
126
127/// Live daemon consumer connections, counted per owner label.
128struct ConsumerGauge {
129    counts: std::sync::Mutex<std::collections::BTreeMap<&'static str, usize>>,
130    changed: AtomicBool,
131    reporter: std::sync::Once,
132}
133
134// Written out because `std::sync::Once` implements `Default` only in Rust
135// releases newer than this crate's minimum supported version.
136impl Default for ConsumerGauge {
137    fn default() -> Self {
138        Self {
139            counts: std::sync::Mutex::default(),
140            changed: AtomicBool::new(false),
141            reporter: std::sync::Once::new(),
142        }
143    }
144}
145
146static CONSUMER_GAUGE: OnceLock<ConsumerGauge> = OnceLock::new();
147
148/// How often the per-owner counts are logged, at most, when they changed.
149const CONSUMER_GAUGE_LOG_INTERVAL: Duration = Duration::from_secs(60);
150
151fn consumer_gauge() -> &'static ConsumerGauge {
152    CONSUMER_GAUGE.get_or_init(ConsumerGauge::default)
153}
154
155impl ConsumerGauge {
156    fn adjust(&self, owner: &'static str, opened: bool) {
157        let mut counts = self
158            .counts
159            .lock()
160            .unwrap_or_else(std::sync::PoisonError::into_inner);
161        let count = counts.entry(owner).or_default();
162        *count = if opened {
163            count.saturating_add(1)
164        } else {
165            count.saturating_sub(1)
166        };
167        self.changed.store(true, Ordering::Release);
168    }
169
170    fn render(&self) -> String {
171        let counts = self
172            .counts
173            .lock()
174            .unwrap_or_else(std::sync::PoisonError::into_inner);
175        let mut line = String::new();
176        for (owner, count) in counts.iter() {
177            if !line.is_empty() {
178                line.push(' ');
179            }
180            line.push_str(&format!("{owner}={count}"));
181        }
182        line
183    }
184
185    /// One process-wide thread logs the counts once a minute, only after a
186    /// change, so a growing owner shows in the log without a line per connect.
187    fn start_reporter(&'static self) {
188        self.reporter.call_once(|| {
189            let _ = std::thread::Builder::new()
190                .name("aft-subc-consumer-gauge".into())
191                .spawn(move || loop {
192                    std::thread::sleep(CONSUMER_GAUGE_LOG_INTERVAL);
193                    if self.changed.swap(false, Ordering::AcqRel) {
194                        log::info!("subc consumers live: {}", self.render());
195                    }
196                });
197        });
198    }
199}
200
201/// Counts one live item (a connection or a worker thread) for its label and
202/// uncounts it when dropped.
203pub struct LiveCount {
204    owner: &'static str,
205}
206
207impl Drop for LiveCount {
208    fn drop(&mut self) {
209        consumer_gauge().adjust(self.owner, false);
210    }
211}
212
213/// Count one live item under `label` in the per-owner gauge line until the
214/// returned guard drops. Used for daemon connections and for the remote-job
215/// worker threads that hold them.
216pub fn count_live(label: &'static str) -> LiveCount {
217    let gauge = consumer_gauge();
218    gauge.start_reporter();
219    gauge.adjust(label, true);
220    LiveCount { owner: label }
221}
222
223/// Count `consumer` as a live connection held by `owner` until the SDK
224/// releases it. The count lives in a connection-state callback, which the
225/// SDK drops together with the connection's shared state: after the last
226/// `SubcConsumer` handle, its subscriptions and its background tasks are gone.
227/// A consumer that is kept alive therefore stays counted.
228pub fn track_consumer(owner: &'static str, consumer: &SubcConsumer) {
229    let live = count_live(owner);
230    consumer.on_connection_state(move |_| {
231        let _ = &live;
232    });
233}
234
235/// The live consumer connections per owner label, for diagnostics and tests.
236#[cfg_attr(not(test), allow(dead_code))]
237pub fn live_consumers() -> std::collections::BTreeMap<&'static str, usize> {
238    consumer_gauge()
239        .counts
240        .lock()
241        .unwrap_or_else(std::sync::PoisonError::into_inner)
242        .clone()
243}
244
245/// The channel was adopted; consumers must wait until it can issue identity claims.
246pub fn channel_adopted() {
247    REGISTRATION.get_or_init(IdentityReady::default);
248}
249
250/// The daemon-backed minter can now issue identity claims to waiting consumers.
251pub fn minter_installed() {
252    REGISTRATION.get_or_init(IdentityReady::default).install();
253}