Skip to main content

bynk_lsp/
contract_diff_request.rs

1//! #2467: `bynk/contractDiff` — the contract-diff custom LSP request.
2//!
3//! Project-scoped, like `bynk/architectureModel`: the params carry a
4//! `textDocument` only to resolve which project's committed round to read.
5//! Two lists come back:
6//!
7//! - **`changes`**: every event and agent class whose shape differs from
8//!   `bynk.schema.lock`, classified `compatible` or `breaking`. The
9//!   classification is `bynk_check::schema_registry::diff_against_lock`,
10//!   which reports the verdicts of the reconciliation `bynk check` runs; this
11//!   module never decides what "breaking" means.
12//! - **`services`**: each context's `on call` contract hash that differs from
13//!   what `bynk.deploy.lock` records as live, per environment, as
14//!   `changed`/`added`/`removed`. A hash says *whether* a contract moved, not
15//!   whether the move is breaking (ADR 0491 compares hashes too), so a
16//!   `changed` row also carries `compat` (#2485) when the ledger recorded the
17//!   live contract's structure: `bynk_check::contract_compat::check_call` of
18//!   the live contract (what its callers speak) against the one this source
19//!   provides. No structure on record, no verdict.
20//!
21//! The ledger is read here, above the driver boundary, like the schema lock
22//! (`schema_lock.rs`); read-only, on request, nothing cached.
23
24use std::collections::{BTreeMap, HashMap};
25use std::path::{Path, PathBuf};
26
27#[cfg(test)]
28use bynk_check::analysis::ProvidedContracts;
29use bynk_check::analysis::{ContractDiff, LockState};
30use bynk_check::contract_compat::{ServiceShape, check_call};
31use bynk_check::index::{ProjectIndex, SymbolKey, SymbolKind};
32use bynk_check::schema_registry::{BoundaryChange, ChangeClass, ChangeKind};
33use serde::{Deserialize, Serialize};
34
35pub use crate::architecture_request::WireLoc as CdLoc;
36
37/// The deploy ledger's file name, at the project root.
38pub(crate) const LEDGER_FILE: &str = "bynk.deploy.lock";
39
40/// The `bynk/contractDiff` request payload.
41#[derive(Debug, Clone, Serialize, Deserialize)]
42#[serde(rename_all = "camelCase")]
43pub struct ContractDiffParams {
44    pub text_document: tower_lsp::lsp_types::TextDocumentIdentifier,
45}
46
47/// What the ledger read gave: the diff against it is only as good as this.
48#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
49#[serde(rename_all = "camelCase")]
50pub enum LedgerState {
51    /// No `bynk.deploy.lock`: nothing has been deployed from this checkout.
52    Absent,
53    /// Present but not parseable here; the services list is empty.
54    Unreadable,
55    Read,
56}
57
58/// [`LockState`] on the wire.
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
60#[serde(rename_all = "camelCase")]
61pub enum LockWire {
62    Absent,
63    Unreadable,
64    Read,
65}
66
67#[derive(Debug, Clone, Serialize)]
68#[serde(rename_all = "camelCase")]
69pub struct CdChange {
70    /// `event` or `agent`.
71    pub kind: &'static str,
72    pub unit: String,
73    pub name: String,
74    /// `compatible` or `breaking`.
75    pub class: &'static str,
76    pub locked_version: i64,
77    pub detail: String,
78    pub loc: Option<CdLoc>,
79}
80
81#[derive(Debug, Clone, Serialize)]
82#[serde(rename_all = "camelCase")]
83pub struct CdService {
84    pub environment: String,
85    /// The providing context, qualified.
86    pub context: String,
87    pub service: String,
88    /// `changed`, `added` (not in the live record) or `removed` (in the live
89    /// record, no longer provided).
90    pub status: &'static str,
91    /// The hash the ledger records as live; `None` for `added`.
92    pub live: Option<String>,
93    /// The hash this source provides; `None` for `removed`.
94    pub current: Option<String>,
95    /// #2485: for a `changed` row, whether callers of the live contract still
96    /// work against this source's, when the ledger recorded the live
97    /// contract's structure. `None` otherwise.
98    pub compat: Option<CdCompat>,
99    pub loc: Option<CdLoc>,
100}
101
102/// A service change's compatibility verdict and the reasons behind it.
103#[derive(Debug, Clone, Serialize)]
104#[serde(rename_all = "camelCase")]
105pub struct CdCompat {
106    /// `compatible` or `breaking`.
107    pub verdict: &'static str,
108    /// One line per difference, breaking ones first.
109    pub reasons: Vec<String>,
110}
111
112#[derive(Debug, Clone, Serialize)]
113#[serde(rename_all = "camelCase")]
114pub struct CdModel {
115    /// Whether there is a readable `bynk.schema.lock` to diff events and
116    /// agents against.
117    pub lock: LockWire,
118    pub ledger: LedgerState,
119    pub changes: Vec<CdChange>,
120    pub services: Vec<CdService>,
121}
122
123/// The slice of `bynk.deploy.lock` this view reads. No `deny_unknown_fields`:
124/// the `bynk` CLI owns the format and adds to it.
125#[derive(Debug, Default, Deserialize)]
126struct Ledger {
127    #[serde(default)]
128    environments: BTreeMap<String, LedgerEnvironment>,
129}
130
131#[derive(Debug, Default, Deserialize)]
132struct LedgerEnvironment {
133    #[serde(default)]
134    workers: BTreeMap<String, LedgerWorker>,
135}
136
137#[derive(Debug, Default, Deserialize)]
138struct LedgerWorker {
139    /// `None`: a push that recorded no contracts. Silence is not a match
140    /// (ADR 0491), so such a Worker yields no row.
141    #[serde(default)]
142    contracts: Option<BTreeMap<String, String>>,
143    /// #2485: the structure behind each hash in `contracts`, by service.
144    #[serde(default)]
145    shapes: BTreeMap<String, String>,
146}
147
148/// Read `bynk.deploy.lock` for the project, read-only.
149pub(crate) fn read_ledger(project_root: &Path) -> (LedgerState, Option<String>) {
150    match std::fs::read_to_string(project_root.join(LEDGER_FILE)) {
151        Ok(text) => (LedgerState::Read, Some(text)),
152        Err(e) if e.kind() == std::io::ErrorKind::NotFound => (LedgerState::Absent, None),
153        Err(e) => {
154            tracing::warn!("could not read {LEDGER_FILE}: {e}");
155            (LedgerState::Unreadable, None)
156        }
157    }
158}
159
160/// Lower the round's [`ContractDiff`] (and the ledger text, if any) to the
161/// wire model.
162pub fn to_wire(
163    diff: &ContractDiff,
164    ledger: (LedgerState, Option<&str>),
165    project_root: &Path,
166    index: &ProjectIndex,
167    snapshots: &HashMap<PathBuf, String>,
168) -> CdModel {
169    let loc_of = |unit: &str, kind: SymbolKind, name: &str| {
170        let key = SymbolKey {
171            unit: unit.to_string(),
172            kind,
173            name: name.to_string(),
174        };
175        let def = index.symbols.get(&key)?.def.as_ref()?;
176        let text = snapshots.get(&def.path)?;
177        let uri = tower_lsp::lsp_types::Url::from_file_path(project_root.join(&def.path)).ok()?;
178        Some(CdLoc {
179            uri,
180            range: crate::position::span_to_range(text, def.span),
181        })
182    };
183
184    let changes = diff
185        .changes
186        .iter()
187        .map(|c: &BoundaryChange| CdChange {
188            kind: match c.kind {
189                ChangeKind::Event => "event",
190                ChangeKind::Agent => "agent",
191            },
192            unit: c.unit.clone(),
193            name: c.name.clone(),
194            class: match c.class {
195                ChangeClass::Compatible => "compatible",
196                ChangeClass::Breaking => "breaking",
197            },
198            locked_version: c.locked_version,
199            detail: c.detail.clone(),
200            loc: loc_of(
201                &c.unit,
202                match c.kind {
203                    ChangeKind::Event => SymbolKind::Type,
204                    ChangeKind::Agent => SymbolKind::Agent,
205                },
206                &c.name,
207            ),
208        })
209        .collect();
210
211    let (state, text) = ledger;
212    let mut state = state;
213    let mut services = Vec::new();
214    if let Some(text) = text {
215        match toml::from_str::<Ledger>(text) {
216            Ok(ledger) => services = service_rows(diff, &ledger, &loc_of),
217            Err(e) => {
218                tracing::warn!("could not parse {LEDGER_FILE}: {e}");
219                state = LedgerState::Unreadable;
220            }
221        }
222    }
223
224    CdModel {
225        lock: match diff.lock {
226            LockState::Absent => LockWire::Absent,
227            LockState::Unreadable => LockWire::Unreadable,
228            LockState::Read => LockWire::Read,
229        },
230        ledger: state,
231        changes,
232        services,
233    }
234}
235
236/// #2485: do callers of the contract the ledger recorded as live still work
237/// against the one this source provides? Both shapes must be on record and
238/// hash to the hashes beside them; otherwise there is no verdict.
239fn classify(
240    live: &LedgerWorker,
241    current: &bynk_check::analysis::ProvidedContracts,
242    service: &str,
243    live_hash: &str,
244    current_hash: &str,
245) -> Option<CdCompat> {
246    let old = ServiceShape::from_text_checked(live.shapes.get(service)?, live_hash)?;
247    let new = ServiceShape::from_text_checked(current.shapes.get(service)?, current_hash)?;
248    let c = check_call(&old, &new);
249    Some(CdCompat {
250        verdict: c.verdict.name(),
251        reasons: c.lines(),
252    })
253}
254
255/// Compare each context's provided hashes with each live Worker record. The
256/// Worker for a context is named as the deploy gate names it.
257fn service_rows(
258    diff: &ContractDiff,
259    ledger: &Ledger,
260    loc_of: &dyn Fn(&str, SymbolKind, &str) -> Option<CdLoc>,
261) -> Vec<CdService> {
262    let mut rows = Vec::new();
263    for (environment, env) in &ledger.environments {
264        for (context, current) in &diff.services {
265            let Some(worker) = env.workers.get(&current.worker) else {
266                continue;
267            };
268            let Some(live) = worker.contracts.as_ref() else {
269                continue;
270            };
271            for (service, hash) in &current.hashes {
272                let (status, recorded) = match live.get(service) {
273                    Some(l) if l == hash => continue,
274                    Some(l) => ("changed", Some(l.clone())),
275                    None => ("added", None),
276                };
277                let compat = recorded
278                    .as_deref()
279                    .and_then(|live_hash| classify(worker, current, service, live_hash, hash));
280                rows.push(CdService {
281                    environment: environment.clone(),
282                    context: context.clone(),
283                    service: service.clone(),
284                    status,
285                    live: recorded,
286                    current: Some(hash.clone()),
287                    compat,
288                    loc: loc_of(context, SymbolKind::Service, service),
289                });
290            }
291            for (service, l) in live {
292                if !current.hashes.contains_key(service) {
293                    rows.push(CdService {
294                        environment: environment.clone(),
295                        context: context.clone(),
296                        service: service.clone(),
297                        status: "removed",
298                        live: Some(l.clone()),
299                        current: None,
300                        compat: None,
301                        loc: None,
302                    });
303                }
304            }
305        }
306        // A live Worker no current context maps to: its context was deleted
307        // or renamed, so everything it provides is gone.
308        for (worker, record) in &env.workers {
309            if diff.services.values().any(|c| &c.worker == worker) {
310                continue;
311            }
312            for (service, l) in record.contracts.iter().flatten() {
313                rows.push(CdService {
314                    environment: environment.clone(),
315                    context: worker.clone(),
316                    service: service.clone(),
317                    status: "removed",
318                    live: Some(l.clone()),
319                    current: None,
320                    compat: None,
321                    loc: None,
322                });
323            }
324        }
325    }
326    rows
327}
328
329#[cfg(test)]
330mod tests {
331    use super::*;
332
333    fn diff_with(context: &str, services: &[(&str, &str)]) -> ContractDiff {
334        ContractDiff {
335            lock: LockState::Read,
336            changes: Vec::new(),
337            services: BTreeMap::from([(
338                context.to_string(),
339                ProvidedContracts {
340                    worker: context.replace('.', "-"),
341                    hashes: services
342                        .iter()
343                        .map(|(s, h)| (s.to_string(), h.to_string()))
344                        .collect(),
345                    shapes: BTreeMap::new(),
346                },
347            )]),
348        }
349    }
350
351    fn model(diff: &ContractDiff, ledger: &str) -> CdModel {
352        to_wire(
353            diff,
354            (LedgerState::Read, Some(ledger)),
355            Path::new("/p"),
356            &ProjectIndex::default(),
357            &HashMap::new(),
358        )
359    }
360
361    const LEDGER: &str = r#"
362version = 1
363[environments.default.workers.shop-billing]
364deployed = true
365[environments.default.workers.shop-billing.contracts]
366charge = "aaaa"
367refund = "bbbb"
368"#;
369
370    #[test]
371    fn an_unchanged_hash_yields_no_row() {
372        let m = model(
373            &diff_with("shop.billing", &[("charge", "aaaa"), ("refund", "bbbb")]),
374            LEDGER,
375        );
376        assert!(m.services.is_empty());
377        assert_eq!(m.ledger, LedgerState::Read);
378    }
379
380    #[test]
381    fn a_moved_hash_without_recorded_structure_is_changed_with_no_verdict() {
382        let m = model(
383            &diff_with("shop.billing", &[("charge", "cccc"), ("refund", "bbbb")]),
384            LEDGER,
385        );
386        assert_eq!(m.services.len(), 1);
387        let row = &m.services[0];
388        assert_eq!((row.status, row.service.as_str()), ("changed", "charge"));
389        assert_eq!(row.live.as_deref(), Some("aaaa"));
390        assert_eq!(row.current.as_deref(), Some("cccc"));
391        assert!(row.compat.is_none(), "hashes alone cannot be classified");
392    }
393
394    /// #2485: with the live structure on record, a `changed` row says whether
395    /// the change is compatible, and why.
396    #[test]
397    fn a_changed_service_with_recorded_structure_is_classified() {
398        use bynk_check::contract_compat::{Field, ServiceShape, Shape};
399        let shape = |extra: bool| {
400            let mut fields = vec![Field {
401                name: "ok".into(),
402                ty: Shape::Base("Bool".into()),
403                preds: Vec::new(),
404                defaulted: false,
405            }];
406            if extra {
407                fields.push(Field {
408                    name: "at".into(),
409                    ty: Shape::Base("Int".into()),
410                    preds: Vec::new(),
411                    defaulted: false,
412                });
413                fields.sort_by_key(|f| f.name.clone());
414            }
415            ServiceShape {
416                name: "charge".into(),
417                params: Vec::new(),
418                ret: Shape::Record {
419                    name: "Receipt".into(),
420                    fields,
421                },
422            }
423        };
424        let (old, new) = (shape(false), shape(true));
425        let ledger = format!(
426            "version = 1\n[environments.default.workers.shop-billing]\ndeployed = true\n\
427             [environments.default.workers.shop-billing.contracts]\ncharge = \"{}\"\n\
428             [environments.default.workers.shop-billing.shapes]\ncharge = '{}'\n",
429            old.hash(),
430            old.to_text()
431        );
432        let mut diff = diff_with("shop.billing", &[("charge", &new.hash())]);
433        let provided = diff.services.get_mut("shop.billing").unwrap();
434        provided.shapes.insert("charge".into(), new.to_text());
435        let m = model(&diff, &ledger);
436        let c = m.services[0].compat.as_ref().expect("classified");
437        assert_eq!(c.verdict, "compatible", "{c:?}");
438        assert!(c.reasons[0].contains("response.at"), "{c:?}");
439        // The reverse is a removal the old callers cannot read.
440        let mut diff = diff_with("shop.billing", &[("charge", &old.hash())]);
441        diff.services
442            .get_mut("shop.billing")
443            .unwrap()
444            .shapes
445            .insert("charge".into(), old.to_text());
446        let ledger = ledger
447            .replace(&old.hash(), &new.hash())
448            .replace(&old.to_text(), &new.to_text());
449        let m = model(&diff, &ledger);
450        let c = m.services[0].compat.as_ref().expect("classified");
451        assert_eq!(c.verdict, "breaking", "{c:?}");
452    }
453
454    #[test]
455    fn added_and_removed_services_are_reported() {
456        let m = model(
457            &diff_with("shop.billing", &[("charge", "aaaa"), ("void", "dddd")]),
458            LEDGER,
459        );
460        let by: Vec<_> = m
461            .services
462            .iter()
463            .map(|r| (r.status, r.service.as_str()))
464            .collect();
465        assert_eq!(by, vec![("added", "void"), ("removed", "refund")]);
466    }
467
468    #[test]
469    fn a_context_that_dropped_its_last_service_reports_it_removed() {
470        let m = model(&diff_with("shop.billing", &[]), LEDGER);
471        let by: Vec<_> = m
472            .services
473            .iter()
474            .map(|r| (r.status, r.service.as_str()))
475            .collect();
476        assert_eq!(by, vec![("removed", "charge"), ("removed", "refund")]);
477    }
478
479    #[test]
480    fn a_worker_with_no_current_context_reports_its_services_removed() {
481        // `shop.billing` was deleted or renamed: only `shop.orders` remains.
482        let m = model(&diff_with("shop.orders", &[("place", "eeee")]), LEDGER);
483        let by: Vec<_> = m
484            .services
485            .iter()
486            .map(|r| (r.status, r.context.as_str(), r.service.as_str()))
487            .collect();
488        assert_eq!(
489            by,
490            vec![
491                ("removed", "shop-billing", "charge"),
492                ("removed", "shop-billing", "refund")
493            ]
494        );
495    }
496
497    #[test]
498    fn a_context_with_no_live_record_yields_nothing() {
499        // `shop.orders` has no Worker in the ledger; `shop.billing` matches.
500        let mut diff = diff_with("shop.billing", &[("charge", "aaaa"), ("refund", "bbbb")]);
501        diff.services.insert(
502            "shop.orders".to_string(),
503            ProvidedContracts {
504                worker: "shop-orders".to_string(),
505                hashes: BTreeMap::from([("place".to_string(), "eeee".to_string())]),
506                shapes: BTreeMap::new(),
507            },
508        );
509        let m = model(&diff, LEDGER);
510        assert!(m.services.is_empty(), "silence is not a match");
511    }
512
513    #[test]
514    fn an_unparseable_ledger_is_reported_not_guessed() {
515        let m = model(
516            &diff_with("shop.billing", &[("charge", "cccc")]),
517            "not toml [",
518        );
519        assert_eq!(m.ledger, LedgerState::Unreadable);
520        assert!(m.services.is_empty());
521    }
522}