subc-client-rs 0.41.0

Shared serve + consume client for Rust subc modules.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
//! One process owner for registration and claim minting. No synchronous mutex is
//! held over I/O. The async pool lock serializes consumer creation, not minting
//! or the registration reader, so a HELLO/claim reply can always make progress.

use super::*;
use consumer::{ConsumerError, ConsumerOptions, SubcConsumer};
use std::sync::{OnceLock, Weak};
use subc_os::registration_channel as os;
use subc_protocol::claim::{
    Claim, ClaimMintReply, ClaimMintRequest, ClaimPresentReply, ClaimPresentRequest, ClaimPurpose,
    ClaimRateLimitedDetail,
};

static OWNER: OnceLock<Arc<dyn ClaimMinter>> = OnceLock::new();
static OWNER_READY: tokio::sync::Notify = tokio::sync::Notify::const_new();
static HELPER_BOUND: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
static SUPERVISED: OnceLock<bool> = OnceLock::new();
static CHANNEL_TAKEN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
static CHANNEL_ADOPTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

/// A custom module loop's channel-0 `claim.mint` RPC implementation.
///
/// Startup order is: call [`adopt_channel`], authenticate the returned stream,
/// send the launched module's HELLO without `launch_nonce`, validate HELLO_ACK,
/// call [`install_claim_minter`], then open consumers. If adoption returns `None`,
/// use the legacy connection and launch-nonce path instead; do not install a minter.
///
/// Implement with [`crate::async_trait`]. Send each request on the adopted module
/// connection and correlate its reply while continuing to read that connection.
/// Validate the reply's type and operation, map daemon refusals to
/// [`ClaimError::Refused`], and honor `claim_rate_limited` retry delays within a
/// bounded budget. Return [`ClaimError::Unavailable`] when the connection closes;
/// never reconnect the registration channel or fall back to nonce authentication.
/// The SDK bounds each mint and ignores the reply's informational wall-clock expiry.
///
/// A module using this path must not pass
/// [`CallOptions::consumer_identity`](crate::consumer::CallOptions::consumer_identity):
/// a claim-bound connection refuses that override before sending it.
#[async_trait]
pub trait ClaimMinter: Send + Sync {
    async fn mint(&self, request: ClaimMintRequest) -> Result<ClaimMintReply, ClaimError>;
}

/// Failure to adopt or install the process's registration owner.
#[derive(Debug)]
#[non_exhaustive]
pub enum RegistrationError {
    Channel(os::RegistrationChannelError),
    Transport(io::Error),
    NotAdopted,
    AlreadyInstalled,
}

impl fmt::Display for RegistrationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Channel(error) => error.fmt(f),
            Self::Transport(_) => f.write_str("could not open registration transport"),
            Self::NotAdopted => f.write_str("registration channel has not been adopted"),
            Self::AlreadyInstalled => f.write_str("registration owner already installed"),
        }
    }
}

impl Error for RegistrationError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Channel(error) => Some(error),
            Self::Transport(error) => Some(error),
            _ => None,
        }
    }
}

/// Take the daemon's private registration stream for a custom module loop.
///
/// Call once at startup, before spawning children. In a Tokio runtime:
/// adopt, authenticate, send HELLO without `launch_nonce`, validate HELLO_ACK,
/// install the owner with [`install_claim_minter`], then open consumers.
/// See [`ClaimMinter`] for the loop's RPC and connection-lifetime obligations.
/// A second call, even after `None`, returns
/// [`RegistrationError::Channel`] containing
/// [`os::RegistrationChannelError::AlreadyTaken`].
///
/// `None` means no validated channel was handed to this process (for example,
/// an older daemon or a non-daemon launch); keep the legacy nonce path then.
pub fn adopt_channel() -> Result<Option<Box<dyn ModuleStream>>, RegistrationError> {
    init_supervised();
    take_channel_stream()
}

/// Install a custom loop's claim minter after HELLO_ACK and before opening consumers.
///
/// Refuses installation before channel adoption or after any owner was installed,
/// including an owner installed by [`crate::serve`]. The process retains the minter;
/// it must report a closed registration connection as unavailable. Installation
/// cannot be undone and must never authorize reconnecting the registration channel.
pub fn install_claim_minter(minter: Arc<dyn ClaimMinter>) -> Result<(), RegistrationError> {
    if !CHANNEL_ADOPTED.load(Ordering::Acquire) {
        return Err(RegistrationError::NotAdopted);
    }
    OWNER
        .set(minter)
        .map_err(|_| RegistrationError::AlreadyInstalled)?;
    OWNER_READY.notify_waiters();
    Ok(())
}

struct SdkClaimMinter(Weak<ModuleHandleShared>);

#[async_trait]
impl ClaimMinter for SdkClaimMinter {
    async fn mint(&self, request: ClaimMintRequest) -> Result<ClaimMintReply, ClaimError> {
        ModuleHandle {
            shared: self.0.upgrade().ok_or(ClaimError::Unavailable)?,
        }
        .mint_claim_reply(request)
        .await
    }
}

#[derive(Default)]
pub(crate) struct Session {
    active: std::sync::atomic::AtomicBool,
    pub(super) prefix_child: std::sync::atomic::AtomicBool,
    pool: tokio::sync::Mutex<Vec<PoolEntry>>,
}

struct PoolEntry {
    path: PathBuf,
    options: ConsumerOptions,
    local: bool,
    consumer: Weak<SubcConsumer>,
}

/// Claim failures never permit continuing with an unbound connection. Debug and
/// Display omit daemon-authored messages and bodies, which can contain secrets.
#[derive(Debug)]
#[non_exhaustive]
pub enum ClaimError {
    Unavailable,
    Timeout,
    Protocol,
    Refused {
        code: String,
    },
    Handoff,
    /// Prefix children cannot open consumer connections in this SDK yet.
    PrefixChildConsumer,
}

impl fmt::Display for ClaimError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if matches!(self, Self::PrefixChildConsumer) {
            f.write_str("prefix children have no consumer connections in this SDK yet")
        } else {
            f.write_str("claim authentication failed")
        }
    }
}
impl Error for ClaimError {}

pub(crate) fn supervised() -> bool {
    SUPERVISED.get().copied().unwrap_or(false)
}

pub(crate) fn adopt(module_id: &str) -> Result<bool, SubcModuleError> {
    let supervised = init_supervised();
    // The inherited channel belongs to the launched module, not every module
    // exported by its process. Sharing a process does not grant other module ids
    // the launched module's authority; they need separate registration authority.
    Ok(supervised && is_launched_module(module_id)?)
}

fn init_supervised() -> bool {
    *SUPERVISED.get_or_init(|| {
        let supervised = os::supervised();
        if let Some(reason) = os::registration_refusal() {
            tracing::warn!(%reason, "registration channel not adopted");
        }
        supervised
    })
}

pub(crate) fn is_launched_module(module_id: &str) -> Result<bool, SubcModuleError> {
    Ok(module_id_from_env()?.is_none_or(|launched_id| launched_id == module_id))
}

pub(crate) fn take_stream() -> Result<Option<Box<dyn ModuleStream>>, SubcModuleError> {
    if !supervised() {
        return Ok(None);
    }
    match take_channel_stream() {
        Err(RegistrationError::Channel(os::RegistrationChannelError::AlreadyTaken)) => {
            let error = match module_id_from_env()? {
                Some(module_id) => io::Error::other(format!(
                    "launched module {module_id:?} is already serving on the registration channel"
                )),
                None => io::Error::other(os::RegistrationChannelError::AlreadyTaken),
            };
            Err(SubcModuleError::RegistrationChannel(error))
        }
        Err(RegistrationError::Transport(error)) => {
            Err(SubcModuleError::RegistrationChannel(error))
        }
        result => {
            result.map_err(|error| SubcModuleError::RegistrationChannel(io::Error::other(error)))
        }
    }
}

fn take_channel_stream() -> Result<Option<Box<dyn ModuleStream>>, RegistrationError> {
    if CHANNEL_TAKEN.swap(true, Ordering::AcqRel) {
        return Err(RegistrationError::Channel(
            os::RegistrationChannelError::AlreadyTaken,
        ));
    }
    let channel = os::take_registration_channel().map_err(RegistrationError::Channel)?;
    let Some(channel) = channel else {
        return Ok(None);
    };
    #[cfg(unix)]
    let stream = {
        let stream = channel.into_unix_stream();
        stream
            .set_nonblocking(true)
            .map_err(RegistrationError::Transport)?;
        tokio::net::UnixStream::from_std(stream).map_err(RegistrationError::Transport)?
    };
    #[cfg(windows)]
    let stream = channel
        .into_tokio_pipe_client()
        .map_err(RegistrationError::Transport)?;
    #[cfg(any(unix, windows))]
    {
        CHANNEL_ADOPTED.store(true, Ordering::Release);
        Ok(Some(Box::new(stream)))
    }
    #[cfg(not(any(unix, windows)))]
    {
        let _ = channel;
        Err(RegistrationError::Transport(io::Error::new(
            io::ErrorKind::Unsupported,
            "registration transport unsupported",
        )))
    }
}

pub(crate) fn install_owner(handle: &ModuleHandle) -> Result<(), SubcModuleError> {
    handle
        .shared
        .registration
        .active
        .store(true, Ordering::Release);
    install_claim_minter(Arc::new(SdkClaimMinter(Arc::downgrade(&handle.shared))))
        .map_err(|error| SubcModuleError::RegistrationChannel(io::Error::other(error)))
}

pub(crate) async fn prefix_claim(module_id: &str) -> Result<Option<Claim>, ClaimError> {
    let deadline = Instant::now() + CATALOG_UPDATE_TIMEOUT;
    timeout_at(deadline, async {
        let owner = loop {
            // Register the waiter before checking OWNER so installation cannot
            // race the transition to sleep.
            let ready = OWNER_READY.notified();
            tokio::pin!(ready);
            ready.as_mut().enable();
            if let Some(owner) = OWNER.get() {
                break owner;
            }
            ready.await;
        };
        match mint_claim(
            owner.as_ref(),
            ClaimPurpose::Prefix {
                module_id: module_id.to_owned(),
            },
        )
        .await
        {
            Err(ClaimError::Refused { code }) if code == error_codes::CLAIM_PREFIX_REFUSED => {
                Ok(None)
            }
            result => result.map(Some),
        }
    })
    .await
    .map_err(|_| ClaimError::Timeout)?
}

pub(crate) fn serve_claim_error(module_id: &str, error: ClaimError) -> SubcModuleError {
    let code = match error {
        ClaimError::Refused { code } => code,
        ClaimError::Unavailable => "claim_unavailable".into(),
        ClaimError::Timeout => "claim_timeout".into(),
        _ => "claim_protocol".into(),
    };
    SubcModuleError::RegistrationChannel(io::Error::other(format!(
        "prefix registration for module {module_id:?} failed: {code}"
    )))
}

impl ModuleHandle {
    /// Open or reuse a self-bound TCP consumer. The pool belongs to this spawn's
    /// registration binding; keys compare the exact path and every option. It
    /// holds only weak references: dropping the last Arc closes the connection.
    /// Await or spawn the serve future before calling this method.
    pub async fn consumer(
        &self,
        path: &Path,
        options: ConsumerOptions,
    ) -> Result<Arc<SubcConsumer>, ConsumerError> {
        self.pooled_consumer(path, options, false).await
    }

    /// Like [`Self::consumer`], but local-only. Local and TCP connections never
    /// share a pool entry, even when their connection file and options match.
    pub async fn consumer_local(
        &self,
        path: &Path,
        options: ConsumerOptions,
    ) -> Result<Arc<SubcConsumer>, ConsumerError> {
        self.pooled_consumer(path, options, true).await
    }

    async fn pooled_consumer(
        &self,
        path: &Path,
        options: ConsumerOptions,
        local: bool,
    ) -> Result<Arc<SubcConsumer>, ConsumerError> {
        if self
            .shared
            .registration
            .prefix_child
            .load(Ordering::Acquire)
        {
            return Err(ConsumerError::claim(ClaimError::PrefixChildConsumer));
        }
        if !self.shared.registration.active.load(Ordering::Acquire)
            || self.shared.close_token.is_cancelled()
        {
            return Err(ConsumerError::claim(ClaimError::Unavailable));
        }
        let mut pool = self.shared.registration.pool.lock().await;
        pool.retain(|entry| {
            entry
                .consumer
                .upgrade()
                .is_some_and(|consumer| consumer.pool_reusable())
        });
        if let Some(consumer) = pool
            .iter()
            .find(|entry| entry.path == path && entry.local == local && entry.options == options)
            .and_then(|entry| entry.consumer.upgrade())
            .filter(|consumer| consumer.pool_reusable())
        {
            return Ok(consumer);
        }
        let consumer = Arc::new(if local {
            SubcConsumer::connect_local(path, options.clone()).await?
        } else {
            SubcConsumer::connect(path, options.clone()).await?
        });
        pool.push(PoolEntry {
            path: path.into(),
            options,
            local,
            consumer: Arc::downgrade(&consumer),
        });
        Ok(consumer)
    }

    /// Pass a helper-purpose claim through subc-os's one-read pipe. The helper
    /// acts for the module, but its calls are attested as delegated, not its own.
    /// No self claim or launch nonce is ever put into the child's environment or
    /// argv. On Unix, install this handoff last on the helper's Command. On
    /// Windows, configure the Command before spawning, then serve the handoff
    /// with the live child's PID on a blocking thread, retaining the child.
    pub async fn helper_claim_handoff(&self) -> Result<os::HelperClaimHandoff, ClaimError> {
        let claim = self.mint_claim(ClaimPurpose::Helper).await?;
        os::HelperClaimHandoff::new(claim.expose_secret()).map_err(|_| ClaimError::Handoff)
    }

    async fn mint_claim(&self, purpose: ClaimPurpose) -> Result<Claim, ClaimError> {
        self.mint_claim_reply(ClaimMintRequest::new(purpose))
            .await
            .map(|reply| reply.claim)
    }

    async fn mint_claim_reply(
        &self,
        request: ClaimMintRequest,
    ) -> Result<ClaimMintReply, ClaimError> {
        if !self.shared.registration.active.load(Ordering::Acquire) {
            return Err(ClaimError::Unavailable);
        }
        let deadline = Instant::now() + CATALOG_UPDATE_TIMEOUT;
        loop {
            let reply = timeout_at(deadline, self.claim_call(&request))
                .await
                .map_err(|_| ClaimError::Timeout)??;
            if reply.header.ty == FrameType::Error {
                let error: ErrorBody =
                    serde_json::from_slice(&reply.body).map_err(|_| ClaimError::Protocol)?;
                if error.code == error_codes::CLAIM_RATE_LIMITED {
                    let detail: ClaimRateLimitedDetail =
                        serde_json::from_value(error.detail.ok_or(ClaimError::Protocol)?)
                            .map_err(|_| ClaimError::Protocol)?;
                    // Use the daemon's delay, never its informational wall-clock
                    // claim expiry. A bounded call must not retry past its budget.
                    timeout_at(
                        deadline,
                        tokio::time::sleep(Duration::from_millis(detail.retry_after_ms)),
                    )
                    .await
                    .map_err(|_| ClaimError::Timeout)?;
                    continue;
                }
                return Err(ClaimError::Refused { code: error.code });
            }
            if reply.header.ty != FrameType::Response {
                return Err(ClaimError::Protocol);
            }
            let reply: ClaimMintReply =
                serde_json::from_slice(&reply.body).map_err(|_| ClaimError::Protocol)?;
            return Ok(reply);
        }
    }

    async fn claim_call(&self, request: &ClaimMintRequest) -> Result<Frame, ClaimError> {
        let body = serde_json::to_vec(request).map_err(|_| ClaimError::Protocol)?;
        let (corr, writer, rx) = {
            let mut inner = self.shared.lock_inner();
            let writer = inner.writer.clone().ok_or(ClaimError::Unavailable)?;
            let corr = next_module_control_corr(&mut inner).ok_or(ClaimError::Unavailable)?;
            let (tx, rx) = oneshot::channel();
            inner.pending_claim_calls.insert(corr, tx);
            (corr, writer, rx)
        };
        let _guard = ClaimWaiter {
            handle: self.clone(),
            corr,
        };
        let frame = Frame::build_with_version(
            self.shared.negotiated_ver,
            FrameType::Request,
            control_flags(),
            0,
            0,
            corr,
            body,
        )
        .map_err(|_| ClaimError::Protocol)?;
        writer
            .send(frame)
            .await
            .map_err(|_| ClaimError::Unavailable)?;
        rx.await.map_err(|_| ClaimError::Unavailable)
    }
}

struct ClaimWaiter {
    handle: ModuleHandle,
    corr: u64,
}
impl Drop for ClaimWaiter {
    fn drop(&mut self) {
        self.handle
            .shared
            .lock_inner()
            .pending_claim_calls
            .remove(&self.corr);
    }
}

pub(crate) fn bound() -> bool {
    supervised() || HELPER_BOUND.load(Ordering::Acquire)
}

async fn mint_claim(minter: &dyn ClaimMinter, purpose: ClaimPurpose) -> Result<Claim, ClaimError> {
    timeout(
        CATALOG_UPDATE_TIMEOUT,
        minter.mint(ClaimMintRequest::new(purpose)),
    )
    .await
    .map_err(|_| ClaimError::Timeout)?
    .map(|reply| reply.claim)
}

pub(crate) async fn bind_consumer<S: AsyncRead + AsyncWrite + Unpin>(
    stream: &mut S,
    deadline: Duration,
) -> Result<(), ClaimError> {
    let claim = if supervised() {
        let owner = OWNER.get().ok_or(ClaimError::Unavailable)?;
        Some(mint_claim(owner.as_ref(), ClaimPurpose::SelfConnection).await?)
    } else {
        os::helper_claim()
            .map_err(|_| ClaimError::Handoff)?
            .map(|claim| {
                HELPER_BOUND.store(true, Ordering::Release);
                Claim::new(claim.value())
            })
    };
    let Some(claim) = claim else {
        return Ok(());
    };
    present_claim(stream, claim, deadline).await
}

pub(crate) async fn present_claim<S: AsyncRead + AsyncWrite + Unpin>(
    stream: &mut S,
    claim: Claim,
    deadline: Duration,
) -> Result<(), ClaimError> {
    let frame = Frame::build(
        FrameType::Request,
        control_flags(),
        0,
        0,
        1,
        serde_json::to_vec(&ClaimPresentRequest::new(claim)).map_err(|_| ClaimError::Protocol)?,
    )
    .map_err(|_| ClaimError::Protocol)?;
    let reply = timeout(deadline, async {
        write_frame(stream, &frame)
            .await
            .map_err(|_| ClaimError::Unavailable)?;
        read_frame(stream)
            .await
            .map_err(|_| ClaimError::Unavailable)?
            .ok_or(ClaimError::Unavailable)
    })
    .await
    .map_err(|_| ClaimError::Timeout)??;
    if reply.header.channel != 0 || reply.header.epoch != 0 || reply.header.corr != 1 {
        return Err(ClaimError::Protocol);
    }
    if reply.header.ty == FrameType::Error {
        let error: ErrorBody =
            serde_json::from_slice(&reply.body).map_err(|_| ClaimError::Protocol)?;
        return Err(ClaimError::Refused { code: error.code });
    }
    if reply.header.ty != FrameType::Response {
        return Err(ClaimError::Protocol);
    }
    serde_json::from_slice::<ClaimPresentReply>(&reply.body).map_err(|_| ClaimError::Protocol)?;
    Ok(())
}

#[cfg(all(test, any(unix, windows)))]
#[path = "registration_tests.rs"]
mod registration_contract;