Skip to main content

code_system_graph_core/
routes.rs

1//! Canonical HTTP route shapes and the single provider index shared by every HTTP link kind.
2//!
3//! Providers are indexed by method and canonical shape. Consumers, tests, and implementation
4//! anchors resolve through the same index, so a concrete request path such as `/orders/42` reaches
5//! the `/orders/{id}` template regardless of the framework syntax that declared it.
6
7use std::collections::BTreeMap;
8
9use code_system_graph_model::{
10    Edge, EdgeId, EdgeKind, EpistemicStatus, Evidence, EvidenceId, HttpLinkGap, HttpLinkGapReason, HttpLinkReport, Node, NodeId, RepoId, stable_id
11};
12
13use crate::linker::{http_link_ambiguity, sort_http_ambiguities};
14use crate::{
15    BoundaryRole, DeclaredImplementation, DeclaredTestCase, HttpBoundary, HttpLinkAmbiguity, HttpLinkResolution, InfrastructureDocument, InfrastructureResourceKind
16};
17
18/// One segment of a canonical route template.
19#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
20pub enum RouteSegment {
21    /// Literal path segment.
22    Static(String),
23    /// Single-segment parameter such as `{id}`, `:id`, `<int:id>`, `{id:int}`, or `[id]`.
24    Param,
25    /// Literal pieces separated by single-segment parameters, such as `{name}.json`.
26    /// The first and last pieces may be empty; parameter names are discarded.
27    Mixed(Vec<String>),
28    /// Parameter that consumes one or more remaining segments, such as `{*rest}`, `{path...}`,
29    /// `<path:rest>`, `[...slug]`, or `*filepath`.
30    CatchAll,
31}
32
33/// Framework-independent route template. Parameter names are not part of the shape.
34#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
35pub struct RouteShape {
36    segments: Vec<RouteSegment>,
37}
38
39impl RouteShape {
40    /// Parses a normalized path or route template. Query strings and fragments are ignored.
41    #[must_use]
42    pub fn parse(path: &str) -> Self {
43        let path = path.split(['?', '#']).next().unwrap_or_default();
44        let mut segments = Vec::new();
45        for segment in path.split('/').filter(|segment| !segment.is_empty()) {
46            let classified = classify_segment(segment);
47            let terminal = classified == RouteSegment::CatchAll;
48            segments.push(classified);
49            if terminal {
50                break;
51            }
52        }
53        Self { segments }
54    }
55
56    /// Returns the canonical segments in path order.
57    #[must_use]
58    pub fn segments(&self) -> &[RouteSegment] {
59        &self.segments
60    }
61
62    /// Returns `true` when the shape has no parameter segment.
63    #[must_use]
64    pub fn is_concrete(&self) -> bool {
65        self.segments
66            .iter()
67            .all(|segment| matches!(segment, RouteSegment::Static(_)))
68    }
69
70    /// Renders the identity form: parameters become `{}` and catch-alls become `{*}`.
71    #[must_use]
72    pub fn canonical(&self) -> String {
73        if self.segments.is_empty() {
74            return "/".to_owned();
75        }
76        let mut rendered = String::new();
77        for segment in &self.segments {
78            rendered.push('/');
79            match segment {
80                RouteSegment::Static(value) => rendered.push_str(value),
81                RouteSegment::Param => rendered.push_str("{}"),
82                RouteSegment::Mixed(literals) => rendered.push_str(&literals.join("{}")),
83                RouteSegment::CatchAll => rendered.push_str("{*}"),
84            }
85        }
86        rendered
87    }
88}
89
90/// Returns the canonical identity form of a path or route template.
91#[must_use]
92pub fn canonical_route(path: &str) -> String {
93    RouteShape::parse(path).canonical()
94}
95
96fn classify_segment(segment: &str) -> RouteSegment {
97    if segment == "*" || segment == "**" {
98        return RouteSegment::CatchAll;
99    }
100    if let Some(inner) = segment
101        .strip_prefix('{')
102        .and_then(|value| value.strip_suffix('}'))
103        .filter(|inner| !inner.contains(['{', '}']))
104    {
105        return if inner.starts_with('*')
106            || inner.ends_with("...")
107            || inner.ends_with(":path")
108            || inner.ends_with(":.*")
109            || inner.ends_with(":.+")
110        {
111            RouteSegment::CatchAll
112        } else {
113            RouteSegment::Param
114        };
115    }
116    if (segment.starts_with("[...") && segment.ends_with(']'))
117        || (segment.starts_with("[[...") && segment.ends_with("]]"))
118    {
119        return RouteSegment::CatchAll;
120    }
121    if segment.len() > 2 && segment.starts_with('[') && segment.ends_with(']') {
122        return RouteSegment::Param;
123    }
124    if let Some(inner) = segment
125        .strip_prefix('<')
126        .and_then(|value| value.strip_suffix('>'))
127    {
128        return if inner.starts_with("path:") {
129            RouteSegment::CatchAll
130        } else {
131            RouteSegment::Param
132        };
133    }
134    if let Some(name) = segment.strip_prefix(':').filter(|name| !name.is_empty()) {
135        return if name.ends_with('*') || name.ends_with('+') {
136            RouteSegment::CatchAll
137        } else {
138            RouteSegment::Param
139        };
140    }
141    if segment.len() > 1 && segment.starts_with('*') {
142        return RouteSegment::CatchAll;
143    }
144    if let Some(literals) = mixed_segment_literals(segment) {
145        if literals.len() == 2 && literals.iter().all(String::is_empty) {
146            return RouteSegment::Param;
147        }
148        return RouteSegment::Mixed(literals);
149    }
150    RouteSegment::Static(segment.to_owned())
151}
152
153fn mixed_segment_literals(segment: &str) -> Option<Vec<String>> {
154    let mut remaining = segment;
155    let mut literals = Vec::new();
156    while let Some((prefix, parameter)) = remaining.split_once('{') {
157        let (name, suffix) = parameter.split_once('}')?;
158        if name.contains('{') || prefix.contains('}') {
159            return None;
160        }
161        // JavaScript interpolation uses `${name}` for the same path parameter.
162        literals.push(prefix.strip_suffix('$').unwrap_or(prefix).to_owned());
163        remaining = suffix;
164    }
165    if literals.is_empty() || remaining.contains('}') {
166        return None;
167    }
168    literals.push(remaining.to_owned());
169    Some(literals)
170}
171
172fn mixed_segment_matches(literals: &[String], value: &str) -> bool {
173    let [prefix, middle @ .., suffix] = literals else {
174        return false;
175    };
176    let Some(remaining) = value.strip_prefix(prefix.as_str()) else {
177        return false;
178    };
179    let Some(mut remaining) = remaining.strip_suffix(suffix.as_str()) else {
180        return false;
181    };
182    for literal in middle {
183        // Each parameter consumes at least one character, including adjacent parameters.
184        let Some(first) = remaining.chars().next() else {
185            return false;
186        };
187        remaining = &remaining[first.len_utf8()..];
188        let Some((_, rest)) = remaining.split_once(literal.as_str()) else {
189            return false;
190        };
191        remaining = rest;
192    }
193    !remaining.is_empty()
194}
195
196/// Returns the normalized authority of an absolute `http`/`https` URL.
197pub(crate) fn url_authority(url: &str) -> Option<String> {
198    let rest = url
199        .strip_prefix("http://")
200        .or_else(|| url.strip_prefix("https://"))?;
201    let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
202    normalize_authority(authority)
203}
204
205/// Normalizes a `host[:port]` authority: lower-case, without user information or a trailing
206/// root dot. Returns `None` for an empty host or a value containing a scheme, path, or whitespace.
207#[must_use]
208pub fn normalize_authority(value: &str) -> Option<String> {
209    let value = value.trim();
210    if value.is_empty() || value.contains(['/', '?', '#', ' ', '\t']) || value.contains("://") {
211        return None;
212    }
213    let host_and_port = value.rsplit_once('@').map_or(value, |(_, host)| host);
214    let (host, port) = split_port(host_and_port);
215    let host = host.trim_end_matches('.').to_ascii_lowercase();
216    if host.is_empty() || port.is_some_and(|port| port.parse::<u16>().is_err()) {
217        return None;
218    }
219    Some(match port {
220        Some(port) if host.contains(':') => format!("[{host}]:{port}"),
221        Some(port) => format!("{host}:{port}"),
222        None => host,
223    })
224}
225
226fn split_port(authority: &str) -> (&str, Option<&str>) {
227    if let Some(rest) = authority.strip_prefix('[') {
228        return match rest.split_once(']') {
229            Some((host, tail)) => (host, tail.strip_prefix(':')),
230            None => (authority, None),
231        };
232    }
233    match authority.rsplit_once(':') {
234        Some((host, port)) if !host.contains(':') => (host, Some(port)),
235        _ => (authority, None),
236    }
237}
238
239fn authority_host(authority: &str) -> &str {
240    split_port(authority).0
241}
242
243/// Returns `true` for loopback and wildcard hosts used by locally started services and tests.
244fn is_loopback(host: &str) -> bool {
245    matches!(
246        host,
247        "localhost" | "::1" | "0.0.0.0" | "host.docker.internal"
248    ) || host.ends_with(".localhost")
249        || host.starts_with("127.")
250}
251
252/// Reduces cluster-internal service DNS names such as `orders.shop.svc.cluster.local` to the
253/// service name.
254fn service_host(host: &str) -> &str {
255    let trimmed = host
256        .strip_suffix(".svc.cluster.local")
257        .or_else(|| host.strip_suffix(".svc"));
258    trimmed.map_or(host, |name| name.split('.').next().unwrap_or(name))
259}
260
261/// Repository that serves each known authority.
262///
263/// Declared authorities come from the manifest and strictly restrict resolution to their
264/// repository. Inferred authorities come from deployment declarations; when the inferred repository
265/// has no matching route, resolution falls back to workspace rules. A host inferred for several
266/// repositories is not used.
267#[derive(Debug, Clone, Default, PartialEq, Eq)]
268pub struct AuthorityMap {
269    declared: BTreeMap<String, RepoId>,
270    inferred: BTreeMap<String, Option<RepoId>>,
271}
272
273/// Resolution target of one call authority.
274#[derive(Debug, Clone, Copy, PartialEq, Eq)]
275enum AuthorityTarget<'a> {
276    Workspace,
277    Declared(&'a RepoId),
278    Inferred(&'a RepoId),
279    External,
280}
281
282impl AuthorityMap {
283    /// Creates an empty map.
284    #[must_use]
285    pub fn new() -> Self {
286        Self::default()
287    }
288
289    /// Declares the repository serving a normalized `host` or `host:port` authority.
290    pub fn declare(&mut self, authority: String, repository: RepoId) {
291        self.declared.insert(authority, repository);
292    }
293
294    /// Records a host inferred from a deployment declaration in `repository`.
295    pub fn infer(&mut self, host: &str, repository: &RepoId) {
296        let Some(host) = normalize_authority(host) else {
297            return;
298        };
299        let host = service_host(authority_host(&host)).to_owned();
300        self.inferred
301            .entry(host)
302            .and_modify(|existing| {
303                if existing.as_ref() != Some(repository) {
304                    *existing = None;
305                }
306            })
307            .or_insert_with(|| Some(repository.clone()));
308    }
309
310    /// Records every service, deployment, and host alias declared by an infrastructure document.
311    pub fn infer_from_infrastructure(
312        &mut self,
313        repository: &RepoId,
314        document: &InfrastructureDocument,
315    ) {
316        for unit in &document.deployment_units {
317            for host in std::iter::once(&unit.name)
318                .chain(&unit.service_names)
319                .chain(&unit.host_aliases)
320            {
321                self.infer(host, repository);
322            }
323        }
324        for resource in document
325            .resources
326            .iter()
327            .filter(|resource| resource.kind == InfrastructureResourceKind::Service)
328        {
329            self.infer(&resource.name, repository);
330        }
331    }
332
333    fn lookup(&self, authority: &str) -> AuthorityTarget<'_> {
334        let host = authority_host(authority);
335        if is_loopback(host) {
336            return AuthorityTarget::Workspace;
337        }
338        if let Some(repository) = self
339            .declared
340            .get(authority)
341            .or_else(|| self.declared.get(host))
342        {
343            return AuthorityTarget::Declared(repository);
344        }
345        match self.inferred.get(service_host(host)) {
346            Some(Some(repository)) => AuthorityTarget::Inferred(repository),
347            Some(None) => AuthorityTarget::Workspace,
348            None => AuthorityTarget::External,
349        }
350    }
351}
352
353/// How a caller constrains which repositories may provide the operation it invokes.
354#[derive(Debug, Clone, Default, PartialEq, Eq)]
355pub enum CallScope {
356    /// Any repository may provide the operation.
357    #[default]
358    Workspace,
359    /// The call runs in-process against the application in its own repository, such as a
360    /// `TestClient(app)`, `httptest`, or `MockMvc` request.
361    InProcess,
362    /// The call targets a normalized `host:port` authority.
363    Authority(String),
364    /// The call targets a host outside the workspace and is never linked.
365    External,
366}
367
368/// Providers sharing one canonical shape, de-duplicated by node identity.
369#[derive(Debug, Default)]
370struct ProviderSet<'a> {
371    providers: Vec<&'a HttpBoundary>,
372}
373
374impl<'a> ProviderSet<'a> {
375    fn insert(&mut self, provider: &'a HttpBoundary) {
376        if let Some(existing) = self
377            .providers
378            .iter_mut()
379            .find(|candidate| candidate.node.id == provider.node.id)
380        {
381            if provider.evidence.confidence > existing.evidence.confidence {
382                *existing = provider;
383            }
384        } else {
385            self.providers.push(provider);
386        }
387    }
388
389    fn accepted(&self, accept: &impl Fn(&HttpBoundary) -> bool) -> Vec<&'a HttpBoundary> {
390        self.providers
391            .iter()
392            .copied()
393            .filter(|provider| accept(provider))
394            .collect()
395    }
396}
397
398#[derive(Debug, Default)]
399struct RouteNode<'a> {
400    statics: BTreeMap<String, RouteNode<'a>>,
401    mixed: BTreeMap<Vec<String>, RouteNode<'a>>,
402    param: Option<Box<RouteNode<'a>>>,
403    catch_all: ProviderSet<'a>,
404    terminal: ProviderSet<'a>,
405}
406
407impl<'a> RouteNode<'a> {
408    fn insert(&mut self, segments: &[RouteSegment], provider: &'a HttpBoundary) {
409        let Some((first, rest)) = segments.split_first() else {
410            self.terminal.insert(provider);
411            return;
412        };
413        match first {
414            RouteSegment::Static(value) => self
415                .statics
416                .entry(value.clone())
417                .or_default()
418                .insert(rest, provider),
419            RouteSegment::Param => self
420                .param
421                .get_or_insert_with(Box::default)
422                .insert(rest, provider),
423            RouteSegment::Mixed(literals) => self
424                .mixed
425                .entry(literals.clone())
426                .or_default()
427                .insert(rest, provider),
428            RouteSegment::CatchAll => self.catch_all.insert(provider),
429        }
430    }
431
432    /// Finds the most specific accepted providers: at every segment a static match is preferred
433    /// over a mixed segment, then a whole-segment parameter, then a catch-all.
434    fn find(
435        &self,
436        query: &[RouteSegment],
437        accept: &impl Fn(&HttpBoundary) -> bool,
438    ) -> Vec<&'a HttpBoundary> {
439        let Some((first, rest)) = query.split_first() else {
440            return self.terminal.accepted(accept);
441        };
442        if let RouteSegment::Static(value) = first
443            && let Some(child) = self.statics.get(value)
444        {
445            let found = child.find(rest, accept);
446            if !found.is_empty() {
447                return found;
448            }
449        }
450        let mut mixed_matches = Vec::new();
451        for (literals, child) in &self.mixed {
452            let matches = match first {
453                RouteSegment::Static(value) => mixed_segment_matches(literals, value),
454                RouteSegment::Mixed(query_literals) => literals == query_literals,
455                RouteSegment::Param | RouteSegment::CatchAll => false,
456            };
457            if matches {
458                mixed_matches.extend(child.find(rest, accept));
459            }
460        }
461        if !mixed_matches.is_empty() {
462            return mixed_matches;
463        }
464        if !matches!(first, RouteSegment::CatchAll)
465            && let Some(child) = &self.param
466        {
467            let found = child.find(rest, accept);
468            if !found.is_empty() {
469                return found;
470            }
471        }
472        self.catch_all.accepted(accept)
473    }
474}
475
476/// Outcome of resolving one HTTP call against the provider index.
477#[derive(Debug, PartialEq)]
478enum RouteResolution<'a> {
479    Unique(&'a HttpBoundary),
480    Ambiguous(Vec<&'a HttpBoundary>),
481    Unmatched,
482}
483
484/// Per-method tries of provider shapes.
485#[derive(Debug, Default)]
486struct RouteIndex<'a> {
487    methods: BTreeMap<&'a str, RouteNode<'a>>,
488}
489
490impl<'a> RouteIndex<'a> {
491    fn new(boundaries: &'a [HttpBoundary]) -> Self {
492        let mut index = Self::default();
493        for provider in boundaries
494            .iter()
495            .filter(|boundary| boundary.role == BoundaryRole::Provider)
496        {
497            index
498                .methods
499                .entry(provider.method.as_str())
500                .or_default()
501                .insert(RouteShape::parse(&provider.path).segments(), provider);
502        }
503        index
504    }
505
506    /// Applies the provider scope rules in order: an explicit repository restriction (mapped
507    /// authority or in-process client), then the caller's own repository, then a unique provider
508    /// in the workspace. Anything else is ambiguous.
509    fn resolve(
510        &self,
511        method: &str,
512        path: &str,
513        caller_repository: Option<&RepoId>,
514        restriction: Option<&RepoId>,
515    ) -> RouteResolution<'a> {
516        let Some(root) = self.methods.get(method) else {
517            return RouteResolution::Unmatched;
518        };
519        let shape = RouteShape::parse(path);
520        let mut found = match restriction {
521            Some(repository) => root.find(shape.segments(), &|provider: &HttpBoundary| {
522                provider.node.repo_id.as_ref() == Some(repository)
523            }),
524            None => root.find(shape.segments(), &|_: &HttpBoundary| true),
525        };
526        if found.len() > 1
527            && let Some(caller) = caller_repository
528        {
529            let local = found
530                .iter()
531                .copied()
532                .filter(|provider| provider.node.repo_id.as_ref() == Some(caller))
533                .collect::<Vec<_>>();
534            if local.len() == 1 {
535                found = local;
536            }
537        }
538        match found.as_slice() {
539            [] => RouteResolution::Unmatched,
540            [provider] => RouteResolution::Unique(provider),
541            _ => RouteResolution::Ambiguous(found),
542        }
543    }
544}
545
546/// Repository restriction implied by a call scope.
547#[derive(Debug, Clone, Copy)]
548enum Restriction<'a> {
549    /// Resolve across the workspace.
550    Workspace,
551    /// Resolve only inside one repository.
552    Strict(&'a RepoId),
553    /// Prefer one repository and fall back to the workspace when it has no match.
554    Preferred(&'a RepoId),
555    /// The call leaves the workspace and is never linked.
556    External,
557}
558
559fn scope_restriction<'a>(
560    scope: &'a CallScope,
561    caller_repository: Option<&'a RepoId>,
562    authorities: &'a AuthorityMap,
563) -> Restriction<'a> {
564    match scope {
565        CallScope::Workspace => Restriction::Workspace,
566        CallScope::InProcess => {
567            caller_repository.map_or(Restriction::Workspace, Restriction::Strict)
568        }
569        CallScope::Authority(authority) => match authorities.lookup(authority) {
570            AuthorityTarget::Workspace => Restriction::Workspace,
571            AuthorityTarget::Declared(repository) => Restriction::Strict(repository),
572            AuthorityTarget::Inferred(repository) => Restriction::Preferred(repository),
573            AuthorityTarget::External => Restriction::External,
574        },
575        CallScope::External => Restriction::External,
576    }
577}
578
579/// Outcome of resolving one scoped call.
580enum CallResolution<'a> {
581    Route(RouteResolution<'a>),
582    External,
583}
584
585fn resolve_call<'a>(
586    index: &RouteIndex<'a>,
587    method: &str,
588    path: &str,
589    caller_repository: Option<&'a RepoId>,
590    scope: &'a CallScope,
591    authorities: &'a AuthorityMap,
592) -> CallResolution<'a> {
593    let resolution = match scope_restriction(scope, caller_repository, authorities) {
594        Restriction::Workspace => index.resolve(method, path, caller_repository, None),
595        Restriction::Strict(repository) => {
596            index.resolve(method, path, caller_repository, Some(repository))
597        }
598        Restriction::Preferred(repository) => {
599            match index.resolve(method, path, caller_repository, Some(repository)) {
600                RouteResolution::Unmatched => index.resolve(method, path, caller_repository, None),
601                resolution => resolution,
602            }
603        }
604        Restriction::External => return CallResolution::External,
605    };
606    CallResolution::Route(resolution)
607}
608
609/// Links HTTP consumers (`calls_remote`), tests (`validates`), and implementation anchors
610/// (`implemented_by`) to providers through one route index.
611///
612/// Concrete paths match provider templates; the most specific template wins and equal-shape
613/// providers are narrowed by scope. Remaining ties are reported as ambiguities with their
614/// candidates instead of edges. `authorities` maps the hosts named by absolute URLs to the
615/// repository that serves them; calls to unknown hosts leave the workspace and are reported as
616/// external rather than unmatched.
617#[must_use]
618pub fn link_http_routes(
619    boundaries: &[HttpBoundary],
620    tests: &[DeclaredTestCase],
621    implementations: &[DeclaredImplementation],
622    authorities: &AuthorityMap,
623) -> HttpLinkResolution {
624    let index = RouteIndex::new(boundaries);
625    let mut sink = LinkSink::default();
626
627    let consumers = boundaries
628        .iter()
629        .filter(|boundary| boundary.role == BoundaryRole::Consumer)
630        .map(|consumer| RemoteCall {
631            node: &consumer.node,
632            method: &consumer.method,
633            path: &consumer.path,
634            scope: &consumer.scope,
635            evidence: &consumer.evidence,
636            kind: EdgeKind::CallsRemote,
637            relation: "calls_remote",
638        });
639    let test_calls = tests.iter().map(|test| RemoteCall {
640        node: &test.node,
641        method: &test.method,
642        path: &test.path,
643        scope: &test.scope,
644        evidence: &test.evidence,
645        kind: EdgeKind::Validates,
646        relation: "validates",
647    });
648    for call in consumers.chain(test_calls) {
649        link_remote_call(&mut sink, &index, authorities, &call);
650    }
651
652    for implementation in implementations {
653        let Some(repository) = implementation.node.repo_id.as_ref() else {
654            continue;
655        };
656        match index.resolve(
657            &implementation.method,
658            &implementation.path,
659            Some(repository),
660            Some(repository),
661        ) {
662            RouteResolution::Unique(provider) => sink.link(
663                &provider.node.id,
664                &implementation.node.id,
665                EdgeKind::ImplementedBy,
666                "implemented_by",
667                provider
668                    .evidence
669                    .confidence
670                    .min(implementation.evidence.confidence),
671                vec![
672                    provider.evidence.id.clone(),
673                    implementation.evidence.id.clone(),
674                ],
675            ),
676            RouteResolution::Ambiguous(candidates) => {
677                sink.ambiguous(&implementation.method, &implementation.path, &candidates);
678            }
679            RouteResolution::Unmatched => {}
680        }
681    }
682
683    sink.finish()
684}
685
686/// Consumer or test call resolved against provider routes.
687struct RemoteCall<'a> {
688    node: &'a Node,
689    method: &'a str,
690    path: &'a str,
691    scope: &'a CallScope,
692    evidence: &'a Evidence,
693    kind: EdgeKind,
694    relation: &'static str,
695}
696
697fn link_remote_call<'a>(
698    sink: &mut LinkSink,
699    index: &RouteIndex<'a>,
700    authorities: &'a AuthorityMap,
701    call: &RemoteCall<'a>,
702) {
703    let caller = call.node.repo_id.as_ref();
704    match resolve_call(
705        index,
706        call.method,
707        call.path,
708        caller,
709        call.scope,
710        authorities,
711    ) {
712        CallResolution::Route(RouteResolution::Unique(provider)) => {
713            sink.report.coverage.linked += 1;
714            sink.link(
715                &call.node.id,
716                &provider.node.id,
717                call.kind,
718                call.relation,
719                call.evidence.confidence.min(provider.evidence.confidence),
720                vec![call.evidence.id.clone(), provider.evidence.id.clone()],
721            );
722        }
723        CallResolution::Route(RouteResolution::Ambiguous(candidates)) => {
724            sink.ambiguous(call.method, call.path, &candidates);
725            sink.gap(call, HttpLinkGapReason::Ambiguous, &candidates);
726        }
727        CallResolution::Route(RouteResolution::Unmatched) => {
728            sink.gap(call, HttpLinkGapReason::NoProvider, &[]);
729        }
730        CallResolution::External => sink.gap(call, HttpLinkGapReason::External, &[]),
731    }
732}
733
734/// Accumulates de-duplicated route edges and unresolved ambiguities.
735#[derive(Debug, Default)]
736struct LinkSink {
737    edges: BTreeMap<EdgeId, Edge>,
738    ambiguities: Vec<HttpLinkAmbiguity>,
739    report: HttpLinkReport,
740}
741
742impl LinkSink {
743    fn link(
744        &mut self,
745        source: &NodeId,
746        target: &NodeId,
747        kind: EdgeKind,
748        relation: &str,
749        confidence: f32,
750        evidence: Vec<EvidenceId>,
751    ) {
752        let edge = Edge {
753            id: EdgeId::new(stable_id(
754                "edge",
755                &format!("{}:{relation}:{}", source.as_str(), target.as_str()),
756            )),
757            source: source.clone(),
758            target: target.clone(),
759            kind,
760            confidence,
761            status: consensus_status(confidence),
762            evidence,
763        };
764        self.edges
765            .entry(edge.id.clone())
766            .and_modify(|existing| merge_equivalent_edge(existing, &edge))
767            .or_insert(edge);
768    }
769
770    fn ambiguous(&mut self, method: &str, path: &str, candidates: &[&HttpBoundary]) {
771        self.ambiguities.push(http_link_ambiguity(
772            method,
773            path,
774            candidates.iter().map(|candidate| &candidate.node.id),
775        ));
776    }
777
778    fn gap(
779        &mut self,
780        call: &RemoteCall<'_>,
781        reason: HttpLinkGapReason,
782        candidates: &[&HttpBoundary],
783    ) {
784        let coverage = &mut self.report.coverage;
785        match reason {
786            HttpLinkGapReason::NoProvider => coverage.no_provider += 1,
787            HttpLinkGapReason::Ambiguous => coverage.ambiguous += 1,
788            HttpLinkGapReason::External => coverage.external += 1,
789        }
790        let mut candidates = candidates
791            .iter()
792            .map(|candidate| candidate.node.id.clone())
793            .collect::<Vec<_>>();
794        candidates.sort();
795        candidates.dedup();
796        self.report.gaps.push(HttpLinkGap {
797            caller: call.node.id.clone(),
798            method: call.method.to_owned(),
799            path: call.path.to_owned(),
800            reason,
801            candidates,
802        });
803    }
804
805    fn finish(mut self) -> HttpLinkResolution {
806        sort_http_ambiguities(&mut self.ambiguities);
807        self.report.gaps.sort();
808        self.report.gaps.dedup();
809        HttpLinkResolution {
810            edges: self.edges.into_values().collect(),
811            ambiguities: self.ambiguities,
812            report: self.report,
813        }
814    }
815}
816
817fn merge_equivalent_edge(existing: &mut Edge, candidate: &Edge) {
818    existing.confidence = existing.confidence.max(candidate.confidence);
819    existing.status = consensus_status(existing.confidence);
820    existing.evidence.extend(candidate.evidence.iter().cloned());
821    existing.evidence.sort();
822    existing.evidence.dedup();
823}
824
825fn consensus_status(confidence: f32) -> EpistemicStatus {
826    if confidence >= 1.0 {
827        EpistemicStatus::Confirmed
828    } else {
829        EpistemicStatus::Inferred
830    }
831}
832
833#[cfg(test)]
834mod tests {
835    use code_system_graph_model::{EdgeKind, HttpLinkGapReason, RepoId};
836
837    use super::{
838        AuthorityMap, CallScope, RouteSegment, RouteShape, canonical_route, link_http_routes, normalize_authority, url_authority
839    };
840    use crate::{HttpBoundary, HttpConsumerConfig, extract_openapi};
841
842    fn provider(repo: &str, method: &str, path: &str) -> HttpBoundary {
843        let document = format!(
844            "openapi: 3.0.3\npaths:\n  {path}:\n    {}: {{}}\n",
845            method.to_ascii_lowercase()
846        );
847        match extract_openapi(&RepoId::new(repo), "openapi.yaml", &document) {
848            Ok(mut boundaries) => boundaries.remove(0),
849            Err(error) => panic!("provider fixture must be valid: {error}"),
850        }
851    }
852
853    fn consumer(repo: &str, method: &str, path: &str) -> HttpBoundary {
854        HttpBoundary::consumer(
855            RepoId::new(repo),
856            &HttpConsumerConfig {
857                method: method.to_owned(),
858                path: path.to_owned(),
859                source: "src/client.ts".to_owned(),
860            },
861        )
862    }
863
864    fn linked_targets(boundaries: &[HttpBoundary]) -> Vec<String> {
865        let resolution = link_http_routes(boundaries, &[], &[], &AuthorityMap::new());
866        resolution
867            .edges
868            .iter()
869            .filter(|edge| edge.kind == EdgeKind::CallsRemote)
870            .filter_map(|edge| {
871                boundaries
872                    .iter()
873                    .find(|boundary| boundary.node.id == edge.target)
874                    .map(|boundary| boundary.path.clone())
875            })
876            .collect()
877    }
878
879    #[test]
880    fn route_shape_should_normalize_every_framework_parameter_syntax() {
881        let parameter = "/orders/{}";
882        for template in [
883            "/orders/{id}",
884            "/orders/:id",
885            "/orders/<int:id>",
886            "/orders/<id>",
887            "/orders/{id:int}",
888            "/orders/{id:[0-9]+}",
889            "/orders/[id]",
890            "/orders/${orderId}",
891        ] {
892            assert_eq!(canonical_route(template), parameter, "{template}");
893        }
894        for template in [
895            "/files/[...slug]",
896            "/files/[[...slug]]",
897            "/files/{*rest}",
898            "/files/{path...}",
899            "/files/{rest:path}",
900            "/files/<path:rest>",
901            "/files/*filepath",
902            "/files/:rest*",
903            "/files/*",
904            "/files/**",
905        ] {
906            assert_eq!(canonical_route(template), "/files/{*}", "{template}");
907        }
908        assert_eq!(canonical_route("/"), "/");
909        assert_eq!(canonical_route("/orders/42?expand=true"), "/orders/42");
910        assert!(RouteShape::parse("/orders/42").is_concrete());
911        assert_eq!(
912            RouteShape::parse("/v1/{tenant}/orders").segments(),
913            &[
914                RouteSegment::Static("v1".to_owned()),
915                RouteSegment::Param,
916                RouteSegment::Static("orders".to_owned()),
917            ]
918        );
919    }
920
921    #[test]
922    fn concrete_path_should_link_to_the_most_specific_template() {
923        let boundaries = [
924            provider("repo:api", "GET", "/orders/{id}"),
925            provider("repo:api", "GET", "/orders/export"),
926            provider("repo:files", "GET", "/{tenant}/export"),
927            provider("repo:files", "GET", "/orders/{rest:path}"),
928            consumer("repo:web", "GET", "/orders/42"),
929            consumer("repo:web", "GET", "/orders/export"),
930            consumer("repo:web", "GET", "/orders/42/lines/7"),
931        ];
932
933        let mut targets = linked_targets(&boundaries);
934        targets.sort();
935
936        assert_eq!(
937            targets,
938            vec![
939                "/orders/export".to_owned(),
940                "/orders/{id}".to_owned(),
941                "/orders/{rest:path}".to_owned(),
942            ]
943        );
944    }
945
946    #[test]
947    fn equal_shapes_should_prefer_the_callers_repository_then_report_ambiguity() {
948        let local = [
949            provider("repo:web", "POST", "/orders"),
950            provider("repo:api", "POST", "/orders"),
951            consumer("repo:web", "POST", "/orders"),
952        ];
953        assert_eq!(linked_targets(&local), vec!["/orders".to_owned()]);
954
955        let remote = [
956            provider("repo:api-a", "POST", "/orders/{id}"),
957            provider("repo:api-b", "POST", "/orders/:orderId"),
958            consumer("repo:web", "POST", "/orders/9"),
959        ];
960        let resolution = link_http_routes(&remote, &[], &[], &AuthorityMap::new());
961        assert_eq!(resolution.edges, Vec::new());
962        assert_eq!(resolution.ambiguities.len(), 1);
963        assert_eq!(resolution.ambiguities[0].path, "/orders/9");
964        assert_eq!(resolution.ambiguities[0].candidates.len(), 2);
965    }
966
967    #[test]
968    fn scoped_calls_should_resolve_only_inside_their_restriction() {
969        let mut in_process = consumer("repo:api-b", "GET", "/health");
970        in_process.scope = CallScope::InProcess;
971        let mut mapped = consumer("repo:web", "GET", "/health");
972        mapped.scope = CallScope::Authority("orders-api:8080".to_owned());
973        let mut external = consumer("repo:web", "GET", "/health");
974        external.scope = CallScope::External;
975        let boundaries = [
976            provider("repo:api-a", "GET", "/health"),
977            provider("repo:api-b", "GET", "/health"),
978            in_process,
979            mapped,
980            external,
981        ];
982        let mut authorities = AuthorityMap::new();
983        authorities.declare("orders-api:8080".to_owned(), RepoId::new("repo:api-a"));
984
985        let resolution = link_http_routes(&boundaries, &[], &[], &authorities);
986        let mut pairs = resolution
987            .edges
988            .iter()
989            .filter_map(|edge| {
990                let source = boundaries.iter().find(|item| item.node.id == edge.source)?;
991                let target = boundaries.iter().find(|item| item.node.id == edge.target)?;
992                Some((
993                    source.node.repo_id.clone()?.as_str().to_owned(),
994                    target.node.repo_id.clone()?.as_str().to_owned(),
995                ))
996            })
997            .collect::<Vec<_>>();
998        pairs.sort();
999
1000        assert_eq!(
1001            pairs,
1002            vec![
1003                ("repo:api-b".to_owned(), "repo:api-b".to_owned()),
1004                ("repo:web".to_owned(), "repo:api-a".to_owned()),
1005            ]
1006        );
1007        assert_eq!(resolution.ambiguities, Vec::new());
1008        assert!(
1009            resolution
1010                .report
1011                .gaps
1012                .iter()
1013                .any(|call| call.reason == HttpLinkGapReason::External)
1014        );
1015    }
1016
1017    fn linked_repositories(boundaries: &[HttpBoundary], authorities: &AuthorityMap) -> Vec<String> {
1018        link_http_routes(boundaries, &[], &[], authorities)
1019            .edges
1020            .iter()
1021            .filter_map(|edge| {
1022                let target = boundaries.iter().find(|item| item.node.id == edge.target)?;
1023                Some(target.node.repo_id.clone()?.as_str().to_owned())
1024            })
1025            .collect()
1026    }
1027
1028    fn authority_consumer(authority: &str) -> HttpBoundary {
1029        let mut call = consumer("repo:web", "GET", "/orders/42");
1030        call.scope = CallScope::Authority(authority.to_owned());
1031        call
1032    }
1033
1034    #[test]
1035    fn authorities_should_resolve_loopback_declared_inferred_and_external_hosts() {
1036        let providers = [
1037            provider("repo:api-a", "GET", "/orders/{id}"),
1038            provider("repo:api-b", "GET", "/orders/{id}"),
1039        ];
1040        let mut authorities = AuthorityMap::new();
1041        authorities.declare("orders-api".to_owned(), RepoId::new("repo:api-a"));
1042        authorities.infer("billing", &RepoId::new("repo:api-b"));
1043        authorities.infer("shared", &RepoId::new("repo:api-a"));
1044        authorities.infer("shared", &RepoId::new("repo:api-b"));
1045        let resolve = |authority: &str| {
1046            let mut boundaries = providers.to_vec();
1047            boundaries.push(authority_consumer(authority));
1048            linked_repositories(&boundaries, &authorities)
1049        };
1050
1051        assert_eq!(resolve("orders-api:8080"), vec!["repo:api-a".to_owned()]);
1052        assert_eq!(
1053            resolve("billing.payments.svc.cluster.local"),
1054            vec!["repo:api-b".to_owned()]
1055        );
1056        assert_eq!(resolve("localhost:8080"), Vec::<String>::new());
1057        assert_eq!(resolve("shared:80"), Vec::<String>::new());
1058        assert_eq!(resolve("api.example.com"), Vec::<String>::new());
1059
1060        let mut single = vec![provider("repo:api-a", "GET", "/orders/{id}")];
1061        single.push(authority_consumer("127.0.0.1:3000"));
1062        assert_eq!(
1063            linked_repositories(&single, &authorities),
1064            vec!["repo:api-a".to_owned()]
1065        );
1066    }
1067
1068    #[test]
1069    fn inferred_authority_should_fall_back_to_the_workspace_when_its_repository_has_no_route() {
1070        let mut boundaries = vec![provider("repo:api-a", "GET", "/orders/{id}")];
1071        boundaries.push(authority_consumer("gateway:8080"));
1072        let mut authorities = AuthorityMap::new();
1073        authorities.infer("gateway", &RepoId::new("repo:edge"));
1074        assert_eq!(
1075            linked_repositories(&boundaries, &authorities),
1076            vec!["repo:api-a".to_owned()]
1077        );
1078
1079        let mut strict = AuthorityMap::new();
1080        strict.declare("gateway".to_owned(), RepoId::new("repo:edge"));
1081        assert_eq!(
1082            linked_repositories(&boundaries, &strict),
1083            Vec::<String>::new()
1084        );
1085    }
1086
1087    #[test]
1088    fn authority_normalization_should_reject_schemes_and_paths() {
1089        assert_eq!(
1090            url_authority("https://User@Orders-API.:8080/v1?x=1"),
1091            Some("orders-api:8080".to_owned())
1092        );
1093        assert_eq!(
1094            url_authority("http://[::1]:9000/x"),
1095            Some("[::1]:9000".to_owned())
1096        );
1097        assert_eq!(normalize_authority("http://orders"), None);
1098        assert_eq!(normalize_authority("orders/v1"), None);
1099        assert_eq!(normalize_authority("orders:http"), None);
1100        assert_eq!(normalize_authority("Orders"), Some("orders".to_owned()));
1101    }
1102
1103    #[test]
1104    fn provider_identity_should_ignore_parameter_names() {
1105        let openapi = provider("repo:api", "GET", "/orders/{orderId}");
1106        let express = provider("repo:api", "GET", "/orders/:id");
1107
1108        assert_eq!(openapi.node.id, express.node.id);
1109    }
1110
1111    #[test]
1112    fn mixed_route_segments_should_preserve_literals_in_their_identity() {
1113        for (template, canonical) in [
1114            ("/files/{name}.json", "/files/{}.json"),
1115            ("/files/report-{name}", "/files/report-{}"),
1116            ("/files/{name}.{format}", "/files/{}.{}"),
1117            ("/files/${name}.json", "/files/{}.json"),
1118        ] {
1119            assert_eq!(canonical_route(template), canonical, "{template}");
1120            assert!(!RouteShape::parse(template).is_concrete(), "{template}");
1121        }
1122        let json = provider("repo:api", "GET", "/files/{name}.json");
1123        let renamed = provider("repo:api", "GET", "/files/{id}.json");
1124        let plain = provider("repo:api", "GET", "/files/{id}");
1125        let xml = provider("repo:api", "GET", "/files/{id}.xml");
1126        assert_eq!(json.node.id, renamed.node.id);
1127        assert_ne!(json.node.id, plain.node.id);
1128        assert_ne!(json.node.id, xml.node.id);
1129    }
1130
1131    #[test]
1132    fn mixed_route_segments_should_link_only_calls_satisfying_every_literal() {
1133        for (template, matching, mismatching) in [
1134            (
1135                "/files/{name}.json",
1136                "/files/readme.json",
1137                "/files/readme.xml",
1138            ),
1139            (
1140                "/files/report-{name}",
1141                "/files/report-readme",
1142                "/files/other-readme",
1143            ),
1144            (
1145                "/files/{name}.{format}",
1146                "/files/readme.json",
1147                "/files/readme",
1148            ),
1149            (
1150                "/files/${name}.json",
1151                "/files/readme.json",
1152                "/files/readme.xml",
1153            ),
1154            ("/files/{a}{b}.json", "/files/ab.json", "/files/a.json"),
1155        ] {
1156            let boundaries = [
1157                provider("repo:api", "GET", template),
1158                consumer("repo:web", "GET", matching),
1159                consumer("repo:web", "GET", mismatching),
1160            ];
1161            assert_eq!(
1162                linked_targets(&boundaries),
1163                vec![template.to_owned()],
1164                "{template}"
1165            );
1166        }
1167    }
1168
1169    #[test]
1170    fn mixed_route_segments_should_rank_between_static_and_whole_segment_parameters() {
1171        for (call, target) in [
1172            ("/files/readme.json", "/files/readme.json"),
1173            ("/files/other.json", "/files/{name}.json"),
1174            ("/files/readme.xml", "/files/{id}"),
1175            ("/files/{id}.json", "/files/{name}.json"),
1176        ] {
1177            let boundaries = [
1178                provider("repo:api", "GET", "/files/{id}"),
1179                provider("repo:api", "GET", "/files/{name}.json"),
1180                provider("repo:api", "GET", "/files/readme.json"),
1181                consumer("repo:web", "GET", call),
1182            ];
1183            assert_eq!(
1184                linked_targets(&boundaries),
1185                vec![target.to_owned()],
1186                "{call}"
1187            );
1188        }
1189    }
1190
1191    #[test]
1192    fn overlapping_mixed_route_segments_should_report_ambiguity() {
1193        let boundaries = [
1194            provider("repo:api", "GET", "/files/{name}.json"),
1195            provider("repo:api", "GET", "/files/report-{name}"),
1196            consumer("repo:web", "GET", "/files/report-readme.json"),
1197        ];
1198        let resolution = link_http_routes(&boundaries, &[], &[], &AuthorityMap::new());
1199        assert_eq!(resolution.edges, Vec::new());
1200        assert_eq!(resolution.ambiguities.len(), 1);
1201        assert_eq!(resolution.ambiguities[0].candidates.len(), 2);
1202    }
1203
1204    #[test]
1205    fn mixed_route_parameters_should_consume_nonempty_unicode_values() {
1206        for (call, expected_links) in [
1207            ("/files/éñ.json", 1),
1208            ("/files/é.json", 0),
1209            ("/files/.json", 0),
1210        ] {
1211            let boundaries = [
1212                provider("repo:api", "GET", "/files/{a}{b}.json"),
1213                consumer("repo:web", "GET", call),
1214            ];
1215            assert_eq!(linked_targets(&boundaries).len(), expected_links, "{call}");
1216        }
1217    }
1218}