lean_ctx_cloud/bus/
mod.rs1pub mod address;
11pub mod control;
12pub mod exchange;
13pub mod handoff;
14pub mod leases;
15pub mod messages_v2;
16pub mod person_rules;
17pub mod plan_body;
18pub mod plan_events;
19pub mod plan_view;
20pub mod presence;
21pub mod queen_kinds;
22pub mod relay_v2;
23pub mod task_events;
24pub mod v2;
25pub mod veto;
26#[cfg(feature = "http-server")]
27mod ws;
28
29use crate::config::{CloudBusMode, CloudConfig};
30use crate::state::{CloudStore, StateLock, lock_state_within};
31
32const CLI_CLAIMS_PASS: std::time::Duration = std::time::Duration::from_secs(30);
34
35fn relay_lock(store: &CloudStore) -> Result<StateLock, crate::CloudError> {
40 lock_state_within(store.data_dir(), "relay", std::time::Duration::ZERO).map_err(|_| {
41 crate::CloudError::Local("another bus relay is already running on this machine".into())
42 })
43}
44
45#[cfg(feature = "http-server")]
49pub(crate) fn relay_config() -> Option<CloudConfig> {
50 let config = lean_ctx::core::config::Config::load_arc().cloud.clone();
51 (config.bus != CloudBusMode::Off && config.enabled != Some(false)).then_some(config)
52}
53
54const LOCK_RETRY: std::time::Duration = std::time::Duration::from_secs(5);
57const RESTART_FIRST: std::time::Duration = std::time::Duration::from_secs(5);
61const RESTART_MAX: std::time::Duration = std::time::Duration::from_secs(300);
62const RESTART_RESET: std::time::Duration = std::time::Duration::from_secs(600);
63
64type Sink = std::sync::Arc<dyn Fn(&str) + Send + Sync>;
66
67#[derive(Clone, Default)]
72pub struct Report {
73 sink: Option<Sink>,
74 last: std::sync::Arc<std::sync::Mutex<String>>,
75}
76
77impl Report {
78 pub fn quiet() -> Self {
80 Self::default()
81 }
82
83 pub fn to(sink: impl Fn(&str) + Send + Sync + 'static) -> Self {
85 Self {
86 sink: Some(std::sync::Arc::new(sink)),
87 last: std::sync::Arc::default(),
88 }
89 }
90
91 #[cfg_attr(not(feature = "http-server"), allow(dead_code))]
92 pub(crate) fn say(&self, line: &str) {
93 let Some(sink) = &self.sink else { return };
94 let mut last = self
95 .last
96 .lock()
97 .unwrap_or_else(std::sync::PoisonError::into_inner);
98 if *last != line {
99 line.clone_into(&mut last);
100 sink(line);
101 }
102 }
103}
104
105fn panic_text(payload: &(dyn std::any::Any + Send)) -> String {
107 payload
108 .downcast_ref::<&str>()
109 .map(|s| (*s).to_owned())
110 .or_else(|| payload.downcast_ref::<String>().cloned())
111 .unwrap_or_else(|| "unknown panic".into())
112}
113
114fn restart_delay(crashes: u32) -> std::time::Duration {
117 RESTART_FIRST
118 .saturating_mul(1u32 << crashes.saturating_sub(1).min(16))
119 .min(RESTART_MAX)
120}
121
122fn supervise(
130 store: &CloudStore,
131 mut run_once: impl FnMut(),
132 mut sleep: impl FnMut(std::time::Duration),
133) {
134 let mut crashes: u32 = 0;
135 loop {
136 let started = std::time::Instant::now();
137 match std::panic::catch_unwind(std::panic::AssertUnwindSafe(&mut run_once)) {
138 Ok(()) => return,
139 Err(payload) => {
140 if started.elapsed() >= RESTART_RESET {
141 crashes = 0;
142 }
143 crashes = crashes.saturating_add(1);
144 let delay = restart_delay(crashes);
145 let line = format!(
146 "bus: the relay crashed ({}); it starts again in {} s",
147 panic_text(payload.as_ref()),
148 delay.as_secs()
149 );
150 tracing::warn!("cloud {line}");
151 store.record_error(&line);
152 sleep(delay);
153 }
154 }
155 }
156}
157
158pub fn spawn(config: CloudConfig) -> Option<std::thread::JoinHandle<()>> {
161 if !cfg!(feature = "http-server") {
163 return None;
164 }
165 if config.bus == CloudBusMode::Off || config.enabled == Some(false) {
166 return None;
167 }
168 let store = CloudStore::open().ok()?;
169 if !matches!(store.instance(), Ok(Some(_))) {
170 return None;
171 }
172 std::thread::Builder::new()
173 .name("cloud-bus".into())
174 .spawn(move || {
175 let _relay = loop {
179 match relay_lock(&store) {
180 Ok(lock) => break lock,
181 Err(error) => {
182 tracing::debug!("cloud bus: {error}; asking again");
183 std::thread::sleep(LOCK_RETRY);
184 }
185 }
186 };
187 if let Err(error) = instance_card(&store, &config) {
190 tracing::info!("cloud instance card: {error}");
191 }
192 let _ = std::thread::Builder::new()
197 .name("cloud-cli-claims".into())
198 .spawn(|| {
199 loop {
200 std::thread::sleep(CLI_CLAIMS_PASS);
201 crate::tasks::keep_cli_claims();
202 crate::tasks::release_abandoned_claims();
203 }
204 });
205 let run_store = store.clone();
206 supervise(
207 &store,
208 move || {
209 let runtime = tokio::runtime::Builder::new_current_thread()
212 .enable_all()
213 .build()
214 .unwrap_or_else(|e| panic!("bus runtime: {e}"));
215 #[cfg(feature = "http-server")]
217 let _stopped = runtime.block_on(ws::run(
218 run_store.clone(),
219 config.clone(),
220 None,
221 Report::quiet(),
222 ));
223 #[cfg(not(feature = "http-server"))]
224 drop((runtime, &run_store, &config));
225 },
226 std::thread::sleep,
227 );
228 })
229 .ok()
230}
231
232fn instance_card(store: &CloudStore, config: &CloudConfig) -> Result<(), crate::CloudError> {
235 let instance = store.instance()?.ok_or(crate::CloudError::NotConnected)?;
236 let root = crate::root_cert::trust_root(store, config, &instance.url)?;
237 let session = crate::auth::Session::load(store.clone(), root)?;
238 crate::workers::register::announce_instance(&session).map(drop)
239}
240
241pub fn run_for(
248 config: CloudConfig,
249 duration: std::time::Duration,
250 report: Report,
251) -> Result<bool, crate::CloudError> {
252 let store = CloudStore::open()?;
253 let Ok(_relay) = relay_lock(&store) else {
256 return Ok(false);
257 };
258 let runtime = tokio::runtime::Builder::new_current_thread()
259 .enable_all()
260 .build()
261 .map_err(|e| crate::CloudError::Local(e.to_string()))?;
262 #[cfg(feature = "http-server")]
265 match runtime.block_on(ws::run(store, config, Some(duration), report)) {
266 Some(error) => Err(error),
267 None => Ok(true),
268 }
269 #[cfg(not(feature = "http-server"))]
270 {
271 drop((runtime, store, config, duration, report));
272 Err(crate::CloudError::Local(
273 "the bus relay needs a build with the http-server feature".into(),
274 ))
275 }
276}
277
278#[cfg(test)]
279mod tests {
280 use super::*;
281
282 #[test]
288 fn a_crashed_relay_is_recorded_and_started_again() {
289 let dir = tempfile::tempdir().unwrap();
290 let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
291 let mut runs = 0;
292 let mut waits = Vec::new();
293 supervise(
294 &store,
295 || {
296 runs += 1;
297 assert!(runs <= 3, "a run that returns ends the supervisor");
298 assert!(
300 runs >= 3,
301 "OS can't spawn worker thread: Resource temporarily unavailable"
302 );
303 },
304 |wait| waits.push(wait),
305 );
306 assert_eq!(runs, 3, "two crashes, then a run that returned");
307 assert_eq!(
308 waits,
309 [
310 std::time::Duration::from_secs(5),
311 std::time::Duration::from_secs(10)
312 ]
313 );
314 let error = store.activity().last_error.unwrap_or_default();
315 assert!(
316 error.contains("the relay crashed (OS can't spawn worker thread")
317 && error.contains("starts again in 10 s"),
318 "{error}"
319 );
320 }
321
322 #[test]
323 fn restarts_wait_longer_up_to_a_cap() {
324 assert_eq!(restart_delay(1), RESTART_FIRST);
325 assert_eq!(restart_delay(2), RESTART_FIRST * 2);
326 assert_eq!(restart_delay(9), RESTART_MAX);
327 assert_eq!(restart_delay(u32::MAX), RESTART_MAX);
328 }
329
330 #[test]
332 fn a_report_does_not_repeat_its_last_line() {
333 let said = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
334 let sink = said.clone();
335 let report = Report::to(move |line| sink.lock().unwrap().push(line.to_owned()));
336 report.say("waiting");
337 report.say("waiting");
338 report.say("connected");
339 report.say("waiting");
340 assert_eq!(*said.lock().unwrap(), ["waiting", "connected", "waiting"]);
341 Report::quiet().say("nobody hears this");
342 }
343}