pub mod address;
pub mod control;
pub mod exchange;
pub mod handoff;
pub mod leases;
pub mod messages_v2;
pub mod person_rules;
pub mod plan_body;
pub mod plan_events;
pub mod plan_view;
pub mod presence;
pub mod queen_kinds;
pub mod relay_v2;
pub mod task_events;
pub mod v2;
pub mod veto;
#[cfg(feature = "http-server")]
mod ws;
use crate::config::CloudConfig;
use crate::state::{CloudStore, StateLock, lock_state_within};
const CLI_CLAIMS_PASS: std::time::Duration = std::time::Duration::from_secs(30);
fn relay_lock(store: &CloudStore) -> Result<StateLock, crate::CloudError> {
lock_state_within(store.data_dir(), "relay", std::time::Duration::ZERO).map_err(|_| {
crate::CloudError::Local("another bus relay is already running on this machine".into())
})
}
#[cfg(feature = "http-server")]
pub(crate) fn relay_config() -> Option<CloudConfig> {
let config = lean_ctx::core::config::Config::load_arc().cloud.clone();
(config.bus != crate::config::CloudBusMode::Off && config.enabled != Some(false))
.then_some(config)
}
const LOCK_RETRY: std::time::Duration = std::time::Duration::from_secs(5);
const RESTART_FIRST: std::time::Duration = std::time::Duration::from_secs(5);
const RESTART_MAX: std::time::Duration = std::time::Duration::from_secs(300);
const RESTART_RESET: std::time::Duration = std::time::Duration::from_secs(600);
type Sink = std::sync::Arc<dyn Fn(&str) + Send + Sync>;
#[derive(Clone, Default)]
pub struct Report {
sink: Option<Sink>,
last: std::sync::Arc<std::sync::Mutex<String>>,
}
impl Report {
pub fn quiet() -> Self {
Self::default()
}
pub fn to(sink: impl Fn(&str) + Send + Sync + 'static) -> Self {
Self {
sink: Some(std::sync::Arc::new(sink)),
last: std::sync::Arc::default(),
}
}
#[cfg_attr(not(feature = "http-server"), allow(dead_code))]
pub(crate) fn say(&self, line: &str) {
let Some(sink) = &self.sink else { return };
let mut last = self
.last
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if *last != line {
line.clone_into(&mut last);
sink(line);
}
}
}
fn panic_text(payload: &(dyn std::any::Any + Send)) -> String {
payload
.downcast_ref::<&str>()
.map(|s| (*s).to_owned())
.or_else(|| payload.downcast_ref::<String>().cloned())
.unwrap_or_else(|| "unknown panic".into())
}
fn restart_delay(crashes: u32) -> std::time::Duration {
RESTART_FIRST
.saturating_mul(1u32 << crashes.saturating_sub(1).min(16))
.min(RESTART_MAX)
}
fn supervise(
store: &CloudStore,
mut run_once: impl FnMut(),
mut sleep: impl FnMut(std::time::Duration),
) {
let mut crashes: u32 = 0;
loop {
let started = std::time::Instant::now();
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(&mut run_once)) {
Ok(()) => return,
Err(payload) => {
if started.elapsed() >= RESTART_RESET {
crashes = 0;
}
crashes = crashes.saturating_add(1);
let delay = restart_delay(crashes);
let line = format!(
"bus: the relay crashed ({}); it starts again in {} s",
panic_text(payload.as_ref()),
delay.as_secs()
);
tracing::warn!("cloud {line}");
store.record_error(&line);
sleep(delay);
}
}
}
}
const WAIT_FOR_BUS: std::time::Duration = std::time::Duration::from_secs(30);
fn wait_for_bus() -> CloudConfig {
loop {
#[cfg(feature = "http-server")]
if let Some(config) = relay_config() {
return config;
}
std::thread::sleep(WAIT_FOR_BUS);
}
}
pub fn spawn() -> Option<std::thread::JoinHandle<()>> {
if !cfg!(feature = "http-server") {
return None;
}
let store = CloudStore::open().ok()?;
if !matches!(store.instance(), Ok(Some(_))) {
return None;
}
std::thread::Builder::new()
.name("cloud-bus".into())
.spawn(move || {
let config = wait_for_bus();
let _relay = loop {
match relay_lock(&store) {
Ok(lock) => break lock,
Err(error) => {
tracing::debug!("cloud bus: {error}; asking again");
std::thread::sleep(LOCK_RETRY);
}
}
};
if let Err(error) = instance_card(&store, &config) {
tracing::info!("cloud instance card: {error}");
}
let _ = std::thread::Builder::new()
.name("cloud-cli-claims".into())
.spawn(|| {
loop {
std::thread::sleep(CLI_CLAIMS_PASS);
crate::tasks::keep_cli_claims();
crate::tasks::release_abandoned_claims();
}
});
let run_store = store.clone();
supervise(
&store,
move || {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap_or_else(|e| panic!("bus runtime: {e}"));
#[cfg(feature = "http-server")]
let _stopped = runtime.block_on(ws::run(
run_store.clone(),
config.clone(),
None,
Report::quiet(),
));
#[cfg(not(feature = "http-server"))]
drop((runtime, &run_store, &config));
},
std::thread::sleep,
);
})
.ok()
}
fn instance_card(store: &CloudStore, config: &CloudConfig) -> Result<(), crate::CloudError> {
let instance = store.instance()?.ok_or(crate::CloudError::NotConnected)?;
let root = crate::root_cert::trust_root(store, config, &instance.url)?;
let session = crate::auth::Session::load(store.clone(), root)?;
crate::workers::register::announce_instance(&session).map(drop)
}
pub fn run_for(
config: CloudConfig,
duration: std::time::Duration,
report: Report,
) -> Result<bool, crate::CloudError> {
let store = CloudStore::open()?;
let Ok(_relay) = relay_lock(&store) else {
return Ok(false);
};
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.map_err(|e| crate::CloudError::Local(e.to_string()))?;
#[cfg(feature = "http-server")]
match runtime.block_on(ws::run(store, config, Some(duration), report)) {
Some(error) => Err(error),
None => Ok(true),
}
#[cfg(not(feature = "http-server"))]
{
drop((runtime, store, config, duration, report));
Err(crate::CloudError::Local(
"the bus relay needs a build with the http-server feature".into(),
))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_crashed_relay_is_recorded_and_started_again() {
let dir = tempfile::tempdir().unwrap();
let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
let mut runs = 0;
let mut waits = Vec::new();
supervise(
&store,
|| {
runs += 1;
assert!(runs <= 3, "a run that returns ends the supervisor");
assert!(
runs >= 3,
"OS can't spawn worker thread: Resource temporarily unavailable"
);
},
|wait| waits.push(wait),
);
assert_eq!(runs, 3, "two crashes, then a run that returned");
assert_eq!(
waits,
[
std::time::Duration::from_secs(5),
std::time::Duration::from_secs(10)
]
);
let error = store.activity().last_error.unwrap_or_default();
assert!(
error.contains("the relay crashed (OS can't spawn worker thread")
&& error.contains("starts again in 10 s"),
"{error}"
);
}
#[test]
fn restarts_wait_longer_up_to_a_cap() {
assert_eq!(restart_delay(1), RESTART_FIRST);
assert_eq!(restart_delay(2), RESTART_FIRST * 2);
assert_eq!(restart_delay(9), RESTART_MAX);
assert_eq!(restart_delay(u32::MAX), RESTART_MAX);
}
#[test]
fn a_report_does_not_repeat_its_last_line() {
let said = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
let sink = said.clone();
let report = Report::to(move |line| sink.lock().unwrap().push(line.to_owned()));
report.say("waiting");
report.say("waiting");
report.say("connected");
report.say("waiting");
assert_eq!(*said.lock().unwrap(), ["waiting", "connected", "waiting"]);
Report::quiet().say("nobody hears this");
}
}