1use 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
37pub(crate) const LEDGER_FILE: &str = "bynk.deploy.lock";
39
40#[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
49#[serde(rename_all = "camelCase")]
50pub enum LedgerState {
51 Absent,
53 Unreadable,
55 Read,
56}
57
58#[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 pub kind: &'static str,
72 pub unit: String,
73 pub name: String,
74 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 pub context: String,
87 pub service: String,
88 pub status: &'static str,
91 pub live: Option<String>,
93 pub current: Option<String>,
95 pub compat: Option<CdCompat>,
99 pub loc: Option<CdLoc>,
100}
101
102#[derive(Debug, Clone, Serialize)]
104#[serde(rename_all = "camelCase")]
105pub struct CdCompat {
106 pub verdict: &'static str,
108 pub reasons: Vec<String>,
110}
111
112#[derive(Debug, Clone, Serialize)]
113#[serde(rename_all = "camelCase")]
114pub struct CdModel {
115 pub lock: LockWire,
118 pub ledger: LedgerState,
119 pub changes: Vec<CdChange>,
120 pub services: Vec<CdService>,
121}
122
123#[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 #[serde(default)]
142 contracts: Option<BTreeMap<String, String>>,
143 #[serde(default)]
145 shapes: BTreeMap<String, String>,
146}
147
148pub(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
160pub 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
236fn 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
255fn 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(¤t.worker) else {
266 continue;
267 };
268 let Some(live) = worker.contracts.as_ref() else {
269 continue;
270 };
271 for (service, hash) in ¤t.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 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 #[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 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 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 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}