1use super::*;
6use consumer::{ConsumerError, ConsumerOptions, SubcConsumer};
7use std::sync::{OnceLock, Weak};
8use subc_os::registration_channel as os;
9use subc_protocol::claim::{
10 Claim, ClaimMintReply, ClaimMintRequest, ClaimPresentReply, ClaimPresentRequest, ClaimPurpose,
11 ClaimRateLimitedDetail,
12};
13
14static OWNER: OnceLock<RegistrationOwner> = OnceLock::new();
15static OWNER_READY: tokio::sync::Notify = tokio::sync::Notify::const_new();
16static HELPER_BOUND: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
17static SUPERVISED: OnceLock<bool> = OnceLock::new();
18static CHANNEL_TAKEN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
19static CHANNEL_ADOPTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
20
21#[async_trait]
40pub trait ClaimMinter: Send + Sync {
41 async fn mint(&self, request: ClaimMintRequest) -> Result<ClaimMintReply, ClaimError>;
42}
43
44#[derive(Debug)]
46#[non_exhaustive]
47pub enum RegistrationError {
48 Channel(os::RegistrationChannelError),
49 Transport(io::Error),
50 NotAdopted,
51 AlreadyInstalled,
52}
53
54impl fmt::Display for RegistrationError {
55 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56 match self {
57 Self::Channel(error) => error.fmt(f),
58 Self::Transport(_) => f.write_str("could not open registration transport"),
59 Self::NotAdopted => f.write_str("registration channel has not been adopted"),
60 Self::AlreadyInstalled => f.write_str("registration owner already installed"),
61 }
62 }
63}
64
65impl Error for RegistrationError {
66 fn source(&self) -> Option<&(dyn Error + 'static)> {
67 match self {
68 Self::Channel(error) => Some(error),
69 Self::Transport(error) => Some(error),
70 _ => None,
71 }
72 }
73}
74
75pub fn adopt_channel() -> Result<Option<Box<dyn ModuleStream>>, RegistrationError> {
88 init_supervised();
89 take_channel_stream()
90}
91
92pub fn install_claim_minter(minter: Arc<dyn ClaimMinter>) -> Result<(), RegistrationError> {
99 install_adopted_owner(RegistrationOwner::Custom(minter))
100}
101
102fn install_adopted_owner(owner: RegistrationOwner) -> Result<(), RegistrationError> {
103 if !CHANNEL_ADOPTED.load(Ordering::Acquire) {
104 return Err(RegistrationError::NotAdopted);
105 }
106 publish_owner(owner)
107}
108
109fn publish_owner(owner: RegistrationOwner) -> Result<(), RegistrationError> {
110 OWNER
111 .set(owner)
112 .map_err(|_| RegistrationError::AlreadyInstalled)?;
113 OWNER_READY.notify_waiters();
114 Ok(())
115}
116
117enum RegistrationOwner {
118 Custom(Arc<dyn ClaimMinter>),
119 Sdk(SdkClaimMinter),
120}
121
122impl RegistrationOwner {
123 fn sdk(handle: &ModuleHandle) -> Self {
124 Self::Sdk(SdkClaimMinter {
125 generations: Arc::downgrade(&handle.generations),
126 consumer_dial_stop: CancellationToken::new(),
127 })
128 }
129
130 fn minter(&self) -> &dyn ClaimMinter {
131 match self {
132 Self::Custom(minter) => minter.as_ref(),
133 Self::Sdk(minter) => minter,
134 }
135 }
136}
137
138struct SdkClaimMinter {
139 generations: Weak<live_upgrade::Generations>,
140 consumer_dial_stop: CancellationToken,
141}
142
143#[async_trait]
144impl ClaimMinter for SdkClaimMinter {
145 async fn mint(&self, request: ClaimMintRequest) -> Result<ClaimMintReply, ClaimError> {
146 ModuleHandle {
147 generations: self.generations.upgrade().ok_or(ClaimError::Unavailable)?,
148 }
149 .mint_claim_reply(request)
150 .await
151 }
152}
153
154fn sdk_owner() -> Option<&'static SdkClaimMinter> {
155 match OWNER.get()? {
156 RegistrationOwner::Sdk(owner) => Some(owner),
157 RegistrationOwner::Custom(_) => None,
158 }
159}
160
161pub(crate) fn check_consumer_dial() -> Result<(), ConsumerError> {
162 if sdk_owner().is_some_and(|owner| owner.consumer_dial_stop.is_cancelled()) {
163 return Err(ConsumerError::Closed);
164 }
165 Ok(())
166}
167
168pub(crate) async fn consumer_dial_stopped() {
169 if let Some(owner) = sdk_owner() {
170 owner.consumer_dial_stop.cancelled().await;
171 } else {
172 std::future::pending().await
173 }
174}
175
176#[derive(Default)]
177pub(crate) struct Session {
178 active: std::sync::atomic::AtomicBool,
179 pub(super) prefix_child: std::sync::atomic::AtomicBool,
180 pool: tokio::sync::Mutex<Vec<PoolEntry>>,
181}
182
183impl Session {
184 pub(super) fn is_active(&self) -> bool {
185 self.active.load(Ordering::Acquire)
186 }
187}
188
189struct PoolEntry {
190 path: PathBuf,
191 options: ConsumerOptions,
192 local: bool,
193 consumer: Weak<SubcConsumer>,
194}
195
196#[derive(Debug)]
201#[non_exhaustive]
202pub enum ClaimError {
203 Unavailable,
204 Timeout,
205 Protocol,
206 Refused {
207 code: String,
208 },
209 Handoff,
210 PrefixChildConsumer,
212}
213
214impl fmt::Display for ClaimError {
215 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
216 if matches!(self, Self::PrefixChildConsumer) {
217 f.write_str("prefix children have no consumer connections in this SDK yet")
218 } else {
219 f.write_str("claim authentication failed")
220 }
221 }
222}
223impl Error for ClaimError {}
224
225pub(crate) fn supervised() -> bool {
226 SUPERVISED.get().copied().unwrap_or(false)
227}
228
229pub(crate) fn adopt(module_id: &str) -> Result<bool, SubcModuleError> {
230 let supervised = init_supervised();
231 Ok(supervised && is_launched_module(module_id)?)
235}
236
237fn init_supervised() -> bool {
238 *SUPERVISED.get_or_init(|| {
239 let supervised = os::supervised();
240 if let Some(reason) = os::registration_refusal() {
241 tracing::warn!(%reason, "registration channel not adopted");
242 }
243 supervised
244 })
245}
246
247pub(crate) fn is_launched_module(module_id: &str) -> Result<bool, SubcModuleError> {
248 Ok(module_id_from_env()?.is_none_or(|launched_id| launched_id == module_id))
249}
250
251pub(crate) fn take_stream() -> Result<Option<Box<dyn ModuleStream>>, SubcModuleError> {
252 if !supervised() {
253 return Ok(None);
254 }
255 match take_channel_stream() {
256 Err(RegistrationError::Channel(os::RegistrationChannelError::AlreadyTaken)) => {
257 let error = match module_id_from_env()? {
258 Some(module_id) => io::Error::other(format!(
259 "launched module {module_id:?} is already serving on the registration channel"
260 )),
261 None => io::Error::other(os::RegistrationChannelError::AlreadyTaken),
262 };
263 Err(SubcModuleError::RegistrationChannel(error))
264 }
265 Err(RegistrationError::Transport(error)) => {
266 Err(SubcModuleError::RegistrationChannel(error))
267 }
268 result => {
269 result.map_err(|error| SubcModuleError::RegistrationChannel(io::Error::other(error)))
270 }
271 }
272}
273
274fn take_channel_stream() -> Result<Option<Box<dyn ModuleStream>>, RegistrationError> {
275 if CHANNEL_TAKEN.swap(true, Ordering::AcqRel) {
276 return Err(RegistrationError::Channel(
277 os::RegistrationChannelError::AlreadyTaken,
278 ));
279 }
280 let channel = os::take_registration_channel().map_err(RegistrationError::Channel)?;
281 let Some(channel) = channel else {
282 return Ok(None);
283 };
284 #[cfg(unix)]
285 let stream = {
286 let stream = channel.into_unix_stream();
287 stream
288 .set_nonblocking(true)
289 .map_err(RegistrationError::Transport)?;
290 tokio::net::UnixStream::from_std(stream).map_err(RegistrationError::Transport)?
291 };
292 #[cfg(windows)]
293 let stream = channel
294 .into_tokio_pipe_client()
295 .map_err(RegistrationError::Transport)?;
296 #[cfg(any(unix, windows))]
297 {
298 CHANNEL_ADOPTED.store(true, Ordering::Release);
299 Ok(Some(Box::new(stream)))
300 }
301 #[cfg(not(any(unix, windows)))]
302 {
303 let _ = channel;
304 Err(RegistrationError::Transport(io::Error::new(
305 io::ErrorKind::Unsupported,
306 "registration transport unsupported",
307 )))
308 }
309}
310
311pub(crate) fn install_owner(handle: &ModuleHandle) -> Result<(), SubcModuleError> {
312 handle
313 .shared()
314 .registration
315 .active
316 .store(true, Ordering::Release);
317 install_adopted_owner(RegistrationOwner::sdk(handle))
318 .map_err(|error| SubcModuleError::RegistrationChannel(io::Error::other(error)))
319}
320
321pub(super) fn rebind_owner(shared: &ModuleHandleShared) {
322 shared.registration.active.store(true, Ordering::Release);
323}
324
325pub(super) fn install_resumed_nonce_owner(handle: &ModuleHandle) -> Result<(), SubcModuleError> {
326 publish_owner(RegistrationOwner::sdk(handle))
330 .map_err(|error| SubcModuleError::RegistrationChannel(io::Error::other(error)))
331}
332
333pub(crate) async fn prefix_claim(module_id: &str) -> Result<Option<Claim>, ClaimError> {
334 let deadline = Instant::now() + CATALOG_UPDATE_TIMEOUT;
335 timeout_at(deadline, async {
336 let owner = loop {
337 let ready = OWNER_READY.notified();
340 tokio::pin!(ready);
341 ready.as_mut().enable();
342 if let Some(owner) = OWNER.get() {
343 break owner;
344 }
345 ready.await;
346 };
347 match mint_claim(
348 owner.minter(),
349 ClaimPurpose::Prefix {
350 module_id: module_id.to_owned(),
351 },
352 )
353 .await
354 {
355 Err(ClaimError::Refused { code }) if code == error_codes::CLAIM_PREFIX_REFUSED => {
356 Ok(None)
357 }
358 result => result.map(Some),
359 }
360 })
361 .await
362 .map_err(|_| ClaimError::Timeout)?
363}
364
365pub(crate) fn serve_claim_error(module_id: &str, error: ClaimError) -> SubcModuleError {
366 let code = match error {
367 ClaimError::Refused { code } => code,
368 ClaimError::Unavailable => "claim_unavailable".into(),
369 ClaimError::Timeout => "claim_timeout".into(),
370 _ => "claim_protocol".into(),
371 };
372 SubcModuleError::RegistrationChannel(io::Error::other(format!(
373 "prefix registration for module {module_id:?} failed: {code}"
374 )))
375}
376
377impl ModuleHandle {
378 pub(super) fn fence_consumer_dials(&self) {
379 if let Some(owner) = sdk_owner() {
380 if owner.generations.ptr_eq(&Arc::downgrade(&self.generations)) {
382 owner.consumer_dial_stop.cancel();
383 }
384 }
385 }
386
387 pub async fn consumer(
392 &self,
393 path: &Path,
394 options: ConsumerOptions,
395 ) -> Result<Arc<SubcConsumer>, ConsumerError> {
396 self.pooled_consumer(path, options, false).await
397 }
398
399 pub async fn consumer_local(
402 &self,
403 path: &Path,
404 options: ConsumerOptions,
405 ) -> Result<Arc<SubcConsumer>, ConsumerError> {
406 self.pooled_consumer(path, options, true).await
407 }
408
409 async fn pooled_consumer(
410 &self,
411 path: &Path,
412 options: ConsumerOptions,
413 local: bool,
414 ) -> Result<Arc<SubcConsumer>, ConsumerError> {
415 let shared = self.shared();
416 Self::check_claim_fence(&shared).map_err(ConsumerError::claim)?;
417 if shared.registration.prefix_child.load(Ordering::Acquire) {
418 return Err(ConsumerError::claim(ClaimError::PrefixChildConsumer));
419 }
420 if !shared.registration.active.load(Ordering::Acquire) || shared.close_token.is_cancelled()
421 {
422 return Err(ConsumerError::claim(ClaimError::Unavailable));
423 }
424 let mut pool = shared.registration.pool.lock().await;
425 pool.retain(|entry| {
426 entry
427 .consumer
428 .upgrade()
429 .is_some_and(|consumer| consumer.pool_reusable())
430 });
431 if let Some(consumer) = pool
432 .iter()
433 .find(|entry| entry.path == path && entry.local == local && entry.options == options)
434 .and_then(|entry| entry.consumer.upgrade())
435 .filter(|consumer| consumer.pool_reusable())
436 {
437 return Ok(consumer);
438 }
439 let consumer = Arc::new(if local {
440 SubcConsumer::connect_local(path, options.clone()).await?
441 } else {
442 SubcConsumer::connect(path, options.clone()).await?
443 });
444 pool.push(PoolEntry {
445 path: path.into(),
446 options,
447 local,
448 consumer: Arc::downgrade(&consumer),
449 });
450 Ok(consumer)
451 }
452
453 pub async fn helper_claim_handoff(&self) -> Result<os::HelperClaimHandoff, ClaimError> {
460 let claim = self.mint_claim(ClaimPurpose::Helper).await?;
461 os::HelperClaimHandoff::new(claim.expose_secret()).map_err(|_| ClaimError::Handoff)
462 }
463
464 async fn mint_claim(&self, purpose: ClaimPurpose) -> Result<Claim, ClaimError> {
465 self.mint_claim_reply(ClaimMintRequest::new(purpose))
466 .await
467 .map(|reply| reply.claim)
468 }
469
470 async fn mint_claim_reply(
471 &self,
472 request: ClaimMintRequest,
473 ) -> Result<ClaimMintReply, ClaimError> {
474 let shared = self.shared();
475 Self::check_claim_fence(&shared)?;
476 if !shared.registration.active.load(Ordering::Acquire) {
477 return Err(ClaimError::Unavailable);
478 }
479 let deadline = Instant::now() + CATALOG_UPDATE_TIMEOUT;
480 loop {
481 let reply = timeout_at(deadline, Self::claim_call(&shared, &request))
482 .await
483 .map_err(|_| ClaimError::Timeout)??;
484 if reply.header.ty == FrameType::Error {
485 let error: ErrorBody =
486 serde_json::from_slice(&reply.body).map_err(|_| ClaimError::Protocol)?;
487 if error.code == error_codes::CLAIM_RATE_LIMITED {
488 let detail: ClaimRateLimitedDetail =
489 serde_json::from_value(error.detail.ok_or(ClaimError::Protocol)?)
490 .map_err(|_| ClaimError::Protocol)?;
491 timeout_at(
494 deadline,
495 tokio::time::sleep(Duration::from_millis(detail.retry_after_ms)),
496 )
497 .await
498 .map_err(|_| ClaimError::Timeout)?;
499 continue;
500 }
501 return Err(ClaimError::Refused { code: error.code });
502 }
503 if reply.header.ty != FrameType::Response {
504 return Err(ClaimError::Protocol);
505 }
506 let reply: ClaimMintReply =
507 serde_json::from_slice(&reply.body).map_err(|_| ClaimError::Protocol)?;
508 return Ok(reply);
509 }
510 }
511
512 fn check_claim_fence(shared: &ModuleHandleShared) -> Result<(), ClaimError> {
513 shared.check_upgrade_fence().map_err(claim_send_error)
514 }
515
516 async fn claim_call(
517 shared: &Arc<ModuleHandleShared>,
518 request: &ClaimMintRequest,
519 ) -> Result<Frame, ClaimError> {
520 let body = serde_json::to_vec(request).map_err(|_| ClaimError::Protocol)?;
521 let (corr, writer, rx) = {
522 let mut inner = shared.lock_inner();
523 if inner.upgrade.fenced() {
524 return Err(claim_send_error(CatalogUpdateError::Rejected(
525 live_upgrade::upgrade_refusal(),
526 )));
527 }
528 let writer = inner.writer.clone().ok_or(ClaimError::Unavailable)?;
529 let corr = next_module_control_corr(&mut inner).ok_or(ClaimError::Unavailable)?;
530 let (tx, rx) = oneshot::channel();
531 inner.pending_claim_calls.insert(corr, tx);
532 (corr, writer, rx)
533 };
534 let _guard = ClaimWaiter {
535 shared: shared.clone(),
536 corr,
537 };
538 let frame = Frame::build_with_version(
539 shared.negotiated_ver,
540 FrameType::Request,
541 control_flags(),
542 0,
543 0,
544 corr,
545 body,
546 )
547 .map_err(|_| ClaimError::Protocol)?;
548 shared
549 .queue_request(&writer, frame)
550 .await
551 .map_err(claim_send_error)?;
552 rx.await.map_err(|_| ClaimError::Unavailable)
553 }
554}
555
556struct ClaimWaiter {
557 shared: Arc<ModuleHandleShared>,
558 corr: u64,
559}
560impl Drop for ClaimWaiter {
561 fn drop(&mut self) {
562 self.shared
563 .lock_inner()
564 .pending_claim_calls
565 .remove(&self.corr);
566 }
567}
568
569fn claim_send_error(error: CatalogUpdateError) -> ClaimError {
570 match error {
571 CatalogUpdateError::Rejected(body) => ClaimError::Refused { code: body.code },
572 _ => ClaimError::Unavailable,
573 }
574}
575
576pub(crate) fn bound() -> bool {
577 supervised() || OWNER.get().is_some() || HELPER_BOUND.load(Ordering::Acquire)
578}
579
580async fn mint_claim(minter: &dyn ClaimMinter, purpose: ClaimPurpose) -> Result<Claim, ClaimError> {
581 timeout(
582 CATALOG_UPDATE_TIMEOUT,
583 minter.mint(ClaimMintRequest::new(purpose)),
584 )
585 .await
586 .map_err(|_| ClaimError::Timeout)?
587 .map(|reply| reply.claim)
588}
589
590pub(crate) async fn bind_consumer<S: AsyncRead + AsyncWrite + Unpin>(
591 stream: &mut S,
592 deadline: Duration,
593) -> Result<(), ClaimError> {
594 let claim = if let Some(owner) = OWNER.get() {
595 Some(mint_claim(owner.minter(), ClaimPurpose::SelfConnection).await?)
596 } else if supervised() {
597 return Err(ClaimError::Unavailable);
598 } else {
599 os::helper_claim()
600 .map_err(|_| ClaimError::Handoff)?
601 .map(|claim| {
602 HELPER_BOUND.store(true, Ordering::Release);
603 Claim::new(claim.value())
604 })
605 };
606 let Some(claim) = claim else {
607 return Ok(());
608 };
609 present_claim(stream, claim, deadline).await
610}
611
612pub(crate) async fn present_claim<S: AsyncRead + AsyncWrite + Unpin>(
613 stream: &mut S,
614 claim: Claim,
615 deadline: Duration,
616) -> Result<(), ClaimError> {
617 let frame = Frame::build(
618 FrameType::Request,
619 control_flags(),
620 0,
621 0,
622 1,
623 serde_json::to_vec(&ClaimPresentRequest::new(claim)).map_err(|_| ClaimError::Protocol)?,
624 )
625 .map_err(|_| ClaimError::Protocol)?;
626 let reply = timeout(deadline, async {
627 write_frame(stream, &frame)
628 .await
629 .map_err(|_| ClaimError::Unavailable)?;
630 read_frame(stream)
631 .await
632 .map_err(|_| ClaimError::Unavailable)?
633 .ok_or(ClaimError::Unavailable)
634 })
635 .await
636 .map_err(|_| ClaimError::Timeout)??;
637 if reply.header.channel != 0 || reply.header.epoch != 0 || reply.header.corr != 1 {
638 return Err(ClaimError::Protocol);
639 }
640 if reply.header.ty == FrameType::Error {
641 let error: ErrorBody =
642 serde_json::from_slice(&reply.body).map_err(|_| ClaimError::Protocol)?;
643 return Err(ClaimError::Refused { code: error.code });
644 }
645 if reply.header.ty != FrameType::Response {
646 return Err(ClaimError::Protocol);
647 }
648 serde_json::from_slice::<ClaimPresentReply>(&reply.body).map_err(|_| ClaimError::Protocol)?;
649 Ok(())
650}
651
652#[cfg(all(test, any(unix, windows)))]
653#[path = "registration_tests.rs"]
654mod registration_contract;