1use 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 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
57pub fn module_consumer_allowed() -> bool {
60 module_id().is_some() && (REGISTRATION.get().is_some() || identity_ready())
61}
62
63pub 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
92fn 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
102pub 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
116pub 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
127struct ConsumerGauge {
129 counts: std::sync::Mutex<std::collections::BTreeMap<&'static str, usize>>,
130 changed: AtomicBool,
131 reporter: std::sync::Once,
132}
133
134impl 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
148const 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 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
201pub 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
213pub 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
223pub 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#[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
245pub fn channel_adopted() {
247 REGISTRATION.get_or_init(IdentityReady::default);
248}
249
250pub fn minter_installed() {
252 REGISTRATION.get_or_init(IdentityReady::default).install();
253}