Skip to main content

lean_ctx_cloud/bus/
handoff.rs

1// SPDX-License-Identifier: Apache-2.0
2//! The handoffs this machine offered through Cloud.
3//!
4//! A handoff to another machine's worker is a typed bus message
5//! (`handoff`, [`super::messages_v2`]); the addressee answers it with an
6//! `answer` that accepts or declines. Cloud keeps the thread and its state.
7//! This file only remembers which local agent offered which handoff, so a
8//! maintainer's veto of it (a control naming the stored message id,
9//! [`super::veto`]) reaches the agent that offered it.
10//!
11//! State in `<data>/cloud/bus/handoffs.json`, keyed by the `client_msg_id`
12//! of the handoff message.
13
14use std::collections::BTreeMap;
15use std::path::Path;
16
17use serde::{Deserialize, Serialize};
18
19use crate::CloudError;
20use crate::state::{load_or_quarantine, lock_state, write_private};
21
22const HANDOFFS_FILE: &str = "handoffs.json";
23/// An offer is remembered this long after it was made (RB8 M14).
24const KEPT: lean_ctx_time::Duration = lean_ctx_time::Duration::days(7);
25/// Offers remembered at most (the newest stay).
26const MAX_OFFERS: usize = 1000;
27
28#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
29#[serde(rename_all = "snake_case", tag = "state")]
30pub enum OfferState {
31    Offered,
32    /// A maintainer vetoed it; the offering agent was told once.
33    Vetoed {
34        reason: String,
35    },
36}
37
38/// A handoff a local agent offered.
39#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
40pub struct Offer {
41    /// The local agent that offered it.
42    pub from: String,
43    /// The worker it was offered to (`wkr_…`).
44    pub to: String,
45    /// The message id Cloud stored it under (`msg_…`), once known.
46    #[serde(default, skip_serializing_if = "Option::is_none")]
47    pub msg_id: Option<String>,
48    pub offered_at: String,
49    #[serde(flatten)]
50    pub state: OfferState,
51}
52
53/// `handoffs.json`: `client_msg_id` → offer.
54#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
55pub struct Handoffs {
56    #[serde(default)]
57    pub offers: BTreeMap<String, Offer>,
58}
59
60impl Handoffs {
61    pub fn load(data_dir: &Path) -> Self {
62        std::fs::read(data_dir.join("bus").join(HANDOFFS_FILE))
63            .ok()
64            .and_then(|bytes| serde_json::from_slice(&bytes).ok())
65            .unwrap_or_default()
66    }
67
68    fn save(&self, data_dir: &Path) -> Result<(), CloudError> {
69        let bytes = serde_json::to_vec(self).map_err(|e| CloudError::Local(e.to_string()))?;
70        write_private(&data_dir.join("bus"), HANDOFFS_FILE, &bytes)
71    }
72
73    /// Load, change and save under `handoffs.lock` (RB8 M11), shared by the
74    /// relay and the tool calls; never held across a request. A damaged or
75    /// unknown file is moved aside first and the state starts empty, so
76    /// the damaged copy is never overwritten (M12); an unreadable one is an
77    /// error. Old entries are pruned on every change (M14).
78    pub fn mutate<T>(
79        data_dir: &Path,
80        change: impl FnOnce(&mut Self) -> T,
81    ) -> Result<T, CloudError> {
82        let dir = data_dir.join("bus");
83        let _lock = lock_state(&dir, HANDOFFS_FILE)?;
84        let path = dir.join(HANDOFFS_FILE);
85        let mut state = match load_or_quarantine::<Self>(&path, |_| true) {
86            Ok(state) => state.unwrap_or_default(),
87            Err(error) if !path.exists() => {
88                tracing::warn!("cloud bus handoffs: {error}");
89                Self::default()
90            }
91            Err(error) => return Err(error),
92        };
93        let before = state.clone();
94        let out = change(&mut state);
95        state.prune(lean_ctx_time::UtcDateTime::now());
96        if state != before {
97            state.save(data_dir)?;
98        }
99        Ok(out)
100    }
101
102    fn prune(&mut self, now: lean_ctx_time::UtcDateTime) {
103        let cutoff = stamp(now - KEPT);
104        self.offers
105            .retain(|_, offer| offer.offered_at.as_str() > cutoff.as_str());
106        let excess = self.offers.len().saturating_sub(MAX_OFFERS);
107        if excess > 0 {
108            let mut by_age: Vec<_> = self
109                .offers
110                .iter()
111                .map(|(id, offer)| (offer.offered_at.clone(), id.clone()))
112                .collect();
113            by_age.sort();
114            for (_, id) in by_age.into_iter().take(excess) {
115                self.offers.remove(&id);
116            }
117        }
118    }
119
120    /// A veto of the handoff `id` (its message id, or its `client_msg_id`):
121    /// the open offers it names become vetoed; the agents that made them.
122    pub fn veto(&mut self, id: &str, reason: &str) -> Vec<String> {
123        let mut from = Vec::new();
124        for (client_msg_id, offer) in &mut self.offers {
125            let named = client_msg_id == id || offer.msg_id.as_deref() == Some(id);
126            if named && offer.state == OfferState::Offered {
127                offer.state = OfferState::Vetoed {
128                    reason: reason.to_string(),
129                };
130                from.push(offer.from.clone());
131            }
132        }
133        from
134    }
135}
136
137fn stamp(at: lean_ctx_time::UtcDateTime) -> String {
138    at.to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true)
139}
140
141/// Remember that `from` offered the handoff message `client_msg_id` to the
142/// worker `to`.
143pub fn offered(
144    data_dir: &Path,
145    client_msg_id: &str,
146    from: &str,
147    to: &str,
148) -> Result<(), CloudError> {
149    let offer = Offer {
150        from: from.into(),
151        to: to.into(),
152        msg_id: None,
153        offered_at: stamp(lean_ctx_time::UtcDateTime::now()),
154        state: OfferState::Offered,
155    };
156    Handoffs::mutate(data_dir, |handoffs| {
157        handoffs.offers.insert(client_msg_id.to_string(), offer);
158    })
159}
160
161/// Cloud stored the message `client_msg_id` as `msg_id`: when it is a
162/// handoff offered here, remember that id (a veto names it). `true` when
163/// it was one.
164#[cfg_attr(not(feature = "http-server"), allow(dead_code))]
165pub(crate) fn stored(
166    data_dir: &Path,
167    client_msg_id: &str,
168    msg_id: &str,
169) -> Result<bool, CloudError> {
170    // Most stored messages are no handoff: read without the lock first.
171    if Handoffs::load(data_dir)
172        .offers
173        .get(client_msg_id)
174        .is_none_or(|offer| offer.msg_id.is_some())
175    {
176        return Ok(false);
177    }
178    Handoffs::mutate(data_dir, |handoffs| {
179        handoffs
180            .offers
181            .get_mut(client_msg_id)
182            .map(|offer| offer.msg_id = Some(msg_id.to_string()))
183            .is_some()
184    })
185}
186
187#[cfg(test)]
188mod tests {
189    use super::*;
190
191    #[test]
192    fn an_offer_learns_its_message_id_and_a_veto_names_either_id() {
193        let dir = tempfile::tempdir().unwrap();
194        offered(dir.path(), "01M5NKA2Z8B000000000000004", "alpha", "wkr_b").unwrap();
195        assert!(
196            !stored(dir.path(), "01OTHER", "msg_1").unwrap(),
197            "no handoff"
198        );
199        assert!(
200            stored(
201                dir.path(),
202                "01M5NKA2Z8B000000000000004",
203                "msg_00000000000000a4"
204            )
205            .unwrap()
206        );
207        assert!(
208            !stored(dir.path(), "01M5NKA2Z8B000000000000004", "msg_x").unwrap(),
209            "once"
210        );
211        let vetoed =
212            Handoffs::mutate(dir.path(), |h| h.veto("msg_00000000000000a4", "veto")).unwrap();
213        assert_eq!(vetoed, ["alpha"]);
214        let again =
215            Handoffs::mutate(dir.path(), |h| h.veto("msg_00000000000000a4", "veto")).unwrap();
216        assert!(again.is_empty(), "a vetoed offer is vetoed once");
217        offered(dir.path(), "01CLIENT", "beta", "wkr_c").unwrap();
218        let by_client_id = Handoffs::mutate(dir.path(), |h| h.veto("01CLIENT", "veto")).unwrap();
219        assert_eq!(by_client_id, ["beta"]);
220    }
221
222    #[test]
223    fn a_damaged_file_is_kept_aside_and_never_overwritten() {
224        let dir = tempfile::tempdir().unwrap();
225        let bus = dir.path().join("bus");
226        std::fs::create_dir_all(&bus).unwrap();
227        std::fs::write(bus.join(HANDOFFS_FILE), b"{ not json").unwrap();
228        assert!(Handoffs::load(dir.path()).offers.is_empty());
229        assert_eq!(
230            std::fs::read(bus.join(HANDOFFS_FILE)).unwrap(),
231            b"{ not json",
232            "a reader changes nothing"
233        );
234        offered(dir.path(), "01A", "alpha", "wkr_b").unwrap();
235        assert_eq!(
236            std::fs::read(bus.join("handoffs.json.damaged-1")).unwrap(),
237            b"{ not json"
238        );
239        assert_eq!(Handoffs::load(dir.path()).offers.len(), 1);
240    }
241
242    #[test]
243    fn old_offers_age_out_and_the_file_is_capped() {
244        let at = lean_ctx_time::UtcDateTime::now();
245        let mk = |days_ago: i64, minutes: i64| Offer {
246            from: "alpha".into(),
247            to: "wkr_b".into(),
248            msg_id: None,
249            offered_at: stamp(
250                at - lean_ctx_time::Duration::days(days_ago)
251                    - lean_ctx_time::Duration::minutes(minutes),
252            ),
253            state: OfferState::Offered,
254        };
255        let mut handoffs = Handoffs::default();
256        handoffs.offers.insert("old".into(), mk(8, 0));
257        for n in 0..(MAX_OFFERS + 2) {
258            let minutes = i64::try_from(MAX_OFFERS + 2 - n).unwrap();
259            handoffs.offers.insert(format!("o_{n:04}"), mk(0, minutes));
260        }
261        handoffs.prune(at);
262        assert!(!handoffs.offers.contains_key("old"));
263        assert_eq!(handoffs.offers.len(), MAX_OFFERS);
264        assert!(!handoffs.offers.contains_key("o_0001"), "oldest went");
265        assert!(handoffs.offers.contains_key("o_0002"));
266    }
267}