Skip to main content

lean_ctx_cloud/bus/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2//! The cross-instance agent bus: the local bus (`ctx_agent`) of every
3//! machine of an organization joined through Cloud.
4//!
5//! One relay per machine runs in the daemon ([`spawn`]); it never runs in a
6//! tool call. Offline, the local bus keeps working exactly as before; on
7//! reconnect the relay catches up from its cursors and republishes what is
8//! pending (Cloud deduplicates by `client_msg_id`).
9
10pub 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
32/// How often the relay's process looks after CLI claims (lean-ctx #3).
33const CLI_CLAIMS_PASS: std::time::Duration = std::time::Duration::from_secs(30);
34
35/// One relay per machine (RB8 M11): two would overwrite each other's
36/// cursors and send twice. The daemon's relay and `cloud bus relay --for`
37/// take `<data>/cloud/relay.lock` without waiting; whoever does not get it
38/// does not relay.
39fn 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/// `[cloud]` as it is now, when it lets the relay run (`bus` not `off`,
46/// Cloud not disabled). The relay reads it before every connect and on
47/// every tick, so switching the bus off takes effect without a restart.
48#[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
55/// How long the daemon's relay waits before it asks for the relay lock
56/// again while another relay (a foreground `cloud bus relay --for`) holds it.
57const LOCK_RETRY: std::time::Duration = std::time::Duration::from_secs(5);
58/// The first restart after the daemon's relay crashed, doubled per crash in
59/// a row, at most [`RESTART_MAX`]. A run that lasted [`RESTART_RESET`]
60/// forgives the crashes before it.
61const 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
65/// Where a [`Report`] line goes.
66type Sink = std::sync::Arc<dyn Fn(&str) + Send + Sync>;
67
68/// Where a relay says what it does. The foreground `cloud bus relay`
69/// prints it; the daemon's relay is quiet (its errors reach `cloud status`).
70/// A line equal to the one said last is not repeated, so a relay that
71/// waits says why once, not on every tick.
72#[derive(Clone, Default)]
73pub struct Report {
74    sink: Option<Sink>,
75    last: std::sync::Arc<std::sync::Mutex<String>>,
76}
77
78impl Report {
79    /// A relay that says nothing (the daemon's).
80    pub fn quiet() -> Self {
81        Self::default()
82    }
83
84    /// A relay that hands every line to `sink`.
85    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
106/// The text of a panic payload.
107fn 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
115/// The wait before restart number `crashes` (1 = the first) of a crashed
116/// relay.
117fn 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
123/// Run the daemon's relay until it stops for good (`run_once` returns: a
124/// revocation, a lapsed lease; the relay records those itself). A panic in
125/// it, e.g. tokio's `spawn_blocking` when the OS refuses a thread (#252:
126/// "OS can't spawn worker thread"), no longer ends the relay for the
127/// daemon's lifetime: it is recorded for `cloud status` and the relay starts
128/// again after [`restart_delay`]. The relay lock stays held meanwhile, so
129/// no second relay starts in between.
130fn 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
159/// How often the daemon's relay thread looks again while `[cloud]` keeps
160/// the bus off: switching it on starts the relay without a daemon restart.
161const WAIT_FOR_BUS: std::time::Duration = std::time::Duration::from_secs(30);
162
163/// `[cloud]` once it lets the relay run; until then nothing is sent to Cloud.
164fn 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
174/// Start the bus relay thread when this machine is connected. While the
175/// bus is off or Cloud is disabled it waits and sends nothing; rc4-82: a
176/// daemon started with `bus = "off"` used to stay without a relay for its
177/// whole life, so turning the bus on later never reached the team.
178pub fn spawn() -> Option<std::thread::JoinHandle<()>> {
179    // The relay speaks WebSocket, which only an http-server build carries.
180    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            // A foreground `cloud bus relay --for` may hold the lock right
192            // now (#252: one that ran while the daemon started left the
193            // daemon without a relay for its whole life). Wait for it.
194            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            // Engine start: the instance card (E44, SPEC-ENGINE ยง3.6). It
204            // runs on this thread before the socket loop and never stops it.
205            if let Err(error) = instance_card(&store, &config) {
206                tracing::info!("cloud instance card: {error}");
207            }
208            // The relay's process outlives CLI calls: it keeps the claims
209            // `lean-ctx cloud tasks claim` made for agents still at work, and
210            // gives back the claims nobody works on any more (an ended
211            // session's, an expired one), so others can take the task.
212            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                    // A runtime the OS cannot build (no threads left) is a
226                    // crash like any other: the supervisor tries again.
227                    let runtime = tokio::runtime::Builder::new_current_thread()
228                        .enable_all()
229                        .build()
230                        .unwrap_or_else(|e| panic!("bus runtime: {e}"));
231                    // A fatal stop is logged and recorded by the relay itself.
232                    #[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
248/// Exchange the instance card (E44); its answer records which protocol
249/// the enrolled Cloud speaks, which the relay needs before it connects.
250fn 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
257/// Run the relay in the foreground for `duration` (`lean-ctx cloud bus
258/// relay --for <seconds>`), e.g. to watch it or in tests. When another
259/// relay (the daemon's) already runs, nothing runs here and `Ok(false)`
260/// says so: the caller then asks that relay to announce now. `report` hears
261/// what the relay sends (each hello's workers, roles and buses) and why it
262/// sends nothing, when it does not.
263pub 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    // The caller asks the running relay to announce
270    // (`presence::announce_and_wait`) and prints its answer.
271    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    // A relay that stopped for good (a revocation, a lapsed lease) says
279    // why, in the words every other CLI path uses.
280    #[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    /// #252: on pounce the daemon's relay thread panicked once (tokio's
299    /// `spawn_blocking` could not get a thread) and was gone for good, so
300    /// no worker of that machine was on the bus any more and role-gated
301    /// claims were refused. A crash is now recorded and the relay starts
302    /// again, with a growing wait; a run that returns ends it.
303    #[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                // The first two runs crash the way a refused thread spawn does.
315                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    /// The foreground relay says why it waits once, not on every tick.
347    #[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}