Skip to main content

subc_client_rs/
registration.rs

1//! One process owner for registration and claim minting. No synchronous mutex is
2//! held over I/O. The async pool lock serializes consumer creation, not minting
3//! or the registration reader, so a HELLO/claim reply can always make progress.
4
5use 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<Arc<dyn ClaimMinter>> = 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/// A custom module loop's channel-0 `claim.mint` RPC implementation.
22///
23/// Startup order is: call [`adopt_channel`], authenticate the returned stream,
24/// send the launched module's HELLO without `launch_nonce`, validate HELLO_ACK,
25/// call [`install_claim_minter`], then open consumers. If adoption returns `None`,
26/// use the legacy connection and launch-nonce path instead; do not install a minter.
27///
28/// Implement with [`crate::async_trait`]. Send each request on the adopted module
29/// connection and correlate its reply while continuing to read that connection.
30/// Validate the reply's type and operation, map daemon refusals to
31/// [`ClaimError::Refused`], and honor `claim_rate_limited` retry delays within a
32/// bounded budget. Return [`ClaimError::Unavailable`] when the connection closes;
33/// never reconnect the registration channel or fall back to nonce authentication.
34/// The SDK bounds each mint and ignores the reply's informational wall-clock expiry.
35///
36/// A module using this path must not pass
37/// [`CallOptions::consumer_identity`](crate::consumer::CallOptions::consumer_identity):
38/// a claim-bound connection refuses that override before sending it.
39#[async_trait]
40pub trait ClaimMinter: Send + Sync {
41    async fn mint(&self, request: ClaimMintRequest) -> Result<ClaimMintReply, ClaimError>;
42}
43
44/// Failure to adopt or install the process's registration owner.
45#[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
75/// Take the daemon's private registration stream for a custom module loop.
76///
77/// Call once at startup, before spawning children. In a Tokio runtime:
78/// adopt, authenticate, send HELLO without `launch_nonce`, validate HELLO_ACK,
79/// install the owner with [`install_claim_minter`], then open consumers.
80/// See [`ClaimMinter`] for the loop's RPC and connection-lifetime obligations.
81/// A second call, even after `None`, returns
82/// [`RegistrationError::Channel`] containing
83/// [`os::RegistrationChannelError::AlreadyTaken`].
84///
85/// `None` means no validated channel was handed to this process (for example,
86/// an older daemon or a non-daemon launch); keep the legacy nonce path then.
87pub fn adopt_channel() -> Result<Option<Box<dyn ModuleStream>>, RegistrationError> {
88    init_supervised();
89    take_channel_stream()
90}
91
92/// Install a custom loop's claim minter after HELLO_ACK and before opening consumers.
93///
94/// Refuses installation before channel adoption or after any owner was installed,
95/// including an owner installed by [`crate::serve`]. The process retains the minter;
96/// it must report a closed registration connection as unavailable. Installation
97/// cannot be undone and must never authorize reconnecting the registration channel.
98pub fn install_claim_minter(minter: Arc<dyn ClaimMinter>) -> Result<(), RegistrationError> {
99    if !CHANNEL_ADOPTED.load(Ordering::Acquire) {
100        return Err(RegistrationError::NotAdopted);
101    }
102    publish_claim_minter(minter)
103}
104
105fn publish_claim_minter(minter: Arc<dyn ClaimMinter>) -> Result<(), RegistrationError> {
106    OWNER
107        .set(minter)
108        .map_err(|_| RegistrationError::AlreadyInstalled)?;
109    OWNER_READY.notify_waiters();
110    Ok(())
111}
112
113struct SdkClaimMinter(Weak<live_upgrade::Generations>);
114
115#[async_trait]
116impl ClaimMinter for SdkClaimMinter {
117    async fn mint(&self, request: ClaimMintRequest) -> Result<ClaimMintReply, ClaimError> {
118        ModuleHandle {
119            generations: self.0.upgrade().ok_or(ClaimError::Unavailable)?,
120        }
121        .mint_claim_reply(request)
122        .await
123    }
124}
125
126#[derive(Default)]
127pub(crate) struct Session {
128    active: std::sync::atomic::AtomicBool,
129    pub(super) prefix_child: std::sync::atomic::AtomicBool,
130    pool: tokio::sync::Mutex<Vec<PoolEntry>>,
131}
132
133impl Session {
134    pub(super) fn is_active(&self) -> bool {
135        self.active.load(Ordering::Acquire)
136    }
137}
138
139struct PoolEntry {
140    path: PathBuf,
141    options: ConsumerOptions,
142    local: bool,
143    consumer: Weak<SubcConsumer>,
144}
145
146/// Claim failures never permit continuing with an unbound connection. Debug and
147/// Display omit daemon-authored messages and bodies, which can contain secrets.
148/// During an announced daemon upgrade, a new mint is refused locally with
149/// `module_reloading` before sending to the daemon.
150#[derive(Debug)]
151#[non_exhaustive]
152pub enum ClaimError {
153    Unavailable,
154    Timeout,
155    Protocol,
156    Refused {
157        code: String,
158    },
159    Handoff,
160    /// Prefix children cannot open consumer connections in this SDK yet.
161    PrefixChildConsumer,
162}
163
164impl fmt::Display for ClaimError {
165    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166        if matches!(self, Self::PrefixChildConsumer) {
167            f.write_str("prefix children have no consumer connections in this SDK yet")
168        } else {
169            f.write_str("claim authentication failed")
170        }
171    }
172}
173impl Error for ClaimError {}
174
175pub(crate) fn supervised() -> bool {
176    SUPERVISED.get().copied().unwrap_or(false)
177}
178
179pub(crate) fn adopt(module_id: &str) -> Result<bool, SubcModuleError> {
180    let supervised = init_supervised();
181    // The inherited channel belongs to the launched module, not every module
182    // exported by its process. Sharing a process does not grant other module ids
183    // the launched module's authority; they need separate registration authority.
184    Ok(supervised && is_launched_module(module_id)?)
185}
186
187fn init_supervised() -> bool {
188    *SUPERVISED.get_or_init(|| {
189        let supervised = os::supervised();
190        if let Some(reason) = os::registration_refusal() {
191            tracing::warn!(%reason, "registration channel not adopted");
192        }
193        supervised
194    })
195}
196
197pub(crate) fn is_launched_module(module_id: &str) -> Result<bool, SubcModuleError> {
198    Ok(module_id_from_env()?.is_none_or(|launched_id| launched_id == module_id))
199}
200
201pub(crate) fn take_stream() -> Result<Option<Box<dyn ModuleStream>>, SubcModuleError> {
202    if !supervised() {
203        return Ok(None);
204    }
205    match take_channel_stream() {
206        Err(RegistrationError::Channel(os::RegistrationChannelError::AlreadyTaken)) => {
207            let error = match module_id_from_env()? {
208                Some(module_id) => io::Error::other(format!(
209                    "launched module {module_id:?} is already serving on the registration channel"
210                )),
211                None => io::Error::other(os::RegistrationChannelError::AlreadyTaken),
212            };
213            Err(SubcModuleError::RegistrationChannel(error))
214        }
215        Err(RegistrationError::Transport(error)) => {
216            Err(SubcModuleError::RegistrationChannel(error))
217        }
218        result => {
219            result.map_err(|error| SubcModuleError::RegistrationChannel(io::Error::other(error)))
220        }
221    }
222}
223
224fn take_channel_stream() -> Result<Option<Box<dyn ModuleStream>>, RegistrationError> {
225    if CHANNEL_TAKEN.swap(true, Ordering::AcqRel) {
226        return Err(RegistrationError::Channel(
227            os::RegistrationChannelError::AlreadyTaken,
228        ));
229    }
230    let channel = os::take_registration_channel().map_err(RegistrationError::Channel)?;
231    let Some(channel) = channel else {
232        return Ok(None);
233    };
234    #[cfg(unix)]
235    let stream = {
236        let stream = channel.into_unix_stream();
237        stream
238            .set_nonblocking(true)
239            .map_err(RegistrationError::Transport)?;
240        tokio::net::UnixStream::from_std(stream).map_err(RegistrationError::Transport)?
241    };
242    #[cfg(windows)]
243    let stream = channel
244        .into_tokio_pipe_client()
245        .map_err(RegistrationError::Transport)?;
246    #[cfg(any(unix, windows))]
247    {
248        CHANNEL_ADOPTED.store(true, Ordering::Release);
249        Ok(Some(Box::new(stream)))
250    }
251    #[cfg(not(any(unix, windows)))]
252    {
253        let _ = channel;
254        Err(RegistrationError::Transport(io::Error::new(
255            io::ErrorKind::Unsupported,
256            "registration transport unsupported",
257        )))
258    }
259}
260
261pub(crate) fn install_owner(handle: &ModuleHandle) -> Result<(), SubcModuleError> {
262    handle
263        .shared()
264        .registration
265        .active
266        .store(true, Ordering::Release);
267    install_claim_minter(Arc::new(SdkClaimMinter(Arc::downgrade(
268        &handle.generations,
269    ))))
270    .map_err(|error| SubcModuleError::RegistrationChannel(io::Error::other(error)))
271}
272
273pub(super) fn rebind_owner(shared: &ModuleHandleShared) {
274    shared.registration.active.store(true, Ordering::Release);
275}
276
277pub(super) fn install_resumed_nonce_owner(handle: &ModuleHandle) -> Result<(), SubcModuleError> {
278    // A nonce launch does not have a claim minter until the daemon accepts its
279    // first resume. From then on the minter follows the stable handle just as
280    // an inherited channel's minter does.
281    publish_claim_minter(Arc::new(SdkClaimMinter(Arc::downgrade(
282        &handle.generations,
283    ))))
284    .map_err(|error| SubcModuleError::RegistrationChannel(io::Error::other(error)))
285}
286
287pub(crate) async fn prefix_claim(module_id: &str) -> Result<Option<Claim>, ClaimError> {
288    let deadline = Instant::now() + CATALOG_UPDATE_TIMEOUT;
289    timeout_at(deadline, async {
290        let owner = loop {
291            // Register the waiter before checking OWNER so installation cannot
292            // race the transition to sleep.
293            let ready = OWNER_READY.notified();
294            tokio::pin!(ready);
295            ready.as_mut().enable();
296            if let Some(owner) = OWNER.get() {
297                break owner;
298            }
299            ready.await;
300        };
301        match mint_claim(
302            owner.as_ref(),
303            ClaimPurpose::Prefix {
304                module_id: module_id.to_owned(),
305            },
306        )
307        .await
308        {
309            Err(ClaimError::Refused { code }) if code == error_codes::CLAIM_PREFIX_REFUSED => {
310                Ok(None)
311            }
312            result => result.map(Some),
313        }
314    })
315    .await
316    .map_err(|_| ClaimError::Timeout)?
317}
318
319pub(crate) fn serve_claim_error(module_id: &str, error: ClaimError) -> SubcModuleError {
320    let code = match error {
321        ClaimError::Refused { code } => code,
322        ClaimError::Unavailable => "claim_unavailable".into(),
323        ClaimError::Timeout => "claim_timeout".into(),
324        _ => "claim_protocol".into(),
325    };
326    SubcModuleError::RegistrationChannel(io::Error::other(format!(
327        "prefix registration for module {module_id:?} failed: {code}"
328    )))
329}
330
331impl ModuleHandle {
332    /// Open or reuse a self-bound TCP consumer. The pool belongs to this spawn's
333    /// registration binding; keys compare the exact path and every option. It
334    /// holds only weak references: dropping the last Arc closes the connection.
335    /// Await or spawn the serve future before calling this method.
336    pub async fn consumer(
337        &self,
338        path: &Path,
339        options: ConsumerOptions,
340    ) -> Result<Arc<SubcConsumer>, ConsumerError> {
341        self.pooled_consumer(path, options, false).await
342    }
343
344    /// Like [`Self::consumer`], but local-only. Local and TCP connections never
345    /// share a pool entry, even when their connection file and options match.
346    pub async fn consumer_local(
347        &self,
348        path: &Path,
349        options: ConsumerOptions,
350    ) -> Result<Arc<SubcConsumer>, ConsumerError> {
351        self.pooled_consumer(path, options, true).await
352    }
353
354    async fn pooled_consumer(
355        &self,
356        path: &Path,
357        options: ConsumerOptions,
358        local: bool,
359    ) -> Result<Arc<SubcConsumer>, ConsumerError> {
360        let shared = self.shared();
361        Self::check_claim_fence(&shared).map_err(ConsumerError::claim)?;
362        if shared.registration.prefix_child.load(Ordering::Acquire) {
363            return Err(ConsumerError::claim(ClaimError::PrefixChildConsumer));
364        }
365        if !shared.registration.active.load(Ordering::Acquire) || shared.close_token.is_cancelled()
366        {
367            return Err(ConsumerError::claim(ClaimError::Unavailable));
368        }
369        let mut pool = shared.registration.pool.lock().await;
370        pool.retain(|entry| {
371            entry
372                .consumer
373                .upgrade()
374                .is_some_and(|consumer| consumer.pool_reusable())
375        });
376        if let Some(consumer) = pool
377            .iter()
378            .find(|entry| entry.path == path && entry.local == local && entry.options == options)
379            .and_then(|entry| entry.consumer.upgrade())
380            .filter(|consumer| consumer.pool_reusable())
381        {
382            return Ok(consumer);
383        }
384        let consumer = Arc::new(if local {
385            SubcConsumer::connect_local(path, options.clone()).await?
386        } else {
387            SubcConsumer::connect(path, options.clone()).await?
388        });
389        pool.push(PoolEntry {
390            path: path.into(),
391            options,
392            local,
393            consumer: Arc::downgrade(&consumer),
394        });
395        Ok(consumer)
396    }
397
398    /// Pass a helper-purpose claim through subc-os's one-read pipe. The helper
399    /// acts for the module, but its calls are attested as delegated, not its own.
400    /// No self claim or launch nonce is ever put into the child's environment or
401    /// argv. On Unix, install this handoff last on the helper's Command. On
402    /// Windows, configure the Command before spawning, then serve the handoff
403    /// with the live child's PID on a blocking thread, retaining the child.
404    pub async fn helper_claim_handoff(&self) -> Result<os::HelperClaimHandoff, ClaimError> {
405        let claim = self.mint_claim(ClaimPurpose::Helper).await?;
406        os::HelperClaimHandoff::new(claim.expose_secret()).map_err(|_| ClaimError::Handoff)
407    }
408
409    async fn mint_claim(&self, purpose: ClaimPurpose) -> Result<Claim, ClaimError> {
410        self.mint_claim_reply(ClaimMintRequest::new(purpose))
411            .await
412            .map(|reply| reply.claim)
413    }
414
415    async fn mint_claim_reply(
416        &self,
417        request: ClaimMintRequest,
418    ) -> Result<ClaimMintReply, ClaimError> {
419        let shared = self.shared();
420        Self::check_claim_fence(&shared)?;
421        if !shared.registration.active.load(Ordering::Acquire) {
422            return Err(ClaimError::Unavailable);
423        }
424        let deadline = Instant::now() + CATALOG_UPDATE_TIMEOUT;
425        loop {
426            let reply = timeout_at(deadline, Self::claim_call(&shared, &request))
427                .await
428                .map_err(|_| ClaimError::Timeout)??;
429            if reply.header.ty == FrameType::Error {
430                let error: ErrorBody =
431                    serde_json::from_slice(&reply.body).map_err(|_| ClaimError::Protocol)?;
432                if error.code == error_codes::CLAIM_RATE_LIMITED {
433                    let detail: ClaimRateLimitedDetail =
434                        serde_json::from_value(error.detail.ok_or(ClaimError::Protocol)?)
435                            .map_err(|_| ClaimError::Protocol)?;
436                    // Use the daemon's delay, never its informational wall-clock
437                    // claim expiry. A bounded call must not retry past its budget.
438                    timeout_at(
439                        deadline,
440                        tokio::time::sleep(Duration::from_millis(detail.retry_after_ms)),
441                    )
442                    .await
443                    .map_err(|_| ClaimError::Timeout)?;
444                    continue;
445                }
446                return Err(ClaimError::Refused { code: error.code });
447            }
448            if reply.header.ty != FrameType::Response {
449                return Err(ClaimError::Protocol);
450            }
451            let reply: ClaimMintReply =
452                serde_json::from_slice(&reply.body).map_err(|_| ClaimError::Protocol)?;
453            return Ok(reply);
454        }
455    }
456
457    fn check_claim_fence(shared: &ModuleHandleShared) -> Result<(), ClaimError> {
458        shared.check_upgrade_fence().map_err(claim_send_error)
459    }
460
461    async fn claim_call(
462        shared: &Arc<ModuleHandleShared>,
463        request: &ClaimMintRequest,
464    ) -> Result<Frame, ClaimError> {
465        let body = serde_json::to_vec(request).map_err(|_| ClaimError::Protocol)?;
466        let (corr, writer, rx) = {
467            let mut inner = shared.lock_inner();
468            if inner.upgrade.fenced() {
469                return Err(claim_send_error(CatalogUpdateError::Rejected(
470                    live_upgrade::upgrade_refusal(),
471                )));
472            }
473            let writer = inner.writer.clone().ok_or(ClaimError::Unavailable)?;
474            let corr = next_module_control_corr(&mut inner).ok_or(ClaimError::Unavailable)?;
475            let (tx, rx) = oneshot::channel();
476            inner.pending_claim_calls.insert(corr, tx);
477            (corr, writer, rx)
478        };
479        let _guard = ClaimWaiter {
480            shared: shared.clone(),
481            corr,
482        };
483        let frame = Frame::build_with_version(
484            shared.negotiated_ver,
485            FrameType::Request,
486            control_flags(),
487            0,
488            0,
489            corr,
490            body,
491        )
492        .map_err(|_| ClaimError::Protocol)?;
493        shared
494            .queue_request(&writer, frame)
495            .await
496            .map_err(claim_send_error)?;
497        rx.await.map_err(|_| ClaimError::Unavailable)
498    }
499}
500
501struct ClaimWaiter {
502    shared: Arc<ModuleHandleShared>,
503    corr: u64,
504}
505impl Drop for ClaimWaiter {
506    fn drop(&mut self) {
507        self.shared
508            .lock_inner()
509            .pending_claim_calls
510            .remove(&self.corr);
511    }
512}
513
514fn claim_send_error(error: CatalogUpdateError) -> ClaimError {
515    match error {
516        CatalogUpdateError::Rejected(body) => ClaimError::Refused { code: body.code },
517        _ => ClaimError::Unavailable,
518    }
519}
520
521pub(crate) fn bound() -> bool {
522    supervised() || OWNER.get().is_some() || HELPER_BOUND.load(Ordering::Acquire)
523}
524
525async fn mint_claim(minter: &dyn ClaimMinter, purpose: ClaimPurpose) -> Result<Claim, ClaimError> {
526    timeout(
527        CATALOG_UPDATE_TIMEOUT,
528        minter.mint(ClaimMintRequest::new(purpose)),
529    )
530    .await
531    .map_err(|_| ClaimError::Timeout)?
532    .map(|reply| reply.claim)
533}
534
535pub(crate) async fn bind_consumer<S: AsyncRead + AsyncWrite + Unpin>(
536    stream: &mut S,
537    deadline: Duration,
538) -> Result<(), ClaimError> {
539    let claim = if let Some(owner) = OWNER.get() {
540        Some(mint_claim(owner.as_ref(), ClaimPurpose::SelfConnection).await?)
541    } else if supervised() {
542        return Err(ClaimError::Unavailable);
543    } else {
544        os::helper_claim()
545            .map_err(|_| ClaimError::Handoff)?
546            .map(|claim| {
547                HELPER_BOUND.store(true, Ordering::Release);
548                Claim::new(claim.value())
549            })
550    };
551    let Some(claim) = claim else {
552        return Ok(());
553    };
554    present_claim(stream, claim, deadline).await
555}
556
557pub(crate) async fn present_claim<S: AsyncRead + AsyncWrite + Unpin>(
558    stream: &mut S,
559    claim: Claim,
560    deadline: Duration,
561) -> Result<(), ClaimError> {
562    let frame = Frame::build(
563        FrameType::Request,
564        control_flags(),
565        0,
566        0,
567        1,
568        serde_json::to_vec(&ClaimPresentRequest::new(claim)).map_err(|_| ClaimError::Protocol)?,
569    )
570    .map_err(|_| ClaimError::Protocol)?;
571    let reply = timeout(deadline, async {
572        write_frame(stream, &frame)
573            .await
574            .map_err(|_| ClaimError::Unavailable)?;
575        read_frame(stream)
576            .await
577            .map_err(|_| ClaimError::Unavailable)?
578            .ok_or(ClaimError::Unavailable)
579    })
580    .await
581    .map_err(|_| ClaimError::Timeout)??;
582    if reply.header.channel != 0 || reply.header.epoch != 0 || reply.header.corr != 1 {
583        return Err(ClaimError::Protocol);
584    }
585    if reply.header.ty == FrameType::Error {
586        let error: ErrorBody =
587            serde_json::from_slice(&reply.body).map_err(|_| ClaimError::Protocol)?;
588        return Err(ClaimError::Refused { code: error.code });
589    }
590    if reply.header.ty != FrameType::Response {
591        return Err(ClaimError::Protocol);
592    }
593    serde_json::from_slice::<ClaimPresentReply>(&reply.body).map_err(|_| ClaimError::Protocol)?;
594    Ok(())
595}
596
597#[cfg(all(test, any(unix, windows)))]
598#[path = "registration_tests.rs"]
599mod registration_contract;