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::{CloudBusMode, 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 != CloudBusMode::Off && config.enabled != Some(false)).then_some(config)
52}
53
54/// How long the daemon's relay waits before it asks for the relay lock
55/// again while another relay (a foreground `cloud bus relay --for`) holds it.
56const LOCK_RETRY: std::time::Duration = std::time::Duration::from_secs(5);
57/// The first restart after the daemon's relay crashed, doubled per crash in
58/// a row, at most [`RESTART_MAX`]. A run that lasted [`RESTART_RESET`]
59/// forgives the crashes before it.
60const 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
64/// Where a [`Report`] line goes.
65type Sink = std::sync::Arc<dyn Fn(&str) + Send + Sync>;
66
67/// Where a relay says what it does. The foreground `cloud bus relay`
68/// prints it; the daemon's relay is quiet (its errors reach `cloud status`).
69/// A line equal to the one said last is not repeated, so a relay that
70/// waits says why once, not on every tick.
71#[derive(Clone, Default)]
72pub struct Report {
73    sink: Option<Sink>,
74    last: std::sync::Arc<std::sync::Mutex<String>>,
75}
76
77impl Report {
78    /// A relay that says nothing (the daemon's).
79    pub fn quiet() -> Self {
80        Self::default()
81    }
82
83    /// A relay that hands every line to `sink`.
84    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
105/// The text of a panic payload.
106fn 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
114/// The wait before restart number `crashes` (1 = the first) of a crashed
115/// relay.
116fn 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
122/// Run the daemon's relay until it stops for good (`run_once` returns: a
123/// revocation, a lapsed lease; the relay records those itself). A panic in
124/// it, e.g. tokio's `spawn_blocking` when the OS refuses a thread (#252:
125/// "OS can't spawn worker thread"), no longer ends the relay for the
126/// daemon's lifetime: it is recorded for `cloud status` and the relay starts
127/// again after [`restart_delay`]. The relay lock stays held meanwhile, so
128/// no second relay starts in between.
129fn 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
158/// Start the bus relay thread when this machine is connected, the bus is
159/// not off and Cloud is not disabled.
160pub fn spawn(config: CloudConfig) -> Option<std::thread::JoinHandle<()>> {
161    // The relay speaks WebSocket, which only an http-server build carries.
162    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            // A foreground `cloud bus relay --for` may hold the lock right
176            // now (#252: one that ran while the daemon started left the
177            // daemon without a relay for its whole life). Wait for it.
178            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            // Engine start: the instance card (E44, SPEC-ENGINE ยง3.6). It
188            // runs on this thread before the socket loop and never stops it.
189            if let Err(error) = instance_card(&store, &config) {
190                tracing::info!("cloud instance card: {error}");
191            }
192            // The relay's process outlives CLI calls: it keeps the claims
193            // `lean-ctx cloud tasks claim` made for agents still at work, and
194            // gives back the claims nobody works on any more (an ended
195            // session's, an expired one), so others can take the task.
196            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                    // A runtime the OS cannot build (no threads left) is a
210                    // crash like any other: the supervisor tries again.
211                    let runtime = tokio::runtime::Builder::new_current_thread()
212                        .enable_all()
213                        .build()
214                        .unwrap_or_else(|e| panic!("bus runtime: {e}"));
215                    // A fatal stop is logged and recorded by the relay itself.
216                    #[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
232/// Exchange the instance card (E44); its answer records which protocol
233/// the enrolled Cloud speaks, which the relay needs before it connects.
234fn 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
241/// Run the relay in the foreground for `duration` (`lean-ctx cloud bus
242/// relay --for <seconds>`), e.g. to watch it or in tests. When another
243/// relay (the daemon's) already runs, nothing runs here and `Ok(false)`
244/// says so: the caller then asks that relay to announce now. `report` hears
245/// what the relay sends (each hello's workers, roles and buses) and why it
246/// sends nothing, when it does not.
247pub 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    // The caller asks the running relay to announce
254    // (`presence::announce_and_wait`) and prints its answer.
255    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    // A relay that stopped for good (a revocation, a lapsed lease) says
263    // why, in the words every other CLI path uses.
264    #[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    /// #252: on pounce the daemon's relay thread panicked once (tokio's
283    /// `spawn_blocking` could not get a thread) and was gone for good, so
284    /// no worker of that machine was on the bus any more and role-gated
285    /// claims were refused. A crash is now recorded and the relay starts
286    /// again, with a growing wait; a run that returns ends it.
287    #[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                // The first two runs crash the way a refused thread spawn does.
299                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    /// The foreground relay says why it waits once, not on every tick.
331    #[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}