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::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 != crate::config::CloudBusMode::Off && config.enabled != Some(false))
52 .then_some(config)
53}
54
55const LOCK_RETRY: std::time::Duration = std::time::Duration::from_secs(5);
58const RESTART_FIRST: std::time::Duration = std::time::Duration::from_secs(5);
62const RESTART_MAX: std::time::Duration = std::time::Duration::from_secs(300);
63const RESTART_RESET: std::time::Duration = std::time::Duration::from_secs(600);
64
65type Sink = std::sync::Arc<dyn Fn(&str) + Send + Sync>;
67
68#[derive(Clone, Default)]
73pub struct Report {
74 sink: Option<Sink>,
75 last: std::sync::Arc<std::sync::Mutex<String>>,
76}
77
78impl Report {
79 pub fn quiet() -> Self {
81 Self::default()
82 }
83
84 pub fn to(sink: impl Fn(&str) + Send + Sync + 'static) -> Self {
86 Self {
87 sink: Some(std::sync::Arc::new(sink)),
88 last: std::sync::Arc::default(),
89 }
90 }
91
92 #[cfg_attr(not(feature = "http-server"), allow(dead_code))]
93 pub(crate) fn say(&self, line: &str) {
94 let Some(sink) = &self.sink else { return };
95 let mut last = self
96 .last
97 .lock()
98 .unwrap_or_else(std::sync::PoisonError::into_inner);
99 if *last != line {
100 line.clone_into(&mut last);
101 sink(line);
102 }
103 }
104}
105
106fn panic_text(payload: &(dyn std::any::Any + Send)) -> String {
108 payload
109 .downcast_ref::<&str>()
110 .map(|s| (*s).to_owned())
111 .or_else(|| payload.downcast_ref::<String>().cloned())
112 .unwrap_or_else(|| "unknown panic".into())
113}
114
115fn restart_delay(crashes: u32) -> std::time::Duration {
118 RESTART_FIRST
119 .saturating_mul(1u32 << crashes.saturating_sub(1).min(16))
120 .min(RESTART_MAX)
121}
122
123fn supervise(
131 store: &CloudStore,
132 mut run_once: impl FnMut(),
133 mut sleep: impl FnMut(std::time::Duration),
134) {
135 let mut crashes: u32 = 0;
136 loop {
137 let started = std::time::Instant::now();
138 match std::panic::catch_unwind(std::panic::AssertUnwindSafe(&mut run_once)) {
139 Ok(()) => return,
140 Err(payload) => {
141 if started.elapsed() >= RESTART_RESET {
142 crashes = 0;
143 }
144 crashes = crashes.saturating_add(1);
145 let delay = restart_delay(crashes);
146 let line = format!(
147 "bus: the relay crashed ({}); it starts again in {} s",
148 panic_text(payload.as_ref()),
149 delay.as_secs()
150 );
151 tracing::warn!("cloud {line}");
152 store.record_error(&line);
153 sleep(delay);
154 }
155 }
156 }
157}
158
159const WAIT_FOR_BUS: std::time::Duration = std::time::Duration::from_secs(30);
162
163fn wait_for_bus() -> CloudConfig {
165 loop {
166 #[cfg(feature = "http-server")]
167 if let Some(config) = relay_config() {
168 return config;
169 }
170 std::thread::sleep(WAIT_FOR_BUS);
171 }
172}
173
174pub fn spawn() -> Option<std::thread::JoinHandle<()>> {
179 if !cfg!(feature = "http-server") {
181 return None;
182 }
183 let store = CloudStore::open().ok()?;
184 if !matches!(store.instance(), Ok(Some(_))) {
185 return None;
186 }
187 std::thread::Builder::new()
188 .name("cloud-bus".into())
189 .spawn(move || {
190 let config = wait_for_bus();
191 let _relay = loop {
195 match relay_lock(&store) {
196 Ok(lock) => break lock,
197 Err(error) => {
198 tracing::debug!("cloud bus: {error}; asking again");
199 std::thread::sleep(LOCK_RETRY);
200 }
201 }
202 };
203 if let Err(error) = instance_card(&store, &config) {
206 tracing::info!("cloud instance card: {error}");
207 }
208 let _ = std::thread::Builder::new()
213 .name("cloud-cli-claims".into())
214 .spawn(|| {
215 loop {
216 std::thread::sleep(CLI_CLAIMS_PASS);
217 crate::tasks::keep_cli_claims();
218 crate::tasks::release_abandoned_claims();
219 }
220 });
221 let run_store = store.clone();
222 supervise(
223 &store,
224 move || {
225 let runtime = tokio::runtime::Builder::new_current_thread()
228 .enable_all()
229 .build()
230 .unwrap_or_else(|e| panic!("bus runtime: {e}"));
231 #[cfg(feature = "http-server")]
233 let _stopped = runtime.block_on(ws::run(
234 run_store.clone(),
235 config.clone(),
236 None,
237 Report::quiet(),
238 ));
239 #[cfg(not(feature = "http-server"))]
240 drop((runtime, &run_store, &config));
241 },
242 std::thread::sleep,
243 );
244 })
245 .ok()
246}
247
248fn instance_card(store: &CloudStore, config: &CloudConfig) -> Result<(), crate::CloudError> {
251 let instance = store.instance()?.ok_or(crate::CloudError::NotConnected)?;
252 let root = crate::root_cert::trust_root(store, config, &instance.url)?;
253 let session = crate::auth::Session::load(store.clone(), root)?;
254 crate::workers::register::announce_instance(&session).map(drop)
255}
256
257pub fn run_for(
264 config: CloudConfig,
265 duration: std::time::Duration,
266 report: Report,
267) -> Result<bool, crate::CloudError> {
268 let store = CloudStore::open()?;
269 let Ok(_relay) = relay_lock(&store) else {
272 return Ok(false);
273 };
274 let runtime = tokio::runtime::Builder::new_current_thread()
275 .enable_all()
276 .build()
277 .map_err(|e| crate::CloudError::Local(e.to_string()))?;
278 #[cfg(feature = "http-server")]
281 match runtime.block_on(ws::run(store, config, Some(duration), report)) {
282 Some(error) => Err(error),
283 None => Ok(true),
284 }
285 #[cfg(not(feature = "http-server"))]
286 {
287 drop((runtime, store, config, duration, report));
288 Err(crate::CloudError::Local(
289 "the bus relay needs a build with the http-server feature".into(),
290 ))
291 }
292}
293
294#[cfg(test)]
295mod tests {
296 use super::*;
297
298 #[test]
304 fn a_crashed_relay_is_recorded_and_started_again() {
305 let dir = tempfile::tempdir().unwrap();
306 let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
307 let mut runs = 0;
308 let mut waits = Vec::new();
309 supervise(
310 &store,
311 || {
312 runs += 1;
313 assert!(runs <= 3, "a run that returns ends the supervisor");
314 assert!(
316 runs >= 3,
317 "OS can't spawn worker thread: Resource temporarily unavailable"
318 );
319 },
320 |wait| waits.push(wait),
321 );
322 assert_eq!(runs, 3, "two crashes, then a run that returned");
323 assert_eq!(
324 waits,
325 [
326 std::time::Duration::from_secs(5),
327 std::time::Duration::from_secs(10)
328 ]
329 );
330 let error = store.activity().last_error.unwrap_or_default();
331 assert!(
332 error.contains("the relay crashed (OS can't spawn worker thread")
333 && error.contains("starts again in 10 s"),
334 "{error}"
335 );
336 }
337
338 #[test]
339 fn restarts_wait_longer_up_to_a_cap() {
340 assert_eq!(restart_delay(1), RESTART_FIRST);
341 assert_eq!(restart_delay(2), RESTART_FIRST * 2);
342 assert_eq!(restart_delay(9), RESTART_MAX);
343 assert_eq!(restart_delay(u32::MAX), RESTART_MAX);
344 }
345
346 #[test]
348 fn a_report_does_not_repeat_its_last_line() {
349 let said = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
350 let sink = said.clone();
351 let report = Report::to(move |line| sink.lock().unwrap().push(line.to_owned()));
352 report.say("waiting");
353 report.say("waiting");
354 report.say("connected");
355 report.say("waiting");
356 assert_eq!(*said.lock().unwrap(), ["waiting", "connected", "waiting"]);
357 Report::quiet().say("nobody hears this");
358 }
359}