use std::time::Duration;
use tokio_tungstenite::tungstenite::http::HeaderValue;
use crate::CloudError;
use crate::config::CloudConfig;
use crate::state::CloudStore;
use lean_ctx_protocol::cloud::CLOUD_API_PREFIX;
mod session;
const TICK: Duration = Duration::from_secs(2);
const WAKE_POLL: Duration = Duration::from_millis(200);
const CARD_RETRY: Duration = Duration::from_secs(60);
const RECONNECT_FIRST: Duration = Duration::from_secs(1);
const RECONNECT_JITTER_MS: u64 = 3_000;
const BACKOFF_MAX: Duration = Duration::from_secs(300);
fn reconnect_delay(failures: u32, jitter_ms: u64) -> Duration {
let base = RECONNECT_FIRST
.saturating_mul(1u32 << failures.min(16))
.min(BACKOFF_MAX);
base + Duration::from_millis(jitter_ms.min(RECONNECT_JITTER_MS))
}
fn jitter_ms() -> u64 {
u64::from_le_bytes(rand_nonce()) % (RECONNECT_JITTER_MS + 1)
}
fn ws_url(origin: &str) -> String {
let rest = origin
.strip_prefix("https://")
.map(|host| format!("wss://{host}"))
.or_else(|| {
origin
.strip_prefix("http://")
.map(|host| format!("ws://{host}"))
})
.unwrap_or_else(|| origin.to_string());
format!("{rest}{CLOUD_API_PREFIX}/bus")
}
fn bus_held(store: &CloudStore) -> bool {
crate::throttle::holding(
store,
crate::throttle::Scope::Bus,
lean_ctx_time::UtcDateTime::now(),
)
.is_some()
}
fn handshake_error(error: tokio_tungstenite::tungstenite::Error) -> CloudError {
match error {
tokio_tungstenite::tungstenite::Error::Http(response) => {
let status = response.status().as_u16();
let body = response
.body()
.as_deref()
.and_then(|b| serde_json::from_slice::<serde_json::Value>(b).ok())
.unwrap_or(serde_json::Value::Null);
match CloudError::from_response(status, &body) {
CloudError::Server { .. } if status == 401 => CloudError::Unauthorized,
CloudError::Server { .. } if status == 403 => CloudError::Forbidden,
CloudError::Server { status, code } if status < 500 && status != 429 => {
CloudError::Offline(format!("bus: LeanCTX Cloud answered {status} ({code})"))
}
mapped => mapped,
}
}
other => CloudError::Offline(format!(
"bus: {}",
other.to_string().chars().take(100).collect::<String>()
)),
}
}
fn fatal(error: &CloudError) -> bool {
matches!(
error,
CloudError::NotConnected
| CloudError::LeaseLapsed
| CloudError::Revoked(_)
| CloudError::Forbidden
| CloudError::Config(_)
| CloudError::UpgradeRequired { .. }
)
}
fn stopped(store: &CloudStore, error: CloudError) -> CloudError {
let error = match (&error, store.instance()) {
(CloudError::Revoked(_), Ok(Some(instance))) => {
crate::revoked::note(store, &instance, error)
}
_ => error,
};
store.record_error(&format!("bus: {error}"));
tracing::warn!("cloud bus relay stopped: {error}");
error
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SessionEnd {
Closed,
Reannounce,
Replay,
}
pub(super) async fn run(
store: CloudStore,
_started_with: CloudConfig,
limit: Option<Duration>,
report: super::Report,
) -> Option<CloudError> {
let _friction = FrictionEmitter::start(store.clone());
let deadline = limit.map(|limit| tokio::time::Instant::now() + limit);
let mut failures: u32 = 0;
let mut card_due: Option<tokio::time::Instant> = None;
loop {
let Some(config) = super::relay_config() else {
report.say(
"bus relay: the bus is off in [cloud] (bus = \"off\" or enabled = false): nothing is sent until it is on again",
);
tokio::select! {
() = tokio::time::sleep(TICK) => continue,
() = sleep_until(deadline) => return None,
}
};
if !super::relay_v2::speaks_v2(&store) {
if card_due.is_none_or(|at| at <= tokio::time::Instant::now()) {
card_due = Some(tokio::time::Instant::now() + CARD_RETRY);
let (card_store, card_config) = (store.clone(), config.clone());
let card = tokio::task::spawn_blocking(move || {
super::instance_card(&card_store, &card_config)
})
.await
.unwrap_or_else(|e| Err(CloudError::Local(e.to_string())));
match card {
Err(error) if fatal(&error) => return Some(stopped(&store, error)),
Err(error) => {
report.say(&format!(
"bus relay: the instance card failed ({error}); no socket is opened, asking again in {} s",
CARD_RETRY.as_secs()
));
store.record_error(&format!("bus: instance card: {error}"));
}
Ok(()) => {}
}
if super::relay_v2::speaks_v2(&store) {
continue;
}
report.say(&format!(
"bus relay: LeanCTX Cloud's instance card did not confirm bus protocol 2.x: no socket is opened, asking again in {} s",
CARD_RETRY.as_secs()
));
}
tokio::select! {
() = tokio::time::sleep(TICK) => continue,
() = sleep_until(deadline) => return None,
}
}
let mut connected = false;
let session = tokio::select! {
result = session::session_once(&store, &config, &mut connected, &report) => result,
() = sleep_until(deadline) => return None,
};
failures = if connected {
0
} else {
failures.saturating_add(1)
};
let delay = reconnect_delay(failures, jitter_ms());
match session {
Ok(SessionEnd::Reannounce) => {
report.say("bus relay: announcing this machine's agents afresh");
continue;
}
Ok(SessionEnd::Replay) => {
report.say("bus relay: a bus moved to a new place or epoch; replaying it from the start");
continue;
}
Ok(SessionEnd::Closed) => report.say(&format!(
"bus relay: LeanCTX Cloud closed the socket (its workers left the bus); reconnecting in {} s",
delay.as_secs()
)),
Err(error) if fatal(&error) => return Some(stopped(&store, error)),
Err(error) => {
report.say(&format!(
"bus relay: {error}; trying again in {} s",
delay.as_secs()
));
store.record_error(&format!("bus: {error}"));
}
}
tokio::select! {
() = tokio::time::sleep(delay) => {}
() = sleep_until(deadline) => return None,
}
}
}
async fn sleep_until(deadline: Option<tokio::time::Instant>) {
match deadline {
Some(at) => tokio::time::sleep_until(at).await,
None => std::future::pending().await,
}
}
const FRICTION_EVERY: Duration = Duration::from_secs(60);
struct FrictionEmitter(tokio::task::JoinHandle<()>);
impl FrictionEmitter {
fn start(store: CloudStore) -> Self {
Self(tokio::spawn(async move {
let mut every = tokio::time::interval(FRICTION_EVERY);
let mut conflicted = std::collections::BTreeSet::new();
loop {
every.tick().await;
let store = store.clone();
let mut seen = std::mem::take(&mut conflicted);
conflicted = tokio::task::spawn_blocking(move || {
crate::friction::sample_merge_conflicts(&store, &mut seen);
crate::friction::emit_due(&store, lean_ctx_time::UtcDateTime::now());
seen
})
.await
.unwrap_or_default();
}
}))
}
}
impl Drop for FrictionEmitter {
fn drop(&mut self) {
self.0.abort();
}
}
fn header(value: &str) -> Result<HeaderValue, CloudError> {
HeaderValue::from_str(value).map_err(|_| CloudError::Local("header value".into()))
}
type Socket =
tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>;
async fn open_socket(
request: tokio_tungstenite::tungstenite::handshake::client::Request,
) -> Result<
(
Socket,
tokio_tungstenite::tungstenite::handshake::client::Response,
),
tokio_tungstenite::tungstenite::Error,
> {
lean_ctx::core::crypto_provider::install_default();
tokio_tungstenite::connect_async(request).await
}
fn rand_nonce() -> [u8; 8] {
let mut bytes = [0u8; 8];
let _ = getrandom::fill(&mut bytes);
bytes
}
#[cfg(test)]
mod tests {
use super::*;
use tokio_tungstenite::tungstenite::client::IntoClientRequest as _;
const PROVIDER_CHILD: &str = "LEAN_CTX_TEST_WS_PROVIDER_CHILD";
#[test]
fn a_revocation_ends_the_relay() {
assert!(fatal(&CloudError::Revoked(crate::Revocation::default())));
assert!(!fatal(&CloudError::Offline("reset".into())));
}
const REVOKED_BODY: &str = include_str!(
"../../../../../crates/lean-ctx-protocol/tests/fixtures/cloud-v2/routes/instance_revoked.error.json"
);
fn refused_upgrade(status: u16, body: Option<&str>) -> CloudError {
let response = tokio_tungstenite::tungstenite::http::Response::builder()
.status(status)
.body(body.map(|b| b.as_bytes().to_vec()))
.unwrap();
handshake_error(tokio_tungstenite::tungstenite::Error::Http(Box::new(
response,
)))
}
#[test]
fn a_refused_upgrade_is_read_by_its_body() {
let revoked = refused_upgrade(401, Some(REVOKED_BODY));
assert!(
matches!(&revoked, CloudError::Revoked(r) if r.reason.as_deref() == Some("key_compromise"))
);
assert!(fatal(&revoked));
assert_eq!(refused_upgrade(401, None), CloudError::Unauthorized);
assert_eq!(refused_upgrade(403, Some("<html>")), CloudError::Forbidden);
let denied = refused_upgrade(
403,
Some(
r#"{"error":{"code":"policy_denied","message":"x","member":"sharing.allowed_vaults","level":"org"}}"#,
),
);
assert!(matches!(denied, CloudError::PolicyDenied(_)));
assert!(
!fatal(&denied),
"a policy may change: the relay keeps reconnecting with its backoff"
);
let busy = refused_upgrade(503, None);
assert!(busy.is_transient() && !fatal(&busy));
let quota = refused_upgrade(
429,
Some(
r#"{"error":{"code":"quota_exceeded","message":"x","resource":"transfer_bytes","retry_after_s":60}}"#,
),
);
assert!(quota.is_transient() && !fatal("a));
assert!(matches!(refused_upgrade(404, None), CloudError::Offline(_)));
}
fn revoked_store() -> (tempfile::TempDir, CloudStore, CloudConfig) {
let dir = tempfile::tempdir().unwrap();
let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
let instance = crate::state::InstanceRecord {
instance_id: "inst_8e3c0d5f2b4e4f609b8c1d2e3f4a5b6c".into(),
org_id: "4b6d8f0a-2c4e-4f6a-8b0c-2e4f6a8c0e1a".into(),
org_name: "acme".into(),
label: "laptop".into(),
url: lean_ctx_protocol::cloud::CLOUD_DEFAULT_URL.into(),
org_salt_id: "s".into(),
enrolled_at: "2026-10-25T10:00:00Z".into(),
web_url: None,
org_kind: None,
company_name: None,
};
store
.write_config(crate::state::INSTANCE_FILE, &instance)
.unwrap();
let config = CloudConfig {
root_key: Some("BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc=".into()),
..CloudConfig::default()
};
(dir, store, config)
}
const REVOKED_LINE: &str = "this instance was revoked by acme (key compromise); reconnect with \
`lean-ctx cloud connect` after an admin allows it";
#[test]
fn a_stopped_relay_records_the_revocation_and_names_it() {
let (_dir, store, _) = revoked_store();
let shown = stopped(&store, refused_upgrade(401, Some(REVOKED_BODY)));
assert_eq!(shown.to_string(), REVOKED_LINE);
let instance = store.instance().unwrap().unwrap();
assert_eq!(
crate::revoked::recorded(&store, &instance),
Some(shown.clone())
);
assert_eq!(
store.activity().last_error.as_deref(),
Some(format!("bus: {REVOKED_LINE}").as_str())
);
}
#[test]
fn a_recorded_revocation_stops_the_relay_at_once() {
let (_dir, store, config) = revoked_store();
let _ = stopped(&store, refused_upgrade(401, Some(REVOKED_BODY)));
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
let started = std::time::Instant::now();
let end = runtime.block_on(run(
store,
config,
Some(Duration::from_secs(60)),
crate::bus::Report::quiet(),
));
assert_eq!(end.map(|e| e.to_string()).as_deref(), Some(REVOKED_LINE));
assert!(
started.elapsed() < Duration::from_secs(30),
"no reconnect loop"
);
}
#[test]
fn a_wss_connect_names_the_crypto_provider_itself() {
if std::env::var_os(PROVIDER_CHILD).is_some() {
assert!(
rustls::crypto::CryptoProvider::get_default().is_none(),
"fresh process"
);
let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("listen");
let port = listener.local_addr().expect("addr").port();
std::thread::spawn(move || {
if let Ok((stream, _)) = listener.accept() {
drop(stream);
}
});
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("runtime");
let request = format!("wss://127.0.0.1:{port}/v1/bus")
.into_client_request()
.expect("request");
assert!(runtime.block_on(open_socket(request)).is_err());
return;
}
let output = std::process::Command::new(std::env::current_exe().expect("test binary"))
.args([
"--exact",
"bus::ws::tests::a_wss_connect_names_the_crypto_provider_itself",
"--nocapture",
"--test-threads=1",
])
.env(PROVIDER_CHILD, "1")
.output()
.expect("child test");
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(output.status.success(), "{stderr}");
assert!(!stderr.contains("CryptoProvider"), "{stderr}");
}
#[test]
fn a_relay_that_was_up_reconnects_within_seconds() {
assert_eq!(reconnect_delay(0, 0), Duration::from_secs(1));
assert_eq!(reconnect_delay(0, 3_000), Duration::from_secs(4));
assert_eq!(
reconnect_delay(0, 999_999),
Duration::from_secs(4),
"jitter is bounded"
);
assert_eq!(reconnect_delay(1, 0), Duration::from_secs(2));
assert_eq!(reconnect_delay(3, 0), Duration::from_secs(8));
assert_eq!(reconnect_delay(9, 0), BACKOFF_MAX);
assert_eq!(reconnect_delay(u32::MAX, 0), BACKOFF_MAX);
for _ in 0..100 {
assert!(jitter_ms() <= RECONNECT_JITTER_MS);
}
}
#[test]
fn bus_urls_follow_the_origin_scheme() {
assert_eq!(
ws_url("https://cloud.leanctx.com"),
"wss://cloud.leanctx.com/v1/bus"
);
assert_eq!(
ws_url("http://127.0.0.1:8100"),
"ws://127.0.0.1:8100/v1/bus"
);
}
}