1use std::collections::{BTreeMap, BTreeSet};
4
5use code_system_graph_model::{
6 Edge, EdgeId, EpistemicStatus, Evidence, EvidenceId, Node, NodeId, NodeKind
7};
8use schemars::JsonSchema;
9use serde::{Deserialize, Serialize};
10
11use super::{
12 EvidenceMetadata, INTERFACE_RESULT_VERSION, INTERFACE_SCHEMA_VERSION, InterfaceError, MAX_EXPORT_NODES, enum_name, evidence_for_edge, index_edges, index_evidence, index_nodes, validate_bound
13};
14use crate::{CompatibilityReport, CompatibilityStatus};
15
16#[derive(
18 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
19)]
20#[serde(rename_all = "kebab-case")]
21pub enum ContractAction {
22 List,
24 Show,
26 Validate,
28 Diff,
30 ExplainLink,
32}
33
34pub const CONTRACT_NODE_KINDS: [NodeKind; 9] = [
36 NodeKind::Package,
37 NodeKind::HttpOperation,
38 NodeKind::GraphqlOperation,
39 NodeKind::RpcMethod,
40 NodeKind::EventChannel,
41 NodeKind::EventSchema,
42 NodeKind::Database,
43 NodeKind::DatabaseTable,
44 NodeKind::DatabaseColumn,
45];
46
47#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
49pub struct ContractRequest {
50 pub action: ContractAction,
52 pub contract: Option<NodeId>,
54 pub related_contract: Option<NodeId>,
56 pub limit: usize,
58}
59
60impl Default for ContractRequest {
61 fn default() -> Self {
62 Self {
63 action: ContractAction::List,
64 contract: None,
65 related_contract: None,
66 limit: 100,
67 }
68 }
69}
70
71#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
73pub struct ContractCompatibility {
74 pub contract_id: NodeId,
76 pub report: CompatibilityReport,
78}
79
80#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
82pub struct ContractLink {
83 pub edge: Edge,
85 pub evidence: Vec<EvidenceMetadata>,
87}
88
89#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
91pub struct ContractView {
92 pub contract: Node,
94 pub links: Vec<ContractLink>,
96}
97
98#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
100pub struct ContractFinding {
101 pub code: String,
103 pub path: String,
105 pub status: CompatibilityStatus,
107 pub factors: Vec<String>,
109 pub recommended_validations: Vec<String>,
111}
112
113#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
115pub struct ContractCompatibilitySummary {
116 pub contract_id: NodeId,
118 pub status: CompatibilityStatus,
120 pub before_fingerprint: String,
122 pub after_fingerprint: String,
124 pub findings: Vec<ContractFinding>,
126}
127
128#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
130pub struct ContractDifference {
131 pub field: String,
133 pub before: Option<String>,
135 pub after: Option<String>,
137}
138
139#[derive(
141 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
142)]
143#[serde(rename_all = "snake_case")]
144pub enum ContractIssueSeverity {
145 Unknown,
147 Warning,
149 Error,
151}
152
153#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
155pub struct ContractIssue {
156 pub code: String,
158 pub severity: ContractIssueSeverity,
160 pub entity_id: Option<String>,
162 pub message: String,
164}
165
166#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
168pub struct ContractReport {
169 pub schema_version: u32,
171 pub result_version: u32,
173 pub action: ContractAction,
175 pub contracts: Vec<ContractView>,
177 pub links: Vec<ContractLink>,
179 pub compatibility: Vec<ContractCompatibilitySummary>,
181 pub differences: Vec<ContractDifference>,
183 pub issues: Vec<ContractIssue>,
185 pub valid: Option<bool>,
187 pub complete: bool,
189 pub truncated: bool,
191}
192
193pub fn inspect_contracts(
203 nodes: &[Node],
204 edges: &[Edge],
205 evidence: &[Evidence],
206 compatibility: &[ContractCompatibility],
207 request: &ContractRequest,
208) -> Result<ContractReport, InterfaceError> {
209 validate_bound("contract result", request.limit, MAX_EXPORT_NODES)?;
210 let node_index = index_nodes(nodes)?;
211 let evidence_index = index_evidence(evidence)?;
212 let edge_index = index_edges(edges)?;
213 let evidence_edges = index_evidence_edges(&edge_index);
214 let contract_ids = node_index
215 .values()
216 .filter(|node| is_contract_kind(node.kind))
217 .map(|node| node.id.clone())
218 .collect::<BTreeSet<_>>();
219 let mut issues = validate_contract_inputs(&node_index, &edge_index, &evidence_index);
220 let context = ContractContext {
221 nodes: &node_index,
222 contract_ids: &contract_ids,
223 edges: &edge_index,
224 evidence_edges: &evidence_edges,
225 evidence: &evidence_index,
226 compatibility,
227 };
228 let mut selected = select_contract_action(&context, request, &mut issues)?;
229 if request.action == ContractAction::List {
230 issues.retain(|issue| issue.severity == ContractIssueSeverity::Error);
231 }
232 if issues
233 .iter()
234 .any(|issue| issue.severity != ContractIssueSeverity::Warning)
235 {
236 selected.complete = false;
237 }
238 issues.sort_by(issue_order);
239 issues.dedup();
240 if issues.len() > request.limit {
241 issues.truncate(request.limit);
242 selected.truncated = true;
243 }
244 Ok(ContractReport {
245 schema_version: INTERFACE_SCHEMA_VERSION,
246 result_version: INTERFACE_RESULT_VERSION,
247 action: request.action,
248 contracts: selected.contracts,
249 links: selected.links,
250 compatibility: selected.compatibility,
251 differences: selected.differences,
252 issues,
253 valid: selected.valid,
254 complete: selected.complete,
255 truncated: selected.truncated,
256 })
257}
258
259struct ContractContext<'a> {
260 nodes: &'a BTreeMap<NodeId, &'a Node>,
261 contract_ids: &'a BTreeSet<NodeId>,
262 edges: &'a BTreeMap<EdgeId, &'a Edge>,
263 evidence_edges: &'a BTreeMap<EvidenceId, BTreeSet<EdgeId>>,
264 evidence: &'a BTreeMap<EvidenceId, &'a Evidence>,
265 compatibility: &'a [ContractCompatibility],
266}
267
268struct ContractSelection {
269 contracts: Vec<ContractView>,
270 links: Vec<ContractLink>,
271 compatibility: Vec<ContractCompatibilitySummary>,
272 differences: Vec<ContractDifference>,
273 valid: Option<bool>,
274 complete: bool,
275 truncated: bool,
276}
277
278impl ContractSelection {
279 fn complete() -> Self {
280 Self {
281 contracts: Vec::new(),
282 links: Vec::new(),
283 compatibility: Vec::new(),
284 differences: Vec::new(),
285 valid: None,
286 complete: true,
287 truncated: false,
288 }
289 }
290}
291
292fn select_contract_action(
293 context: &ContractContext<'_>,
294 request: &ContractRequest,
295 issues: &mut Vec<ContractIssue>,
296) -> Result<ContractSelection, InterfaceError> {
297 match request.action {
298 ContractAction::List => Ok(select_contract_list(context, request.limit)),
299 ContractAction::Show => select_contract_show(context, request, issues),
300 ContractAction::Validate => select_contract_validation(context, request, issues),
301 ContractAction::Diff => select_contract_diff(context, request, issues),
302 ContractAction::ExplainLink => select_contract_link(context, request, issues),
303 }
304}
305
306fn select_contract_list(context: &ContractContext<'_>, limit: usize) -> ContractSelection {
307 let ordered = ordered_contracts(context.nodes);
308 let mut selected = ContractSelection::complete();
309 selected.truncated = ordered.len() > limit;
310 selected.contracts = ordered
311 .into_iter()
312 .take(limit)
313 .map(|node| ContractView {
314 contract: node.clone(),
315 links: Vec::new(),
316 })
317 .collect();
318 selected
319}
320
321fn select_contract_show(
322 context: &ContractContext<'_>,
323 request: &ContractRequest,
324 issues: &mut Vec<ContractIssue>,
325) -> Result<ContractSelection, InterfaceError> {
326 let id = required_contract(request, false)?;
327 let node = require_contract(context.nodes, context.contract_ids, id)?;
328 issues.retain(|issue| issue_applies_to(issue, id, context.edges, context.evidence_edges));
329 let (links, truncated) = links_for_node(id, context.edges, context.evidence, request.limit);
330 let mut selected = ContractSelection::complete();
331 selected.contracts.push(ContractView {
332 contract: node.clone(),
333 links,
334 });
335 selected.truncated = truncated;
336 selected.compatibility =
337 compatibility_for(&[id], context.compatibility, issues, &mut selected.complete);
338 Ok(selected)
339}
340
341fn select_contract_validation(
342 context: &ContractContext<'_>,
343 request: &ContractRequest,
344 issues: &mut Vec<ContractIssue>,
345) -> Result<ContractSelection, InterfaceError> {
346 let mut selected = ContractSelection::complete();
347 if let Some(id) = request.contract.as_ref() {
348 let node = require_contract(context.nodes, context.contract_ids, id)?;
349 selected.contracts.push(ContractView {
350 contract: node.clone(),
351 links: Vec::new(),
352 });
353 issues.retain(|issue| issue_applies_to(issue, id, context.edges, context.evidence_edges));
354 }
355 let conclusive = !issues
356 .iter()
357 .any(|issue| issue.severity == ContractIssueSeverity::Unknown);
358 selected.complete = conclusive;
359 selected.valid = Some(
360 conclusive
361 && !issues
362 .iter()
363 .any(|issue| issue.severity == ContractIssueSeverity::Error),
364 );
365 Ok(selected)
366}
367
368fn select_contract_diff(
369 context: &ContractContext<'_>,
370 request: &ContractRequest,
371 issues: &mut Vec<ContractIssue>,
372) -> Result<ContractSelection, InterfaceError> {
373 let before_id = required_contract(request, false)?;
374 let after_id = required_contract(request, true)?;
375 let before = require_contract(context.nodes, context.contract_ids, before_id)?;
376 let after = require_contract(context.nodes, context.contract_ids, after_id)?;
377 issues.retain(|issue| {
378 issue_applies_to(issue, before_id, context.edges, context.evidence_edges)
379 || issue_applies_to(issue, after_id, context.edges, context.evidence_edges)
380 });
381 let mut selected = ContractSelection::complete();
382 selected.contracts = vec![
383 ContractView {
384 contract: before.clone(),
385 links: Vec::new(),
386 },
387 ContractView {
388 contract: after.clone(),
389 links: Vec::new(),
390 },
391 ];
392 selected.differences = contract_differences(before, after);
393 selected.compatibility = compatibility_for(
394 &[before_id, after_id],
395 context.compatibility,
396 issues,
397 &mut selected.complete,
398 );
399 Ok(selected)
400}
401
402fn select_contract_link(
403 context: &ContractContext<'_>,
404 request: &ContractRequest,
405 issues: &mut Vec<ContractIssue>,
406) -> Result<ContractSelection, InterfaceError> {
407 let source_id = required_contract(request, false)?;
408 let target_id = required_contract(request, true)?;
409 let source = require_contract(context.nodes, context.contract_ids, source_id)?;
410 let target = require_contract(context.nodes, context.contract_ids, target_id)?;
411 issues.retain(|issue| {
412 issue_applies_to(issue, source_id, context.edges, context.evidence_edges)
413 || issue_applies_to(issue, target_id, context.edges, context.evidence_edges)
414 });
415 let mut selected = ContractSelection::complete();
416 selected.contracts = vec![
417 ContractView {
418 contract: source.clone(),
419 links: Vec::new(),
420 },
421 ContractView {
422 contract: target.clone(),
423 links: Vec::new(),
424 },
425 ];
426 let mut matching = context
427 .edges
428 .values()
429 .filter(|edge| {
430 (&edge.source == source_id && &edge.target == target_id)
431 || (&edge.source == target_id && &edge.target == source_id)
432 })
433 .map(|edge| link_from_edge(edge, context.evidence))
434 .collect::<Vec<_>>();
435 matching.sort_by(|left, right| left.edge.id.cmp(&right.edge.id));
436 selected.truncated = matching.len() > request.limit;
437 selected.links = matching.into_iter().take(request.limit).collect();
438 if selected.links.is_empty() {
439 selected.complete = false;
440 issues.push(contract_issue(
441 "contract.link_not_observed",
442 ContractIssueSeverity::Unknown,
443 None,
444 "No direct link was observed; absence is not proof of independence.",
445 ));
446 }
447 Ok(selected)
448}
449
450fn is_contract_kind(kind: NodeKind) -> bool {
451 CONTRACT_NODE_KINDS.contains(&kind)
452}
453
454fn ordered_contracts<'a>(nodes: &'a BTreeMap<NodeId, &Node>) -> Vec<&'a Node> {
455 let mut contracts = nodes
456 .values()
457 .copied()
458 .filter(|node| is_contract_kind(node.kind))
459 .collect::<Vec<_>>();
460 contracts.sort_by(|left, right| {
461 left.stable_key
462 .cmp(&right.stable_key)
463 .then_with(|| left.id.cmp(&right.id))
464 });
465 contracts
466}
467
468fn required_contract(request: &ContractRequest, related: bool) -> Result<&NodeId, InterfaceError> {
469 let value = if related {
470 request.related_contract.as_ref()
471 } else {
472 request.contract.as_ref()
473 };
474 value.ok_or_else(|| InterfaceError::MissingContractField {
475 action: request.action,
476 field: if related {
477 "related_contract".to_owned()
478 } else {
479 "contract".to_owned()
480 },
481 })
482}
483
484fn require_contract<'a>(
485 nodes: &'a BTreeMap<NodeId, &Node>,
486 contracts: &BTreeSet<NodeId>,
487 id: &NodeId,
488) -> Result<&'a Node, InterfaceError> {
489 if !contracts.contains(id) {
490 return Err(InterfaceError::NotFound(id.as_str().to_owned()));
491 }
492 nodes
493 .get(id)
494 .copied()
495 .ok_or_else(|| InterfaceError::NotFound(id.as_str().to_owned()))
496}
497
498fn validate_contract_inputs(
499 nodes: &BTreeMap<NodeId, &Node>,
500 edges: &BTreeMap<EdgeId, &Edge>,
501 evidence: &BTreeMap<EvidenceId, &Evidence>,
502) -> Vec<ContractIssue> {
503 let mut issues = Vec::new();
504 for edge in edges.values().copied() {
505 for endpoint in [&edge.source, &edge.target] {
506 if !nodes.contains_key(endpoint) {
507 issues.push(contract_issue(
508 "contract.dangling_edge",
509 ContractIssueSeverity::Error,
510 Some(edge.id.as_str()),
511 &format!(
512 "Edge `{}` references missing node `{}`.",
513 edge.id.as_str(),
514 endpoint.as_str()
515 ),
516 ));
517 }
518 }
519 if !edge.confidence.is_finite() || !(0.0..=1.0).contains(&edge.confidence) {
520 issues.push(contract_issue(
521 "contract.invalid_confidence",
522 ContractIssueSeverity::Error,
523 Some(edge.id.as_str()),
524 "Edge confidence is not finite and within the inclusive range 0..=1.",
525 ));
526 }
527 if edge.status != EpistemicStatus::Confirmed {
528 issues.push(contract_issue(
529 "contract.unresolved_link",
530 ContractIssueSeverity::Unknown,
531 Some(edge.id.as_str()),
532 "The relationship is not confirmed and cannot prove a contract link.",
533 ));
534 }
535 for evidence_id in &edge.evidence {
536 if !evidence.contains_key(evidence_id) {
537 issues.push(contract_issue(
538 "contract.evidence_not_observed",
539 ContractIssueSeverity::Unknown,
540 Some(edge.id.as_str()),
541 &format!(
542 "Referenced evidence `{}` was not observed.",
543 evidence_id.as_str()
544 ),
545 ));
546 }
547 }
548 }
549 for item in evidence.values().copied() {
550 if !item.confidence.is_finite() || !(0.0..=1.0).contains(&item.confidence) {
551 issues.push(contract_issue(
552 "contract.invalid_evidence_confidence",
553 ContractIssueSeverity::Error,
554 Some(item.id.as_str()),
555 "Evidence confidence is not finite and within the inclusive range 0..=1.",
556 ));
557 }
558 }
559 issues
560}
561
562fn contract_issue(
563 code: &str,
564 severity: ContractIssueSeverity,
565 entity_id: Option<&str>,
566 message: &str,
567) -> ContractIssue {
568 ContractIssue {
569 code: code.to_owned(),
570 severity,
571 entity_id: entity_id.map(str::to_owned),
572 message: message.to_owned(),
573 }
574}
575
576fn issue_order(left: &ContractIssue, right: &ContractIssue) -> std::cmp::Ordering {
577 issue_severity_rank(left.severity)
578 .cmp(&issue_severity_rank(right.severity))
579 .then_with(|| left.code.cmp(&right.code))
580 .then_with(|| left.entity_id.cmp(&right.entity_id))
581 .then_with(|| left.message.cmp(&right.message))
582}
583
584const fn issue_severity_rank(severity: ContractIssueSeverity) -> u8 {
585 match severity {
586 ContractIssueSeverity::Error => 0,
587 ContractIssueSeverity::Unknown => 1,
588 ContractIssueSeverity::Warning => 2,
589 }
590}
591
592fn issue_applies_to(
593 issue: &ContractIssue,
594 contract_id: &NodeId,
595 edges: &BTreeMap<EdgeId, &Edge>,
596 evidence_edges: &BTreeMap<EvidenceId, BTreeSet<EdgeId>>,
597) -> bool {
598 issue.entity_id.as_deref().is_some_and(|entity_id| {
599 entity_id == contract_id.as_str()
600 || edges
601 .get(&EdgeId::new(entity_id))
602 .is_some_and(|edge| edge.source == *contract_id || edge.target == *contract_id)
603 || evidence_edges
604 .get(&EvidenceId::new(entity_id))
605 .is_some_and(|incident| {
606 incident.iter().any(|edge_id| {
607 edges.get(edge_id).is_some_and(|edge| {
608 edge.source == *contract_id || edge.target == *contract_id
609 })
610 })
611 })
612 })
613}
614
615fn index_evidence_edges(edges: &BTreeMap<EdgeId, &Edge>) -> BTreeMap<EvidenceId, BTreeSet<EdgeId>> {
616 let mut index = BTreeMap::<EvidenceId, BTreeSet<EdgeId>>::new();
617 for edge in edges.values() {
618 for evidence_id in &edge.evidence {
619 index
620 .entry(evidence_id.clone())
621 .or_default()
622 .insert(edge.id.clone());
623 }
624 }
625 index
626}
627
628fn link_from_edge(edge: &Edge, evidence: &BTreeMap<EvidenceId, &Evidence>) -> ContractLink {
629 ContractLink {
630 edge: edge.clone(),
631 evidence: evidence_for_edge(edge, evidence),
632 }
633}
634
635fn links_for_node(
636 id: &NodeId,
637 edges: &BTreeMap<EdgeId, &Edge>,
638 evidence: &BTreeMap<EvidenceId, &Evidence>,
639 limit: usize,
640) -> (Vec<ContractLink>, bool) {
641 let matching = edges
642 .values()
643 .copied()
644 .filter(|edge| edge.source == *id || edge.target == *id)
645 .collect::<Vec<_>>();
646 let truncated = matching.len() > limit;
647 (
648 matching
649 .into_iter()
650 .take(limit)
651 .map(|edge| link_from_edge(edge, evidence))
652 .collect(),
653 truncated,
654 )
655}
656
657fn compatibility_for(
658 ids: &[&NodeId],
659 compatibility: &[ContractCompatibility],
660 issues: &mut Vec<ContractIssue>,
661 complete: &mut bool,
662) -> Vec<ContractCompatibilitySummary> {
663 let wanted = ids.iter().copied().collect::<BTreeSet<_>>();
664 let mut selected = compatibility
665 .iter()
666 .filter(|item| wanted.contains(&item.contract_id))
667 .map(compatibility_summary)
668 .collect::<Vec<_>>();
669 selected.sort_by(|left, right| left.contract_id.cmp(&right.contract_id));
670 selected.dedup_by(|left, right| left.contract_id == right.contract_id);
671 for id in ids {
672 if !selected.iter().any(|item| &item.contract_id == *id) {
673 *complete = false;
674 issues.push(contract_issue(
675 "contract.compatibility_not_observed",
676 ContractIssueSeverity::Unknown,
677 Some(id.as_str()),
678 "Compatibility was not supplied for the selected contract.",
679 ));
680 }
681 }
682 selected
683}
684
685fn compatibility_summary(value: &ContractCompatibility) -> ContractCompatibilitySummary {
686 let mut findings = value
687 .report
688 .findings
689 .iter()
690 .map(|finding| ContractFinding {
691 code: finding.code.clone(),
692 path: finding.path.clone(),
693 status: finding.status,
694 factors: finding.factors.clone(),
695 recommended_validations: finding.recommended_validations.clone(),
696 })
697 .collect::<Vec<_>>();
698 findings.sort_by(|left, right| {
699 left.path
700 .cmp(&right.path)
701 .then_with(|| left.code.cmp(&right.code))
702 });
703 ContractCompatibilitySummary {
704 contract_id: value.contract_id.clone(),
705 status: value.report.status,
706 before_fingerprint: value.report.before_fingerprint.clone(),
707 after_fingerprint: value.report.after_fingerprint.clone(),
708 findings,
709 }
710}
711
712fn contract_differences(before: &Node, after: &Node) -> Vec<ContractDifference> {
713 let mut differences = Vec::new();
714 if before.kind != after.kind {
715 differences.push(ContractDifference {
716 field: "kind".to_owned(),
717 before: Some(enum_name(before.kind)),
718 after: Some(enum_name(after.kind)),
719 });
720 }
721 if before.repo_id != after.repo_id {
722 differences.push(ContractDifference {
723 field: "repo_id".to_owned(),
724 before: before.repo_id.as_ref().map(|id| id.as_str().to_owned()),
725 after: after.repo_id.as_ref().map(|id| id.as_str().to_owned()),
726 });
727 }
728 if before.stable_key != after.stable_key {
729 differences.push(ContractDifference {
730 field: "stable_key".to_owned(),
731 before: Some(before.stable_key.clone()),
732 after: Some(after.stable_key.clone()),
733 });
734 }
735 if before.label != after.label {
736 differences.push(ContractDifference {
737 field: "label".to_owned(),
738 before: Some(before.label.clone()),
739 after: Some(after.label.clone()),
740 });
741 }
742 differences
743}