Skip to main content

lean_ctx_cloud/
resolution.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Local vault resolutions that no longer fit their checkout (dogfood
3//! 5.11.: one repository split across two vaults without a warning).
4//!
5//! `projects.json` ([`VaultMap`]) remembers which vault Cloud resolved for a
6//! checkout. That memory goes stale when
7//! - the link file now names another vault (`cloud link` after `cloud
8//!   connect`, or a pulled commit that changed `.lean-ctx-cloud.json`), or
9//! - the checkout's identity changed: a `.lean-ctx-id` that an earlier
10//!   `cloud link` wrote (32 random hex characters) no longer outranks the git
11//!   origin ([`crate::vault::project_identity`]), so every checkout of one
12//!   origin is one repository again.
13//!
14//! A stale record is never used: it is dropped, and the next resolve maps
15//! the checkout again (with the person's first-share consent where the gate
16//! holds). When Cloud still answers with another vault than the link file
17//! names, the resolve is refused ([`refuse_unlinked`]): nothing syncs into
18//! a vault the link file does not name.
19
20use std::path::Path;
21
22use lean_ctx::core::pathutil::same_project;
23use lean_ctx_protocol::cloud::status::CloudStatusVaultMismatchV1;
24use lean_ctx_protocol::cloud::vault::{VaultRefV1, stable_identity};
25
26use super::CloudError;
27use super::link::read_link;
28use super::vault::{VaultMap, VaultRecord, project_identity};
29
30/// Why a recorded resolution does not fit the checkout any more.
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub enum StaleReason {
33    /// The link file names `linked` (`ns/name`).
34    Link { linked: String },
35    /// The checkout's identity is not the one the record was resolved for.
36    Identity,
37}
38
39/// A resolution of `root` to `resolved` (`ns/name`) that does not hold.
40#[derive(Debug, Clone, PartialEq, Eq)]
41pub struct Stale {
42    pub root: String,
43    pub resolved: String,
44    pub reason: StaleReason,
45}
46
47impl Stale {
48    /// The linked vault, when the link file is the reason.
49    pub fn linked(&self) -> Option<&str> {
50        match &self.reason {
51            StaleReason::Link { linked } => Some(linked),
52            StaleReason::Identity => None,
53        }
54    }
55
56    /// `vault_mismatch` of `cloud status --json`.
57    pub fn wire(&self) -> CloudStatusVaultMismatchV1 {
58        CloudStatusVaultMismatchV1 {
59            project_root: self.root.clone(),
60            resolved: self.resolved.clone(),
61            linked: self.linked().map(str::to_string),
62            reason: match self.reason {
63                StaleReason::Link { .. } => "link",
64                StaleReason::Identity => "identity",
65            }
66            .into(),
67        }
68    }
69
70    /// One line for people (status, connect, link, sync).
71    pub fn describe(&self) -> String {
72        match &self.reason {
73            StaleReason::Link { linked } => format!(
74                "this machine resolved {} to the vault {}, but its link file names {linked}",
75                self.root, self.resolved
76            ),
77            StaleReason::Identity => format!(
78                "this machine resolved {} to the vault {} under an identity the checkout no longer has (a `.lean-ctx-id` written by an earlier `cloud link`; the git origin counts now)",
79                self.root, self.resolved
80            ),
81        }
82    }
83}
84
85fn address(record: &VaultRecord) -> String {
86    format!("{}/{}", record.ns, record.name)
87}
88
89/// The record `root` uses (its own, or its main checkout's), its key and
90/// the recorded root it was found by.
91fn recorded<'a>(map: &'a VaultMap, root: &Path) -> Option<(&'a str, &'a VaultRecord, String)> {
92    let find = |root: &str| {
93        map.vaults.iter().find_map(|(key, record)| {
94            record
95                .roots
96                .iter()
97                .find(|known| same_project(known, root))
98                .map(|known| (key.as_str(), record, known.clone()))
99        })
100    };
101    let root_str = root.to_string_lossy();
102    find(&root_str).or_else(|| {
103        let main = super::link::main_worktree_root(root)?;
104        find(&main.to_string_lossy())
105    })
106}
107
108/// Whether the recorded resolution of `root` is stale. Local files only;
109/// changes nothing.
110pub fn stale_for_root(map: &VaultMap, root: &Path) -> Option<Stale> {
111    let (key, record, _) = recorded(map, root)?;
112    let resolved = address(record);
113    let stale = |reason| Stale {
114        root: root.to_string_lossy().into_owned(),
115        resolved: resolved.clone(),
116        reason,
117    };
118    // A damaged link file is refused where the link is used; here it says
119    // nothing about the record.
120    if let Ok(Some(link)) = read_link(root)
121        && (link.vault.ns != record.ns || link.vault.name != record.name)
122    {
123        return Some(stale(StaleReason::Link {
124            linked: format!("{}/{}", link.vault.ns, link.vault.name),
125        }));
126    }
127    let current = project_identity(root).map(|identity| stable_identity(&identity));
128    if current.is_some_and(|current| current != key) {
129        return Some(stale(StaleReason::Identity));
130    }
131    None
132}
133
134/// Drop the stale resolution of `root` from `map`, if any. A link file that
135/// names another vault drops the whole record: one identity has one vault,
136/// so every checkout of it resolves again. An identity change drops only
137/// this checkout from the record of its old identity.
138pub fn forget_stale(map: &mut VaultMap, root: &Path) -> Option<Stale> {
139    let stale = stale_for_root(map, root)?;
140    let (key, _, known) = recorded(map, root)?;
141    let key = key.to_string();
142    match stale.reason {
143        StaleReason::Link { .. } => {
144            map.vaults.remove(&key);
145        }
146        StaleReason::Identity => {
147            if let Some(record) = map.vaults.get_mut(&key) {
148                record.roots.retain(|r| r != &known);
149                if record.roots.is_empty() {
150                    map.vaults.remove(&key);
151                }
152            }
153        }
154    }
155    Some(stale)
156}
157
158/// [`forget_stale`] for every checkout `map` knows.
159pub fn forget_all_stale(map: &mut VaultMap) -> Vec<Stale> {
160    let roots: Vec<String> = map
161        .vaults
162        .values()
163        .flat_map(|record| record.roots.iter().cloned())
164        .collect();
165    roots
166        .iter()
167        .filter_map(|root| forget_stale(map, Path::new(root)))
168        .collect()
169}
170
171/// The vault map at `data_dir` without stale resolutions; the file is
172/// rewritten when one was dropped. What every pass that sends (sync, task
173/// proposals) reads, so none sends into a vault the checkout left.
174pub fn load_current(data_dir: &Path) -> Result<(VaultMap, Vec<Stale>), CloudError> {
175    let mut map = VaultMap::load(data_dir);
176    let dropped = forget_all_stale(&mut map);
177    if !dropped.is_empty() {
178        map.save(data_dir)
179            .map_err(|e| CloudError::Local(format!("projects.json: {e}")))?;
180        for stale in &dropped {
181            tracing::info!(
182                "cloud: dropped a stale vault resolution: {}",
183                stale.describe()
184            );
185        }
186    }
187    Ok((map, dropped))
188}
189
190/// Drop the stale resolution of `root` in the map at `data_dir`.
191pub fn forget_stale_at(data_dir: &Path, root: &Path) -> Result<Option<Stale>, CloudError> {
192    let mut map = VaultMap::load(data_dir);
193    let Some(stale) = forget_stale(&mut map, root) else {
194        return Ok(None);
195    };
196    map.save(data_dir)
197        .map_err(|e| CloudError::Local(format!("projects.json: {e}")))?;
198    Ok(Some(stale))
199}
200
201/// The vault the checkout at `root` sends to, from the map at `data_dir`:
202/// `None` when it has none, refused (`vault_mismatch`) when its record is
203/// stale. The one lookup of every caller that writes to a vault (tasks, bus
204/// posts and leases, docs, the live bus), so a record the link file or the
205/// identity no longer backs is never written to, also before link, connect
206/// or sync dropped it (a `git pull` that changed the link file).
207pub fn vault_for_root(data_dir: &Path, root: &Path) -> Result<Option<VaultRecord>, CloudError> {
208    vault_in(&VaultMap::load(data_dir), root).map(Option::<&VaultRecord>::cloned)
209}
210
211/// The map at `data_dir` without its stale records, the file unchanged:
212/// what the live bus subscribes and announces from, so it never joins a
213/// vault a checkout left.
214pub fn current_view(data_dir: &Path) -> VaultMap {
215    let mut map = VaultMap::load(data_dir);
216    forget_all_stale(&mut map);
217    map
218}
219
220/// [`vault_for_root`] in a loaded `map`.
221pub fn vault_in<'a>(map: &'a VaultMap, root: &Path) -> Result<Option<&'a VaultRecord>, CloudError> {
222    if let Some(stale) = stale_for_root(map, root) {
223        return Err(refuse_stale(&stale));
224    }
225    Ok(map.for_root(&root.to_string_lossy()))
226}
227
228/// Refused (`vault_mismatch`) when `record`, which a caller is about to
229/// sync for the checkout at `root`, is not what the checkout resolves to
230/// now: its link file names another vault, or the map's record of `root`
231/// at `data_dir` is stale. The guard of every vault sync (background pass
232/// and `cloud sync`), whatever map snapshot the caller planned from.
233pub fn refuse_stale_record(
234    data_dir: &Path,
235    record: &VaultRecord,
236    root: &Path,
237) -> Result<(), CloudError> {
238    if let Ok(Some(link)) = read_link(root)
239        && (link.vault.ns != record.ns || link.vault.name != record.name)
240    {
241        return Err(refuse_stale(&Stale {
242            root: root.to_string_lossy().into_owned(),
243            resolved: address(record),
244            reason: StaleReason::Link {
245                linked: format!("{}/{}", link.vault.ns, link.vault.name),
246            },
247        }));
248    }
249    match stale_for_root(&VaultMap::load(data_dir), root) {
250        Some(stale) => Err(refuse_stale(&stale)),
251        None => Ok(()),
252    }
253}
254
255/// The refusal for a write into the stale resolution `stale`.
256pub fn refuse_stale(stale: &Stale) -> CloudError {
257    CloudError::Refused(format!(
258        "vault_mismatch: {}. Nothing is sent to {} any more: run `lean-ctx cloud connect` here to resolve the project again",
259        stale.describe(),
260        stale.resolved
261    ))
262}
263
264/// Cloud answered `answered` for the checkout at `root`: refused when its
265/// link file names another vault. Cloud keeps the first binding of an
266/// identity (another Instance of the workspace may have made it), so a
267/// link to another vault cannot move it; syncing anyway would split the
268/// repository silently.
269pub fn refuse_unlinked(root: &Path, answered: &VaultRefV1) -> Result<(), CloudError> {
270    let Some(link) = read_link(root)? else {
271        return Ok(());
272    };
273    if link.vault == *answered {
274        return Ok(());
275    }
276    Err(CloudError::Refused(format!(
277        "vault_mismatch: LeanCTX Cloud keeps this repository in the vault {}/{} (bound there first, possibly by another Instance of the workspace), but {} names {}/{}. Nothing syncs for it until both agree: run `lean-ctx cloud link {}/{}` here, or move the repository to {}/{} in LeanCTX Cloud and run `lean-ctx cloud connect` again",
278        answered.ns,
279        answered.name,
280        super::link::LINK_FILE,
281        link.vault.ns,
282        link.vault.name,
283        answered.ns,
284        answered.name,
285        link.vault.ns,
286        link.vault.name,
287    )))
288}
289
290#[cfg(test)]
291mod tests {
292    use super::*;
293
294    fn checkout(base: &Path, name: &str, origin: Option<&str>) -> std::path::PathBuf {
295        let root = base.join(name);
296        std::fs::create_dir_all(root.join(".git")).unwrap();
297        let config = origin.map_or(String::new(), |url| {
298            format!("[remote \"origin\"]\n\turl = {url}\n")
299        });
300        std::fs::write(root.join(".git/config"), config).unwrap();
301        root
302    }
303
304    fn record(map: &mut VaultMap, key: &str, vault: &str, roots: &[&Path]) {
305        let (ns, name) = vault.split_once('/').unwrap();
306        map.vaults.insert(
307            key.into(),
308            VaultRecord {
309                vault_id: format!("id-{name}"),
310                ns: ns.into(),
311                name: name.into(),
312                sealed: false,
313                roots: roots
314                    .iter()
315                    .map(|r| r.to_string_lossy().into_owned())
316                    .collect(),
317            },
318        );
319    }
320
321    fn stable(root: &Path) -> String {
322        stable_identity(&project_identity(root).unwrap())
323    }
324
325    /// The guard of `place::sync_vault`: a record planned from an older map
326    /// is refused once the link file names another vault, also when the map
327    /// on disk no longer has it.
328    #[test]
329    fn a_sync_of_a_record_the_link_file_left_is_refused() {
330        let base = tempfile::tempdir().unwrap();
331        let data = base.path().join("data");
332        std::fs::create_dir_all(&data).unwrap();
333        let a = checkout(
334            base.path(),
335            "a",
336            Some("git@github.com:yves/leanctx-cloud.git"),
337        );
338        let mut map = VaultMap::default();
339        record(&mut map, &stable(&a), "yves/cloud", &[&a]);
340        map.save(&data).unwrap();
341        let planned = map.vaults.values().next().unwrap().clone();
342        crate::link::link(&a, "yves/cloud").unwrap();
343        assert!(refuse_stale_record(&data, &planned, &a).is_ok());
344
345        crate::link::link(&a, "yves/leanctx-cloud").unwrap();
346        let refused = refuse_stale_record(&data, &planned, &a).unwrap_err();
347        assert!(refused.to_string().contains("vault_mismatch"), "{refused}");
348        VaultMap::default().save(&data).unwrap();
349        assert!(refuse_stale_record(&data, &planned, &a).is_err());
350    }
351
352    #[test]
353    fn a_link_that_names_another_vault_drops_the_whole_record() {
354        let base = tempfile::tempdir().unwrap();
355        let a = checkout(
356            base.path(),
357            "a",
358            Some("git@github.com:yves/leanctx-cloud.git"),
359        );
360        let b = checkout(
361            base.path(),
362            "b",
363            Some("git@github.com:yves/leanctx-cloud.git"),
364        );
365        let mut map = VaultMap::default();
366        record(&mut map, &stable(&a), "yves/cloud", &[&a, &b]);
367        assert_eq!(
368            stale_for_root(&map, &a),
369            None,
370            "no link file: nothing to compare"
371        );
372
373        super::super::link::link(&a, "yves/leanctx-cloud").unwrap();
374        let stale = stale_for_root(&map, &a).expect("stale");
375        assert_eq!(stale.resolved, "yves/cloud");
376        assert_eq!(stale.linked(), Some("yves/leanctx-cloud"));
377        assert!(
378            stale
379                .describe()
380                .contains("link file names yves/leanctx-cloud")
381        );
382        assert_eq!(forget_stale(&mut map, &a), Some(stale));
383        assert!(map.vaults.is_empty(), "b is the same repository");
384        assert!(map.for_root(&b.to_string_lossy()).is_none());
385    }
386
387    #[test]
388    fn an_identity_change_drops_only_that_checkout() {
389        let base = tempfile::tempdir().unwrap();
390        let a = checkout(base.path(), "a", Some("https://github.com/acme/pay.git"));
391        let mut map = VaultMap::default();
392        record(&mut map, "old-random-identity", "acme/pay", &[&a]);
393        let other = base.path().join("elsewhere");
394        record(&mut map, &stable(&a), "acme/pay", &[&other]);
395        let stale = forget_stale(&mut map, &a).expect("stale");
396        assert_eq!(stale.reason, StaleReason::Identity);
397        assert!(!map.vaults.contains_key("old-random-identity"));
398        assert!(map.vaults.contains_key(&stable(&a)));
399        assert_eq!(forget_stale(&mut map, &a), None);
400    }
401
402    #[test]
403    fn load_current_rewrites_the_map_once() {
404        let base = tempfile::tempdir().unwrap();
405        let data = base.path().join("data");
406        std::fs::create_dir_all(&data).unwrap();
407        let a = checkout(base.path(), "a", Some("https://github.com/acme/pay.git"));
408        let mut map = VaultMap::default();
409        record(&mut map, &stable(&a), "acme/old", &[&a]);
410        map.save(&data).unwrap();
411        super::super::link::link(&a, "acme/pay").unwrap();
412        let (map, dropped) = load_current(&data).unwrap();
413        assert_eq!(dropped.len(), 1);
414        assert!(map.vaults.is_empty());
415        assert!(VaultMap::load(&data).vaults.is_empty(), "saved");
416        assert!(load_current(&data).unwrap().1.is_empty());
417    }
418
419    #[test]
420    fn cloud_answering_another_vault_than_the_link_is_refused() {
421        let base = tempfile::tempdir().unwrap();
422        let a = checkout(base.path(), "a", Some("https://github.com/acme/pay.git"));
423        let answered = VaultRefV1 {
424            ns: "acme".into(),
425            name: "old".into(),
426        };
427        assert!(
428            refuse_unlinked(&a, &answered).is_ok(),
429            "no link: LeanCTX Cloud decides"
430        );
431        super::super::link::link(&a, "acme/pay").unwrap();
432        let refused = refuse_unlinked(&a, &answered).unwrap_err().to_string();
433        assert!(refused.contains("vault_mismatch"), "{refused}");
434        assert!(
435            refused.contains("acme/old") && refused.contains("acme/pay"),
436            "{refused}"
437        );
438        let linked = VaultRefV1 {
439            ns: "acme".into(),
440            name: "pay".into(),
441        };
442        assert!(refuse_unlinked(&a, &linked).is_ok());
443    }
444}