Skip to main content

agentmux_srv_core/muxbus/cloud_subscriber/
sign_in.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What the subscriber's loop asks of the stored sign-in: whether it can be used
5//! or refreshed, whether a refresh came back for the same account, and a wait for
6//! a new sign-in.
7
8use std::sync::Arc;
9use std::time::Duration;
10
11use tokio::sync::mpsc;
12
13use super::supervisor::beat;
14use super::CtrlMsg;
15use crate::backend::storage::store::Store;
16
17/// [`super::load_valid_token`] for the subscriber's own loop, which stamps its progress once the
18/// call returns. Only code that runs in the loop may stamp: the helper is shared with callers
19/// elsewhere, and a stamp from them would hide a stalled loop.
20pub(super) async fn token_for_loop(mstore: &Arc<Store>, scheduler: &crate::broker::RefreshScheduler) -> Option<String> {
21    let token = super::load_valid_token(mstore, scheduler).await;
22    beat();
23    token
24}
25
26/// A loaded sign-in that can be used now or refreshed: a valid access token,
27/// or a refresh token (all a torn sign-in keeps, see `storage::muxbus`).
28pub(super) fn usable_or_refreshable(c: &crate::muxbus::MuxBusCredentials) -> bool {
29    c.is_valid() || !c.refresh_token.is_empty()
30}
31
32/// Whether a refresh came back for the account the saved sign-in names. A
33/// torn set could pair a refresh token with another account's row; a row
34/// with no account recorded (an older sign-in) can't be checked.
35pub(super) fn refreshed_same_account(current: &crate::muxbus::MuxBusCredentials, refreshed: &crate::muxbus::MuxBusCredentials) -> bool {
36    if current.user_sub.is_empty() {
37        return true;
38    }
39    let sub = crate::muxbus::pkce::token_sub(&refreshed.id_token);
40    let sub = if sub.is_empty() { crate::muxbus::pkce::token_sub(&refreshed.access_token) } else { sub };
41    sub == current.user_sub
42}
43
44/// Park until a sign-in (`ReloadToken`) or `recheck` elapses, whichever comes
45/// first. AddAgent/RemoveAgent drain without waking it: they already updated
46/// the `agents` set the next connection subscribes from.
47pub(super) async fn wait_for_sign_in(ctrl_rx: &mut mpsc::UnboundedReceiver<CtrlMsg>, recheck: Duration) {
48    beat();
49    let sleep = tokio::time::sleep(recheck);
50    tokio::pin!(sleep);
51    loop {
52        tokio::select! {
53            _ = &mut sleep => return,
54            msg = ctrl_rx.recv() => match msg {
55                Some(CtrlMsg::ReloadToken) => return,
56                Some(CtrlMsg::AddAgent(_) | CtrlMsg::RemoveAgent(_)) => {}
57                // Closed: nothing can wake us early; wait out the recheck.
58                None => {
59                    (&mut sleep).await;
60                    return;
61                }
62            }
63        }
64    }
65}