Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(workspace): gateway routes from Spring Cloud Gateway and Zuul, rewritten at match time (#4536)

Raghav Chamadiya712261ba74be
diff --git a/docs/architecture/workspace.md b/docs/architecture/workspace.md
index 4acf6f363..da2d9b6fb 100644
--- a/docs/architecture/workspace.md
+++ b/docs/architecture/workspace.md
@@ -130,8 +130,8 @@ links are appended after it.
pattern subscription, `service_mapped` when the provider sits in the consumer's
resolved target. A target the map placed does not fall back to another repo that
serves the same path (`common.prefer_target_repo`).
-4. **Type passes**, in `MATCHERS` order: HTTP `base_resolved_pass`, `candidate_pass`
- (`unique_path`, `ambiguous_path`, `prefix_stripped`) and `service_pass`; topic
+4. **Type passes**, in `MATCHERS` order: HTTP `gateway_pass` (`gateway_route`),
+ `base_resolved_pass`, `candidate_pass` (`unique_path`, `ambiguous_path`, `prefix_stripped`) and `service_pass`; topic
`binding_pass` (`binding_routed`); data `shared_table_pass` (`shared_table`).
5. **Service links**: `service_pass` gives each HTTP consumer whose target is a
workspace repo, but whose path no provider serves, one `host_only` link with no
@@ -381,7 +381,10 @@ support a score, a cycle verdict or an empty impact set.
built from), `aliases` (repo aliases the file names, such as an image basename),
`ref` (an `ENV` key whose value is a host, resolved through the finished host
map) or `own_repo` (the repo holding the file, kept only when it is the only name
- the source places there). Use `base.host_of` to read address values.
+ the source places there). Use `base.host_of` to read address values. A gateway
+ states `route=Route(prefix, upstream)` claims instead, with `base.literal_prefix`
+ for its path patterns; the engine settles them into `GatewayRoute` rows the HTTP
+ matcher applies (`matching/http.py::gateway_pass`).
4. Add `SOURCE` to `SOURCES`, keeping it sorted by `name`.
5. Copy a real config file into `tests/fixtures/service_names/<estate>/`, with
`.keep` files for the repo directories it names, and add a test in
@@ -408,6 +411,8 @@ add its case to `test_graph_evidence.py`.
`ExternalName` services are not read.
- Only HTTP consumers resolve targets through the map, and only HTTP has service
links.
+- Gateway routes are prefix routes only. A relative call from a frontend repo other
+ than the gateway's is not routed, since nothing says which gateway serves it.
- A `host_only` edge is service-level: it has no provider route, so breaking-change
diffs and test impact do not follow it.
- The network probe is lexical. It reads only extensions some extractor walks,
diff --git a/docs/reference/WORKSPACE_CONTRACTS.md b/docs/reference/WORKSPACE_CONTRACTS.md
index 2815d4182..ccda333cc 100644
--- a/docs/reference/WORKSPACE_CONTRACTS.md
+++ b/docs/reference/WORKSPACE_CONTRACTS.md
@@ -42,6 +42,7 @@ follows from the strategy.
| 0.6 | `ambiguous_path` | candidate | The base is unread and several services serve the path; linked to each |
| 0.6 | `prefix_stripped` | candidate | Matched only after stripping mount, version or base prefixes |
| 0.5 | `host_only` | candidate | The host names a workspace service, but no route there serves the path; a service-level edge |
+| 1.0 | `gateway_route` | exact | A gateway's config forwards the path to the service: the gateway's own edge, and a call through it linked on the forwarded path |
| 1.0 | `manual` | manual | Declared in the workspace config |
A new dialect picks an existing origin, not a number. A system-graph edge carries the
@@ -125,12 +126,25 @@ records `target_via` (the source) and `target_evidence` (the file).
| `compose` | `docker-compose*.yml`, `compose*.yml` | Service name, `container_name`, `hostname`; `environment` keys whose value is an address | `build` context (or its Dockerfile's directory), else an image basename equal to a repo alias |
| `k8s_service` | `*.yaml` under `k8s/`, `deploy/`, `manifests/`, ... | `kind: Service` `metadata.name` | A selector or label value equal to a repo alias, else the manifest's repo when it declares no other Service |
| `spring_application_name` | `application` / `bootstrap` `.yml` or `.properties` | `spring.application.name` | The module the file sits in |
+| `spring_gateway` | `application` / `bootstrap` in a module's resources, or a config-server file named `*gateway*`, `*zuul*`, `*proxy*`, `*edge*` (`.yml` or `.properties`) holding `routes` | Spring Cloud Gateway `routes[]` (`lb://name`, `http://host`) and Zuul `zuul.routes` | A gateway route (below) |
Each repo is walked once per update for these file names; test, example and build-output
directories are skipped, and files at the workspace root are read too. A name two files
place in different repos is left unmapped rather than guessed. To override or fill a gap, add
the host or base token to `service_bases`, which always wins.
+A gateway source states routes rather than names: a path prefix the gateway forwards to a
+service, and the path it forwards (Spring `StripPrefix`, `PrefixPath` and a
+`RewritePath=/x/?(?<s>.*), /y/${s}`; Zuul `stripPrefix`). The gateway is the repo holding
+an `application` file in its module's own resources, or for a config server's `gateway.yml`
+the app its name spells. Each route is a `gateway_route` edge from the gateway to the
+service. A route whose forwarded path or target is not read (a Host or Method predicate,
+`SetPath`, a service outside the workspace, a prefix sent two ways) rewrites no call but keeps
+a shorter prefix from claiming the paths under it. A call that reaches the gateway (its
+host names the gateway, or a relative call from the gateway's own pages) is rewritten by the
+longest matching prefix and linked to the route's service on the forwarded path; when no
+route there serves it, it becomes a `host_only` edge to that service.
+
## Contracts over REST
`GET /api/workspace/contracts` lists contracts and links,
diff --git a/packages/core/src/repowise/core/workspace/contracts.py b/packages/core/src/repowise/core/workspace/contracts.py
index 72366a813..9bf3c4f88 100644
--- a/packages/core/src/repowise/core/workspace/contracts.py
+++ b/packages/core/src/repowise/core/workspace/contracts.py
@@ -72,7 +72,8 @@ CONTRACTS_FILENAME = "contracts.json"
# service-name map (:mod:`.service_names`), and ``service_links`` holds the
# service-level edges for calls whose host is known but whose route is not;
# each repo also counts the files whose network calls produced no contract
-# (see :mod:`.network_probe`).
+# (see :mod:`.network_probe`). Gateway routes (Spring Cloud Gateway, Zuul)
+# rewrite the calls they forward and add gateway-to-service service links.
CONTRACTS_VERSION = 15
#: ``meta["kind"]`` of a topic contract: the destination a broker call names.
@@ -256,8 +257,9 @@ class ContractStore:
#: run and must be re-extracted rather than trusted.
repo_provenance: dict[str, dict[str, str]] = field(default_factory=dict)
#: Service-level edges (:attr:`.origins.LinkStrategy.HOST_ONLY`): a consumer
- #: whose host names a workspace repo while no route there serves its path.
- #: Kept out of ``contract_links``, which only ever pairs two contracts.
+ #: whose host names a workspace repo while no route there serves its path;
+ #: and a gateway's edge to each service it routes to
+ #: (:attr:`.origins.LinkStrategy.GATEWAY_ROUTE`, no consumer contract). Kept out of ``contract_links``, which only ever pairs two contracts.
service_links: list[ContractLink] = field(default_factory=list)
#: The service-name map matching used (:mod:`.service_names`): each name, its
#: repo, and the source and file that placed it, plus the fingerprint that
@@ -669,7 +671,7 @@ async def run_contract_extraction(
else:
names = await asyncio.to_thread(build_service_name_map, repo_paths, workspace_root)
annotate_consumer_targets(all_contracts, contract_config.service_bases, names)
- matched = run_matching(all_contracts)
+ matched = run_matching(all_contracts, names.routes)
links = matched.links
# Merge manual links
diff --git a/packages/core/src/repowise/core/workspace/matching/__init__.py b/packages/core/src/repowise/core/workspace/matching/__init__.py
index 947ad9ce1..1e0fd671c 100644
--- a/packages/core/src/repowise/core/workspace/matching/__init__.py
+++ b/packages/core/src/repowise/core/workspace/matching/__init__.py
@@ -12,7 +12,7 @@ Same-repo same-service pairs, and consumers resolved to a third-party host
from __future__ import annotations
-from collections.abc import Callable
+from collections.abc import Callable, Iterable
from dataclasses import dataclass
from typing import TYPE_CHECKING
@@ -25,6 +25,7 @@ from .http import annotate_consumer_targets
if TYPE_CHECKING:
from repowise.core.workspace.contracts import Contract, ContractLink
+ from repowise.core.workspace.service_names import GatewayRoute
@dataclass(frozen=True)
@@ -45,7 +46,12 @@ class TypeMatcher:
MATCHERS: dict[str, TypeMatcher] = {
"http": TypeMatcher(
deferred=http.is_deferred,
- passes=(http.base_resolved_pass, http.candidate_pass, http.service_pass),
+ passes=(
+ http.gateway_pass,
+ http.base_resolved_pass,
+ http.candidate_pass,
+ http.service_pass,
+ ),
),
"topic": TypeMatcher(
deferred=topic.is_binding,
@@ -92,18 +98,20 @@ def _exact_pass(state: MatchState) -> None:
state.add(consumer, provider, strategy, via_alias=aliased)
-def run_matching(contracts: list[Contract]) -> MatchState:
+def run_matching(contracts: list[Contract], routes: Iterable[GatewayRoute] = ()) -> MatchState:
"""Match providers to consumers across repos; the state holds links and service links.
The exact pass runs first for every type, then each registered type's own
passes in registry order. Target resolution for HTTP consumers is read from
- ``meta`` (see :func:`annotate_consumer_targets`).
+ ``meta`` (see :func:`annotate_consumer_targets`). Each gateway route in
+ *routes* adds its gateway-to-service edge to the service links.
"""
state = MatchState.build(contracts)
_exact_pass(state)
for rules in MATCHERS.values():
for run in rules.passes:
run(state)
+ state.service_links.extend(http.gateway_route_links(routes))
return state
diff --git a/packages/core/src/repowise/core/workspace/matching/common.py b/packages/core/src/repowise/core/workspace/matching/common.py
index ccc1869ba..e482460b2 100644
--- a/packages/core/src/repowise/core/workspace/matching/common.py
+++ b/packages/core/src/repowise/core/workspace/matching/common.py
@@ -92,6 +92,9 @@ class MatchState:
normalize_contract_id(provider.contract_id) if via_alias else "",
)
if dedup_key in self.seen:
+ # The same call written twice in one file: already linked, so later
+ # passes must not place it again.
+ self.matched.add(id(consumer))
return False
self.seen.add(dedup_key)
self.links.append(
diff --git a/packages/core/src/repowise/core/workspace/matching/http.py b/packages/core/src/repowise/core/workspace/matching/http.py
index 2fd4c6ece..7d6c182db 100644
--- a/packages/core/src/repowise/core/workspace/matching/http.py
+++ b/packages/core/src/repowise/core/workspace/matching/http.py
@@ -13,12 +13,26 @@ from collections import defaultdict
from typing import TYPE_CHECKING
from repowise.core.workspace.contracts import ContractLink, normalize_contract_id
-from repowise.core.workspace.origins import LinkStrategy, link_confidence, match_type_for
-from repowise.core.workspace.service_names import ENV, HOST, ServiceName, ServiceNameMap
+from repowise.core.workspace.origins import (
+ ORIGIN_CONFIDENCE,
+ ContractOrigin,
+ LinkStrategy,
+ link_confidence,
+ match_type_for,
+)
+from repowise.core.workspace.service_names import (
+ ENV,
+ HOST,
+ GatewayRoute,
+ ServiceName,
+ ServiceNameMap,
+)
from .common import find_matching_keys, internal, prefer_target_repo
if TYPE_CHECKING:
+ from collections.abc import Iterable
+
from repowise.core.workspace.contracts import Contract
from .common import MatchState
@@ -173,6 +187,8 @@ def annotate_consumer_targets(
for key in _TARGET_KEYS:
c.meta.pop(key, None)
target, external, via = _resolve_consumer_target(c, repo_aliases, sb, names)
+ if not external and names.routes:
+ target, via = _apply_gateway_route(c, target, via, names)
if external:
c.meta["external"] = True
elif target:
@@ -183,7 +199,41 @@ def annotate_consumer_targets(
c.meta["target_evidence"] = via.file
-_TARGET_KEYS = ("target_repo", "external", "target_via", "target_evidence")
+_TARGET_KEYS = ("target_repo", "external", "target_via", "target_evidence", "route_path")
+
+
+def _through_gateway(
+ consumer: Contract, target: str | None, names: ServiceNameMap
+) -> tuple[GatewayRoute, str] | None:
+ """The gateway route *consumer* travels, and the path it forwards, when one applies.
+
+ A call reaches a gateway when its host or base resolved to the gateway's
+ repo, or when it names no host or base at all and sits in the gateway's
+ repo (pages the gateway serves itself). Ceiling: a relative call from a
+ separate frontend repo is not routed; it would need the frontend's own
+ proxy or base config to say which gateway it talks to.
+ """
+ meta = consumer.meta
+ if target is not None:
+ gateway = target
+ elif not meta.get("host") and not meta.get("base_token"):
+ gateway = consumer.repo
+ else:
+ return None
+ split = _split_http_id(normalize_contract_id(consumer.contract_id))
+ return names.route_for(gateway, split[1]) if split is not None else None
+
+
+def _apply_gateway_route(
+ consumer: Contract, target: str | None, via: ServiceName | None, names: ServiceNameMap
+) -> tuple[str | None, ServiceName | None]:
+ """Retarget *consumer* to the service its gateway route forwards to, stamping the
+ forwarded path; unchanged when no route applies."""
+ routed = _through_gateway(consumer, target, names)
+ if routed is None:
+ return target, via
+ route, consumer.meta["route_path"] = routed
+ return route.repo, ServiceName(route.name, HOST, route.repo, route.source, route.file)
# ---------------------------------------------------------------------------
@@ -232,8 +282,63 @@ def _methods_compatible(consumer_method: str, provider_method: str) -> bool:
def is_deferred(consumer: Contract) -> bool:
- """A base-stripped consumer skips the exact pass; :func:`base_resolved_pass` owns it."""
- return bool(consumer.meta.get("base_stripped"))
+ """A base-stripped or gateway-routed consumer skips the exact pass; its own pass owns it."""
+ return bool(consumer.meta.get("base_stripped") or "route_path" in consumer.meta)
+
+
+def gateway_pass(state: MatchState) -> None:
+ """Link each gateway-routed consumer on the path its route forwards, in the route's target.
+
+ A routed consumer no provider there serves is left to :func:`service_pass`,
+ which draws the service-level edge the route itself establishes.
+ """
+ for consumer in state.unmatched("http"):
+ upstream = consumer.meta.get("route_path")
+ split = _split_http_id(normalize_contract_id(consumer.contract_id))
+ if upstream is None or split is None:
+ continue
+ target = consumer.meta.get("target_repo")
+ keys = find_matching_keys(f"http::{split[0]}::{upstream}", state.provider_index)
+ providers = [p for k in keys for p in state.provider_index[k] if p.repo == target]
+ for provider in providers:
+ if not internal(provider, consumer):
+ state.add(consumer, provider, LinkStrategy.GATEWAY_ROUTE)
+
+
+def gateway_route_links(routes: Iterable[GatewayRoute]) -> list[ContractLink]:
+ """One service-level edge per route, from the gateway to the service it forwards to.
+
+ The route is declared config, so the edge carries a route registration's
+ confidence; its consumer file is the config file when that sits in the
+ gateway's own repo, else the repo root (a config server's file).
+ """
+ confidence = link_confidence(
+ LinkStrategy.GATEWAY_ROUTE, ORIGIN_CONFIDENCE[ContractOrigin.ROUTE_REGISTRATION]
+ )
+ links: list[ContractLink] = []
+ for r in routes:
+ if not r.repo:
+ continue # a blocker: the target is outside the workspace or disputed
+ own = r.file.startswith(f"{r.gateway}/")
+ forwarded = "?" if r.upstream is None else r.upstream or "/"
+ links.append(
+ ContractLink(
+ contract_id=f"http::*::{r.prefix}/**",
+ contract_type="http",
+ match_type=match_type_for(LinkStrategy.GATEWAY_ROUTE),
+ confidence=confidence,
+ provider_repo=r.repo,
+ provider_file="",
+ provider_symbol=f"{r.name} ({r.source})",
+ provider_service=None,
+ consumer_repo=r.gateway,
+ consumer_file=r.file[len(r.gateway) + 1 :] if own else "",
+ consumer_symbol=f"{r.prefix}/** -> {forwarded}",
+ consumer_service=None,
+ strategy=LinkStrategy.GATEWAY_ROUTE,
+ )
+ )
+ return links
def base_resolved_pass(state: MatchState) -> None:
@@ -245,7 +350,7 @@ def base_resolved_pass(state: MatchState) -> None:
every service that serves it (``ambiguous_path``, a candidate).
"""
for consumer in state.unmatched("http"):
- if not is_deferred(consumer):
+ if not consumer.meta.get("base_stripped") or "route_path" in consumer.meta:
continue
matching_keys = find_matching_keys(consumer.contract_id, state.provider_index)
providers = [
@@ -290,6 +395,7 @@ def candidate_pass(state: MatchState) -> None:
if split is None:
continue
method, path = split
+ path = consumer.meta.get("route_path", path)
if _is_static_asset_path(path):
continue
core = _candidate_http_path(path)
@@ -351,6 +457,8 @@ __all__ = [
"annotate_consumer_targets",
"base_resolved_pass",
"candidate_pass",
+ "gateway_pass",
+ "gateway_route_links",
"is_deferred",
"service_pass",
]
diff --git a/packages/core/src/repowise/core/workspace/origins.py b/packages/core/src/repowise/core/workspace/origins.py
index 7d675b141..32cc16dec 100644
--- a/packages/core/src/repowise/core/workspace/origins.py
+++ b/packages/core/src/repowise/core/workspace/origins.py
@@ -83,6 +83,10 @@ class LinkStrategy(StrEnum):
#: The consumer's host or base token maps to a service, but no route there serves
#: its path: a service-level dependency, not a route link.
HOST_ONLY = "host_only"
+ #: A gateway's config forwards a path prefix to the service: the gateway's
+ #: own edge to it, and a call through the gateway linked on the path the
+ #: route forwards (see :mod:`.service_names.spring_gateway`).
+ GATEWAY_ROUTE = "gateway_route"
#: The consumer's base is unread and exactly one service serves the path.
UNIQUE_PATH = "unique_path"
#: The consumer's base is unread and several services serve the path; linked to each.
@@ -102,6 +106,7 @@ STRATEGY_CONFIDENCE: dict[LinkStrategy, float] = {
LinkStrategy.SHARED_TABLE: 1.0,
LinkStrategy.SERVICE_MAPPED: 1.0,
LinkStrategy.HOST_ONLY: 0.5,
+ LinkStrategy.GATEWAY_ROUTE: 1.0,
LinkStrategy.UNIQUE_PATH: 1.0,
LinkStrategy.AMBIGUOUS_PATH: 0.6,
LinkStrategy.PREFIX_STRIPPED: 0.6,
diff --git a/packages/core/src/repowise/core/workspace/service_names/__init__.py b/packages/core/src/repowise/core/workspace/service_names/__init__.py
index 2e9696092..10b6ae83d 100644
--- a/packages/core/src/repowise/core/workspace/service_names/__init__.py
+++ b/packages/core/src/repowise/core/workspace/service_names/__init__.py
@@ -7,6 +7,11 @@ one pruned walk per repo plus the workspace root's own files) and states
:class:`.base.Claim` rows; :func:`build_service_name_map` turns them into one
entry per name, recording the source and file that produced it.
+A gateway source states route claims instead: a path prefix one gateway
+forwards to a named service. They resolve after the host map into
+:class:`GatewayRoute` rows, which the matcher applies as path rewrites and
+draws as gateway-to-service edges.
+
A name two sources (or two files) place in different repos is dropped rather
than guessed. Manual ``contracts.service_bases`` entries are not part of the map:
the matcher (:func:`..matching.http.annotate_consumer_targets`) consults them
@@ -23,14 +28,15 @@ import json
import logging
import os
from collections import defaultdict
+from collections.abc import Callable
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import Any
from repowise.core.fs_walk import PRUNED_DIRS, walk_repo
-from . import aspire, compose, k8s_service, spring
-from .base import ENV, HOST, Claim, ServiceNameSource, SourceFile
+from . import aspire, compose, k8s_service, spring, spring_gateway
+from .base import ENV, HOST, Claim, Route, ServiceNameSource, SourceFile
_log = logging.getLogger("repowise.workspace.service_names")
@@ -39,6 +45,7 @@ SOURCES: tuple[ServiceNameSource, ...] = (
compose.SOURCE,
k8s_service.SOURCE,
spring.SOURCE,
+ spring_gateway.SOURCE,
)
# Test, example and build-output trees declare services that are not the
@@ -75,6 +82,25 @@ class ServiceName:
file: str
+@dataclass(frozen=True)
+class GatewayRoute:
+ """A path prefix the *gateway* repo forwards to *repo*, rewritten to *upstream*.
+
+ *name* is the service the route names, *source* and *file* say where it was read.
+ A route whose forwarded path is unknown (``upstream`` None) rewrites nothing but
+ still shadows shorter prefixes; one whose target is unknown or disputed has
+ ``repo`` ``""`` and draws no edge either.
+ """
+
+ gateway: str
+ prefix: str
+ upstream: str | None
+ repo: str
+ name: str
+ source: str
+ file: str
+
+
@dataclass
class ServiceNameMap:
"""Names to repos, by kind (:data:`.base.HOST` or :data:`.base.ENV`)."""
@@ -84,15 +110,37 @@ class ServiceNameMap:
repos: frozenset[str] = frozenset()
#: Names claimed for more than one repo, and those repos: left unmapped.
ambiguous: dict[tuple[str, str], tuple[str, ...]] = field(default_factory=dict)
+ #: Gateway routes, one per gateway and prefix.
+ routes: tuple[GatewayRoute, ...] = ()
def lookup(self, name: str, kind: str = HOST) -> ServiceName | None:
return self.entries.get((kind, name.lower()))
+ def route_for(self, gateway: str, path: str) -> tuple[GatewayRoute, str] | None:
+ """The longest route *gateway* forwards *path* (lowercase) under, and the path it forwards.
+
+ Ceiling: Spring Cloud Gateway picks the first route in its own order, not
+ the longest prefix; longest-prefix is the reading that holds whenever a
+ more specific route is listed before a broader one, as is usual.
+ """
+ under = [
+ r
+ for r in self.routes
+ if r.gateway == gateway and (path == r.prefix or path.startswith(r.prefix + "/"))
+ ]
+ if not under:
+ return None
+ best = max(under, key=lambda r: len(r.prefix))
+ if best.upstream is None or not best.repo:
+ return None
+ return best, (best.upstream + path[len(best.prefix) :]) or "/"
+
def to_dict(self, fingerprint: str = "") -> dict[str, Any]:
return {
"fingerprint": fingerprint,
"repos": sorted(self.repos),
"entries": [asdict(e) for _, e in sorted(self.entries.items())],
+ "routes": [asdict(r) for r in self.routes],
}
@classmethod
@@ -101,6 +149,7 @@ class ServiceNameMap:
return cls(
entries={(e.kind, e.name): e for e in entries},
repos=frozenset(data.get("repos", [])),
+ routes=tuple(GatewayRoute(**r) for r in data.get("routes", [])),
)
@@ -212,6 +261,48 @@ def _settle(
out.ambiguous[key] = tuple(sorted(by_repo))
+def _route_row(f: _Found, named: Callable[[str], str | None]) -> GatewayRoute | None:
+ """One route claim placed: its gateway repo and target repo (``""`` when unknown or itself)."""
+ route: Route = f.claim.route # type: ignore[assignment]
+ if route.gateway:
+ gateway = next((r for r in map(named, route.gateway) if r is not None), None)
+ else:
+ gateway = f.file_repo
+ if gateway is None or not route.prefix:
+ return None
+ target = named(f.claim.name)
+ target = "" if target is None or target == gateway else target
+ return GatewayRoute(
+ gateway, route.prefix, route.upstream, target, f.claim.name, f.source.name, f.evidence
+ )
+
+
+def _settle_routes(
+ found: list[_Found], named: Callable[[str], str | None]
+) -> tuple[GatewayRoute, ...]:
+ """One route per gateway and prefix.
+
+ A prefix sent two ways, to a service outside the workspace, or back to the
+ gateway is kept as a blocker (no target, no rewrite) rather than dropped, so
+ a shorter prefix of the same gateway cannot claim the paths under it.
+ """
+ by_key: dict[tuple[str, str], dict[tuple[str, str | None], GatewayRoute]] = defaultdict(dict)
+ for f in found:
+ row = _route_row(f, named)
+ if row is not None:
+ by_key[(row.gateway, row.prefix)].setdefault((row.repo, row.upstream), row)
+ settled: list[GatewayRoute] = []
+ for (gateway, prefix), ways in sorted(by_key.items()):
+ first = next(iter(ways.values()))
+ if len(ways) > 1:
+ targets = sorted({t for t, _ in ways})
+ _log.debug("Gateway %s routes %s several ways: %s", gateway, prefix, targets)
+ target = targets[0] if len(targets) == 1 else ""
+ first = GatewayRoute(gateway, prefix, None, target, first.name, first.source, first.file)
+ settled.append(first)
+ return tuple(settled)
+
+
def build_service_name_map(
repo_paths: dict[str, Path], workspace_root: Path | None = None
) -> ServiceNameMap:
@@ -230,12 +321,16 @@ def build_service_name_map(
own: dict[tuple[str, str], set[str]] = defaultdict(set)
deferred_own: list[tuple[_Found, str]] = []
refs: list[_Found] = []
+ routes: list[_Found] = []
def claim(f: _Found, repo: str) -> None:
claimed[(f.claim.kind, f.claim.name)].setdefault(repo, (f.source.name, f.evidence))
for f in found:
c = f.claim
+ if c.route is not None:
+ routes.append(f)
+ continue
if c.ref is not None:
refs.append(f)
continue
@@ -257,14 +352,17 @@ def build_service_name_map(
# Ceiling: keys and names are workspace-wide, not scoped to the stack that
# declares them; two stacks reusing a name collide and are dropped. Scoping
# by compose project is the upgrade if estates mix unrelated stacks.
+ def named(name: str) -> str | None:
+ hit = out.lookup(name, HOST)
+ return hit.repo if hit is not None else resolver.named((name.lower(),))
+
env_claimed: dict[tuple[str, str], dict[str, tuple[str, str]]] = defaultdict(dict)
for f in refs:
- ref = f.claim.ref or ""
- hit = out.lookup(ref, HOST)
- repo = hit.repo if hit is not None else resolver.named((ref,))
+ repo = named(f.claim.ref or "")
if repo is not None:
env_claimed[(ENV, f.claim.name)].setdefault(repo, (f.source.name, f.evidence))
_settle(env_claimed, out)
+ out.routes = _settle_routes(routes, named)
if out.ambiguous:
_log.debug("Service names left unmapped (claimed for several repos): %s", out.ambiguous)
@@ -275,6 +373,7 @@ __all__ = [
"ENV",
"HOST",
"SOURCES",
+ "GatewayRoute",
"ServiceName",
"ServiceNameMap",
"build_service_name_map",
diff --git a/packages/core/src/repowise/core/workspace/service_names/base.py b/packages/core/src/repowise/core/workspace/service_names/base.py
index 4f6ecb007..790245db0 100644
--- a/packages/core/src/repowise/core/workspace/service_names/base.py
+++ b/packages/core/src/repowise/core/workspace/service_names/base.py
@@ -26,6 +26,25 @@ HOST = "host"
ENV = "env"
+@dataclass(frozen=True)
+class Route:
+ """A gateway's path rule: a request under ``prefix`` is forwarded with that prefix
+ replaced by ``upstream`` (``""`` strips it, ``prefix`` keeps it).
+
+ Both are lowercase literal paths without a trailing slash. ``upstream`` is
+ None when the route's forwarded path cannot be read (a filter or predicate
+ the source does not model): no call is rewritten through it, and it still
+ keeps a shorter prefix from claiming the paths under it. ``gateway`` names
+ the gateway service when the file configures an app that lives elsewhere (a
+ config server's ``gateway.yml``), as candidate names tried in order through
+ the host map and the repo aliases; empty means the repo holding the file.
+ """
+
+ prefix: str
+ upstream: str | None = ""
+ gateway: tuple[str, ...] = ()
+
+
@dataclass(frozen=True)
class Claim:
"""One file's statement that *name* is served by some repo.
@@ -37,6 +56,10 @@ class Claim:
resolved through the finished host map), and ``own_repo`` (the repo holding
the file, kept only when it is the only name the source places in that
repo this way, so a deploy repo listing every service claims none).
+
+ A claim with a ``route`` says instead that a gateway forwards that path
+ prefix to *name*; *name* resolves like a ``ref``, through the finished host
+ map and then the repo aliases.
"""
name: str
@@ -45,6 +68,7 @@ class Claim:
aliases: tuple[str, ...] = ()
ref: str | None = None
own_repo: bool = False
+ route: Route | None = None
@dataclass(frozen=True)
@@ -62,8 +86,8 @@ class ServiceNameSource:
``filenames`` are case-insensitive globs on the file's own name; ``under``,
when set, requires an ancestor directory (inside the repo) with one of
those names; ``marker`` must occur in the text before ``read`` parses it.
- A gateway source would add a path rewrite to its claims for the matcher to
- apply; nothing here assumes a claim is a plain host.
+ A gateway source states :class:`Route` claims, which the matcher applies as
+ path rewrites.
"""
name: str
@@ -105,6 +129,34 @@ _ADDRESS_KEY_RE = re.compile(
)
+_PATTERN_SEGMENT_RE = re.compile(r"[*{}?<>()\[\]$^]")
+_WHOLE_SEGMENT_RE = re.compile(r"^(?:\*{1,2}|\{[^{}]*\})$")
+
+#: :func:`literal_prefix` kinds: a whole wildcard or variable segment follows the
+#: prefix (a prefix route), the pattern is all literal, or a segment mixes text
+#: and a wildcard (``orders*``, ``v{n}``), so only the part before it is known.
+PREFIX = "prefix"
+EXACT = "exact"
+PARTIAL = "partial"
+
+
+def literal_prefix(pattern: str) -> tuple[str, str]:
+ """The literal leading path of a route pattern, and what follows it.
+
+ ``/api/vet/**`` is ``("/api/vet", PREFIX)``, ``/orders/{id}`` is
+ ``("/orders", PREFIX)``, ``/health`` is ``("/health", EXACT)`` and
+ ``/api/orders*`` is ``("/api", PARTIAL)``. Lowercase, no trailing slash;
+ ``""`` when the pattern starts with a wildcard.
+ """
+ literal: list[str] = []
+ for seg in (s for s in pattern.strip().split("/") if s):
+ if _PATTERN_SEGMENT_RE.search(seg):
+ kind = PREFIX if _WHOLE_SEGMENT_RE.match(seg) else PARTIAL
+ return ("/" + "/".join(literal) if literal else ""), kind
+ literal.append(seg.lower())
+ return ("/" + "/".join(literal) if literal else ""), EXACT
+
+
def host_of(key: str, value: str) -> str | None:
"""The host config entry *key* = *value* names, or None when it is not an address.
@@ -120,4 +172,17 @@ def host_of(key: str, value: str) -> str | None:
return m.group(1).lower() if m else None
-__all__ = ["ENV", "HOST", "Claim", "ServiceNameSource", "SourceFile", "host_of", "join_config_path"]
+__all__ = [
+ "ENV",
+ "EXACT",
+ "HOST",
+ "PARTIAL",
+ "PREFIX",
+ "Claim",
+ "Route",
+ "ServiceNameSource",
+ "SourceFile",
+ "host_of",
+ "join_config_path",
+ "literal_prefix",
+]
diff --git a/packages/core/src/repowise/core/workspace/service_names/spring_gateway.py b/packages/core/src/repowise/core/workspace/service_names/spring_gateway.py
new file mode 100644
index 000000000..d0020f38e
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/service_names/spring_gateway.py
@@ -0,0 +1,225 @@
+"""Spring Cloud Gateway and Netflix Zuul routes: which path prefix a gateway forwards where.
+
+Read from YAML or ``.properties``, flattened to Spring's dotted keys so both
+spellings go through one reader:
+
+- ``spring.cloud.gateway[.server.webflux|.server.webmvc|.mvc].routes[i]``: the
+ ``uri`` (``lb://name`` or ``http://host:port``) names the service, a ``Path``
+ predicate the prefix, and ``StripPrefix``, ``PrefixPath`` and the
+ ``RewritePath=/x/?(?<s>.*), /y/${s}`` shape what is forwarded;
+- ``zuul.routes.<id>``: ``path``, then ``serviceId``, ``url`` or the route id,
+ with ``stripPrefix`` (default true) and the global ``zuul.prefix``.
+
+The gateway is the repo holding an ``application`` or ``bootstrap`` file that
+sits in its module's own resources or ``config/`` directory, or for any other
+file (a config server's ``gateway.yml``) the app its name spells, a profile
+suffix dropped.
+
+A route the reader cannot rewrite through (a fully literal or partly
+wildcarded ``Path``, a Host, Method or Header predicate, ``SetPath``, another
+``RewritePath``, a ``forward:`` target) is still stated, with no forwarded
+path, so it keeps a shorter prefix from claiming its calls. A catch-all
+``/**`` is skipped. A config-server file is read only when its name holds
+``gateway``, ``zuul``, ``proxy`` or ``edge``; widening that gate is one glob.
+"""
+
+from __future__ import annotations
+
+import re
+from collections import defaultdict
+from collections.abc import Callable, Iterable, Iterator
+from pathlib import Path
+from typing import Any
+
+from .base import PREFIX, Claim, Route, ServiceNameSource, SourceFile, host_of, literal_prefix
+from .yaml_docs import load_yaml_docs
+
+_SCG_RE = re.compile(
+ r"^spring\.cloud\.gateway(?:\.server\.webflux|\.server\.webmvc|\.mvc)?\.routes\[(\d+)\]\.(.+)$"
+)
+_ZUUL_RE = re.compile(r"^zuul\.routes\.([^.\[]+)(?:\.([^.]+))?$")
+_PROPERTY_RE = re.compile(r"^\s*([^#!\s=:][^=:\s]*)\s*[=:]\s*(.*?)\s*$", re.MULTILINE)
+_LIST_ITEM_RE = re.compile(r"^(predicates|filters)\[(\d+)\](?:\.(.+))?$")
+_REWRITE_RE = re.compile(r"^(/[^()*?+\\$^\[]*?)/?\??\(\?<(\w+)>\.\*\)$")
+_REPLACEMENT_RE = re.compile(r"^(/?[^$]*?)/?\$\\?\{(\w+)\}$")
+_PATH_FILTERS = frozenset({"setpath", "rewritepath"})
+
+
+def _flatten(node: Any, key: str, out: dict[str, str]) -> None:
+ if isinstance(node, dict):
+ for k, v in node.items():
+ _flatten(v, f"{key}.{k}" if key else str(k), out)
+ elif isinstance(node, list):
+ for i, v in enumerate(node):
+ _flatten(v, f"{key}[{i}]", out)
+ elif node is not None and key:
+ out[key] = str(node)
+
+
+def _flat(file: SourceFile) -> list[dict[str, str]]:
+ if file.path.suffix.lower() == ".properties":
+ return [dict(_PROPERTY_RE.findall(file.text))]
+ docs: list[dict[str, str]] = []
+ for doc in load_yaml_docs(file.text):
+ flat: dict[str, str] = {}
+ _flatten(doc, "", flat)
+ docs.append(flat)
+ return docs
+
+
+def _key(name: str) -> str:
+ """Relaxed binding: ``serviceId``, ``service-id`` and ``service_id`` are one key."""
+ return name.replace("-", "").replace("_", "").lower()
+
+
+def _items(fields: dict[str, str], kind: str) -> list[tuple[str, list[str]]]:
+ """``(name, args)`` of each predicate or filter, shortcut (``Path=/a/**``) or long form."""
+ grouped: dict[int, dict[str, str]] = defaultdict(dict)
+ for sub, value in fields.items():
+ m = _LIST_ITEM_RE.match(sub)
+ if m and m.group(1) == kind:
+ grouped[int(m.group(2))][m.group(3) or ""] = value
+ items: list[tuple[str, list[str]]] = []
+ for _, parts in sorted(grouped.items()):
+ if "" in parts:
+ name, _, args = parts[""].partition("=")
+ items.append((name.strip(), [a.strip() for a in args.split(",") if a.strip()]))
+ else:
+ args = [v for k, v in sorted(parts.items()) if k.startswith("args.")]
+ items.append((parts.get("name", "").strip(), args))
+ return items
+
+
+def _rewrite(current: str, regex: str, replacement: str) -> str | None:
+ """``current`` under ``RewritePath=/x/?(?<s>.*), /y/${s}``, or None for any other shape."""
+ m, r = _REWRITE_RE.match(regex.strip()), _REPLACEMENT_RE.match(replacement.strip())
+ if m is None or r is None or m.group(2) != r.group(2):
+ return None
+ head = m.group(1).rstrip("/").lower()
+ if current != head and not current.startswith(head + "/"):
+ return None
+ return r.group(1).rstrip("/").lower() + current[len(head) :]
+
+
+def _forwarded(prefix: str, filters: list[tuple[str, list[str]]]) -> str | None:
+ """What *prefix* is forwarded as after *filters*, or None when a filter cannot be read."""
+ current = prefix
+ for name, args in filters:
+ key = _key(name)
+ if key == "stripprefix":
+ n = int(args[0]) if args and args[0].isdigit() else 1
+ segments = [s for s in current.split("/") if s]
+ if n > len(segments):
+ return None # strips into the wildcard part: the rest is unknown
+ current = "/" + "/".join(segments[n:]) if segments[n:] else ""
+ elif key == "prefixpath" and args:
+ current = args[0].rstrip("/").lower() + current
+ elif key == "rewritepath":
+ if len(args) != 2 or (current := _rewrite(current, *args)) is None: # type: ignore[assignment]
+ return None
+ elif key in _PATH_FILTERS:
+ return None
+ return current
+
+
+def _service(uri: str) -> str | None:
+ uri = uri.strip()
+ if uri.lower().startswith("lb:"):
+ return uri.split("://", 1)[-1].split("/")[0].split(":")[0].lower() or None
+ return host_of("uri", uri) if "://" in uri else None
+
+
+def _route(pattern: str, forwarded: Callable[[str], str | None], readable: bool = True) -> Route | None:
+ """The route a path pattern makes: a rewrite for a readable prefix route, else a blocker."""
+ prefix, kind = literal_prefix(pattern)
+ if not prefix:
+ return None # a catch-all is never more specific than a real route
+ upstream = forwarded(prefix) if kind == PREFIX and readable else None
+ return Route(prefix, upstream)
+
+
+def _gateway_routes(flat: dict[str, str]) -> Iterator[tuple[str, Route]]:
+ routes: dict[str, dict[str, str]] = defaultdict(dict)
+ for key, value in flat.items():
+ if m := _SCG_RE.match(key):
+ routes[m.group(1)][m.group(2)] = value
+ for fields in routes.values():
+ # A forward:/ or no://op route serves locally: it only blocks shorter prefixes.
+ service = _service(fields.get("uri", "")) or ""
+ filters = _items(fields, "filters")
+ predicates = _items(fields, "predicates")
+ # A Host, Method or Header predicate narrows which calls take the route.
+ readable = all(_key(name) == "path" for name, _ in predicates)
+ for name, args in predicates:
+ if _key(name) != "path":
+ continue
+ for pattern in args:
+ route = _route(pattern, lambda p, f=filters: _forwarded(p, f), readable)
+ if route is not None:
+ yield service, route
+
+
+def _zuul_routes(flat: dict[str, str]) -> Iterator[tuple[str, Route]]:
+ routes: dict[str, dict[str, str]] = defaultdict(dict)
+ settings: dict[str, str] = {}
+ for key, value in flat.items():
+ if m := _ZUUL_RE.match(key):
+ routes[m.group(1)][_key(m.group(2) or "path")] = value
+ elif key.startswith("zuul."):
+ settings[_key(key)] = value
+ global_prefix = literal_prefix(settings.get("zuul.prefix", ""))[0]
+ global_strip = settings.get("zuul.stripprefix", "true").lower() != "false"
+ for route_id, fields in routes.items():
+ if "url" in fields and "serviceid" not in fields:
+ service = _service(fields["url"]) or "" # forward:/local only blocks
+ else:
+ service = fields.get("serviceid") or route_id
+ strip = fields.get("stripprefix", "true").lower() != "false"
+ route = _route(
+ fields.get("path", f"/{route_id}/**"),
+ lambda p, strip=strip: ("" if global_strip else global_prefix) + ("" if strip else p),
+ )
+ if route is not None:
+ yield service.lower(), Route(global_prefix + route.prefix, route.upstream)
+
+
+#: Spring profile suffixes a config server's ``<app>-<profile>.yml`` may carry.
+_PROFILES = frozenset(
+ {"default", "dev", "development", "local", "test", "qa", "stage", "staging", "uat",
+ "prod", "production", "docker", "k8s", "kubernetes", "cloud", "native"}
+)
+#: Where a module's own ``application`` file sits: ``src/main/resources``, its
+#: ``config/`` child, or a ``config/`` beside the jar. Anywhere else (a config
+#: server's ``shared/`` tree) it configures every app, not this repo's gateway.
+_OWN_CONFIG_DIRS = frozenset({"resources", "config"})
+
+
+def _gateway_names(path: Path) -> tuple[str, ...] | None:
+ """The app a config file configures: ``()`` for its own module's file, its name
+ otherwise (a profile suffix dropped), or None when the file is not a gateway's."""
+ stem = path.stem.lower()
+ if stem.startswith(("application", "bootstrap")):
+ return () if path.parent.name.lower() in _OWN_CONFIG_DIRS else None
+ app, _, profile = stem.rpartition("-")
+ return (stem, app) if app and profile in _PROFILES else (stem,)
+
+
+def read(file: SourceFile) -> Iterable[Claim]:
+ gateway = _gateway_names(file.path)
+ if gateway is None:
+ return
+ for flat in _flat(file):
+ for service, route in (*_gateway_routes(flat), *_zuul_routes(flat)):
+ yield Claim(name=service, route=Route(route.prefix, route.upstream, gateway))
+
+
+SOURCE = ServiceNameSource(
+ name="spring_gateway",
+ filenames=tuple(
+ f"{stem}.{ext}"
+ for stem in ("application*", "bootstrap*", "*gateway*", "*zuul*", "*proxy*", "*edge*")
+ for ext in ("yml", "yaml", "properties")
+ ),
+ marker="routes",
+ read=read,
+)
diff --git a/tests/fixtures/service_names/spring_pc/spring-petclinic-api-gateway/src/main/resources/application.yml b/tests/fixtures/service_names/spring_pc/spring-petclinic-api-gateway/src/main/resources/application.yml
new file mode 100644
index 000000000..d4e05f84b
--- /dev/null
+++ b/tests/fixtures/service_names/spring_pc/spring-petclinic-api-gateway/src/main/resources/application.yml
@@ -0,0 +1,53 @@
+spring:
+ application:
+ name: api-gateway
+ config:
+ import: optional:configserver:${CONFIG_SERVER_URL:http://localhost:8888/}
+ cloud:
+ gateway:
+ server:
+ webflux:
+ default-filters:
+ - name: CircuitBreaker
+ args:
+ name: defaultCircuitBreaker
+ fallbackUri: forward:/fallback
+ - name: Retry
+ args:
+ retries: 1
+ statuses: SERVICE_UNAVAILABLE
+ methods: POST
+ routes:
+ - id: vets-service
+ uri: lb://vets-service
+ predicates:
+ - Path=/api/vet/**
+ filters:
+ - StripPrefix=2
+ - id: visits-service
+ uri: lb://visits-service
+ predicates:
+ - Path=/api/visit/**
+ filters:
+ - StripPrefix=2
+ - id: customers-service
+ uri: lb://customers-service
+ predicates:
+ - Path=/api/customer/**
+ filters:
+ - StripPrefix=2
+ - id: genai-service
+ uri: lb://genai-service
+ predicates:
+ - Path=/api/genai/**
+ filters:
+ - StripPrefix=2
+ - CircuitBreaker=name=genaiCircuitBreaker,fallbackUri=/fallback
+ reactor:
+ context-propagation: auto
+---
+spring:
+ config:
+ activate:
+ on-profile: docker
+ import: configserver:http://config-server:8888
diff --git a/tests/fixtures/service_names/spring_pc/spring-petclinic-customers-service/src/main/resources/application.yml b/tests/fixtures/service_names/spring_pc/spring-petclinic-customers-service/src/main/resources/application.yml
new file mode 100644
index 000000000..2a0866eb4
--- /dev/null
+++ b/tests/fixtures/service_names/spring_pc/spring-petclinic-customers-service/src/main/resources/application.yml
@@ -0,0 +1,3 @@
+spring:
+ application:
+ name: customers-service
diff --git a/tests/fixtures/service_names/spring_pc/spring-petclinic-vets-service/src/main/resources/application.yml b/tests/fixtures/service_names/spring_pc/spring-petclinic-vets-service/src/main/resources/application.yml
new file mode 100644
index 000000000..d253cdb23
--- /dev/null
+++ b/tests/fixtures/service_names/spring_pc/spring-petclinic-vets-service/src/main/resources/application.yml
@@ -0,0 +1,3 @@
+spring:
+ application:
+ name: vets-service
diff --git a/tests/fixtures/service_names/spring_pm/config/src/main/resources/shared/gateway.yml b/tests/fixtures/service_names/spring_pm/config/src/main/resources/shared/gateway.yml
new file mode 100644
index 000000000..bceb918d7
--- /dev/null
+++ b/tests/fixtures/service_names/spring_pm/config/src/main/resources/shared/gateway.yml
@@ -0,0 +1,45 @@
+hystrix:
+ command:
+ default:
+ execution:
+ isolation:
+ thread:
+ timeoutInMilliseconds: 20000
+
+ribbon:
+ ReadTimeout: 20000
+ ConnectTimeout: 20000
+
+zuul:
+ ignoredServices: '*'
+ host:
+ connect-timeout-millis: 20000
+ socket-timeout-millis: 20000
+
+ routes:
+ auth-service:
+ path: /uaa/**
+ url: http://auth-service:5000
+ stripPrefix: false
+ sensitiveHeaders:
+
+ account-service:
+ path: /accounts/**
+ serviceId: account-service
+ stripPrefix: false
+ sensitiveHeaders:
+
+ statistics-service:
+ path: /statistics/**
+ serviceId: statistics-service
+ stripPrefix: false
+ sensitiveHeaders:
+
+ notification-service:
+ path: /notifications/**
+ serviceId: notification-service
+ stripPrefix: false
+ sensitiveHeaders:
+
+server:
+ port: 4000
diff --git a/tests/fixtures/service_names/spring_pm/gateway/src/main/resources/bootstrap.yml b/tests/fixtures/service_names/spring_pm/gateway/src/main/resources/bootstrap.yml
new file mode 100644
index 000000000..56093adc5
--- /dev/null
+++ b/tests/fixtures/service_names/spring_pm/gateway/src/main/resources/bootstrap.yml
@@ -0,0 +1,9 @@
+spring:
+ application:
+ name: gateway
+ cloud:
+ config:
+ uri: http://config:8888
+ fail-fast: true
+ password: ${CONFIG_SERVICE_PASSWORD}
+ username: user
diff --git a/tests/unit/workspace/test_gateway_routes.py b/tests/unit/workspace/test_gateway_routes.py
new file mode 100644
index 000000000..b0dbaca4c
--- /dev/null
+++ b/tests/unit/workspace/test_gateway_routes.py
@@ -0,0 +1,311 @@
+"""Gateway routes: read from config, settled in the service-name map, applied by the matcher."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from repowise.core.workspace.contracts import Contract, ContractStore
+from repowise.core.workspace.cross_repo import CrossRepoOverlay
+from repowise.core.workspace.matching import annotate_consumer_targets, run_matching
+from repowise.core.workspace.origins import LinkStrategy
+from repowise.core.workspace.service_names import (
+ GatewayRoute,
+ ServiceName,
+ ServiceNameMap,
+ build_service_name_map,
+)
+from repowise.core.workspace.service_names.base import (
+ EXACT,
+ PARTIAL,
+ PREFIX,
+ Route,
+ SourceFile,
+ literal_prefix,
+)
+from repowise.core.workspace.service_names.spring_gateway import read
+from repowise.core.workspace.system_graph import build_system_graph
+
+FIXTURES = Path(__file__).resolve().parents[2] / "fixtures" / "service_names"
+
+
+def _routes(m: ServiceNameMap) -> set[tuple[str, str, str | None, str]]:
+ return {(r.gateway, r.prefix, r.upstream, r.repo) for r in m.routes}
+
+
+def _read(name: str, text: str) -> list[tuple[str, Route]]:
+ return [(c.name, c.route) for c in read(SourceFile(Path(name), text)) if c.route is not None]
+
+
+# ---------------------------------------------------------------------------
+# Sources, on real files
+# ---------------------------------------------------------------------------
+
+
+def test_spring_cloud_gateway_routes_strip_their_prefix() -> None:
+ root = FIXTURES / "spring_pc"
+ gateway, customers, vets = (
+ "spring-petclinic-api-gateway",
+ "spring-petclinic-customers-service",
+ "spring-petclinic-vets-service",
+ )
+ m = build_service_name_map({a: root / a for a in (gateway, customers, vets)})
+ # visits-service and genai-service are routed outside this workspace: blockers only.
+ assert _routes(m) == {
+ (gateway, "/api/customer", "", customers),
+ (gateway, "/api/vet", "", vets),
+ (gateway, "/api/visit", "", ""),
+ (gateway, "/api/genai", "", ""),
+ }
+ [route] = [r for r in m.routes if r.repo == vets]
+ assert (route.name, route.source) == ("vets-service", "spring_gateway")
+ assert route.file == f"{gateway}/src/main/resources/application.yml"
+
+
+def test_zuul_routes_in_a_config_server_file_belong_to_the_app_it_names() -> None:
+ root = FIXTURES / "spring_pm"
+ repos = ("account-service", "auth-service", "config", "gateway")
+ m = build_service_name_map({a: root / a for a in repos})
+ # stripPrefix: false keeps the prefix; the file sits in config, the gateway is `gateway`.
+ assert _routes(m) == {
+ ("gateway", "/accounts", "/accounts", "account-service"),
+ ("gateway", "/uaa", "/uaa", "auth-service"),
+ ("gateway", "/notifications", "/notifications", ""),
+ ("gateway", "/statistics", "/statistics", ""),
+ }
+ # Without the gateway's own module the owner is unknown: no route, not the config repo.
+ assert build_service_name_map({a: root / a for a in repos[:3]}).routes == ()
+
+
+# ---------------------------------------------------------------------------
+# The reader's shapes
+# ---------------------------------------------------------------------------
+
+
+def test_properties_long_form_and_path_filters() -> None:
+ text = "\n".join(
+ [
+ "spring.cloud.gateway.routes[0].uri=lb://orders",
+ "spring.cloud.gateway.routes[0].predicates[0]=Path=/api/orders/**,/v2/orders/**",
+ "spring.cloud.gateway.routes[0].filters[0]=StripPrefix=1",
+ "spring.cloud.gateway.routes[0].filters[1]=PrefixPath=/internal",
+ "spring.cloud.gateway.routes[1].uri=http://billing:8080",
+ "spring.cloud.gateway.routes[1].predicates[0]=Path=/bill/**",
+ r"spring.cloud.gateway.routes[1].filters[0]=RewritePath=/bill/?(?<seg>.*), /v1/$\{seg}",
+ ]
+ )
+ assert _read("src/main/resources/application.properties", text) == [
+ ("orders", Route("/api/orders", "/internal/orders")),
+ ("orders", Route("/v2/orders", "/internal/orders")),
+ ("billing", Route("/bill", "/v1")),
+ ]
+
+
+def test_yaml_long_form_and_routes_it_can_only_block() -> None:
+ text = """
+spring:
+ cloud:
+ gateway:
+ mvc:
+ routes:
+ - id: users
+ uri: lb:ws://users
+ predicates:
+ - name: Path
+ args:
+ patterns: /users/**
+ filters:
+ - name: StripPrefix
+ args:
+ parts: 1
+ - {id: exact, uri: lb://a, predicates: [Path=/health]}
+ - {id: all, uri: lb://b, predicates: [Path=/**]}
+ - {id: deep, uri: lb://c, predicates: ["Path=/x/{y}/**"], filters: [StripPrefix=2]}
+ - {id: setpath, uri: lb://d, predicates: [Path=/d/**], filters: [SetPath=/z]}
+ - {id: partial, uri: lb://e, predicates: ["Path=/api/orders*"]}
+ - {id: method, uri: lb://f, predicates: [Path=/f/**, Method=GET]}
+ - {id: local, uri: forward:/local, predicates: [Path=/local/**]}
+"""
+ g = ("gateway-dev", "gateway")
+ assert _read("gateway-dev.yml", text) == [
+ ("users", Route("/users", "", g)),
+ ("a", Route("/health", None, g)),
+ ("c", Route("/x", None, g)),
+ ("d", Route("/d", None, g)),
+ ("e", Route("/api", None, g)),
+ ("f", Route("/f", None, g)),
+ ("", Route("/local", "/local", g)), # no target: settles as a blocker
+ ]
+
+
+def test_zuul_defaults_and_global_prefix() -> None:
+ text = """
+zuul:
+ prefix: /api
+ strip_prefix: true
+ routes:
+ users: /myusers/**
+ orders:
+ path: /orders/**
+ url: http://orders-svc:8080
+ stripPrefix: false
+ local:
+ path: /local/**
+ url: forward:/here
+"""
+ assert _read("src/main/resources/application.yml", text) == [
+ ("users", Route("/api/myusers", "")),
+ ("orders-svc", Route("/api/orders", "/orders")),
+ ("", Route("/api/local", "")),
+ ]
+
+
+def test_which_files_name_a_gateway() -> None:
+ text = "zuul:\n routes:\n users: /users/**\n"
+ # A profile suffix is dropped; any other last word is part of the name.
+ assert [r.gateway for _, r in _read("api-gateway-docker.yml", text)] == [
+ ("api-gateway-docker", "api-gateway")
+ ]
+ assert [r.gateway for _, r in _read("api-gateway.yml", text)] == [("api-gateway",)]
+ # An application file outside a module's own resources configures every app.
+ assert _read("config/src/main/resources/shared/application.yml", text) == []
+ assert [r.gateway for _, r in _read("gw/src/main/resources/config/application.yml", text)] == [()]
+
+
+ ("pattern", "expected"),
+ [
+ ("/api/vet/**", ("/api/vet", PREFIX)),
+ ("/Orders/{id}", ("/orders", PREFIX)),
+ ("/health", ("/health", EXACT)),
+ ("/api/orders*", ("/api", PARTIAL)),
+ ("/api/v{n}/x/**", ("/api", PARTIAL)),
+ ("/**", ("", PREFIX)),
+ ],
+)
+def test_literal_prefix(pattern: str, expected: tuple[str, str]) -> None:
+ assert literal_prefix(pattern) == expected
+
+
+def test_a_disputed_or_unknown_route_blocks_shorter_prefixes(tmp_path: Path) -> None:
+ for name, svc in (("gw", None), ("a", "svc-a"), ("b", "svc-b")):
+ res = tmp_path / name / "src" / "main" / "resources"
+ res.mkdir(parents=True)
+ if svc:
+ (res / "application.yml").write_text(f"spring:\n application:\n name: {svc}\n")
+ gw_res = tmp_path / "gw" / "src" / "main" / "resources"
+ rows = [
+ ("lb://svc-a", "/api/**"),
+ ("lb://svc-a", "/api/vet/**"),
+ ("lb://svc-b", "/api/vet/**"), # the same prefix, another service
+ ("lb://elsewhere", "/api/pay/**"), # a service outside the workspace
+ ("lb://svc-b", "/api/visit/**"),
+ ]
+ (gw_res / "application.properties").write_text(
+ "".join(
+ f"spring.cloud.gateway.routes[{i}].uri={uri}\n"
+ f"spring.cloud.gateway.routes[{i}].predicates[0]=Path={path}\n"
+ for i, (uri, path) in enumerate(rows)
+ )
+ )
+ m = build_service_name_map({n: tmp_path / n for n in ("gw", "a", "b")})
+ assert _routes(m) == {
+ ("gw", "/api", "/api", "a"),
+ ("gw", "/api/vet", None, ""),
+ ("gw", "/api/pay", "/api/pay", ""),
+ ("gw", "/api/visit", "/api/visit", "b"),
+ }
+ assert m.route_for("gw", "/api/vet/x") is None
+ assert m.route_for("gw", "/api/pay/x") is None
+ assert m.route_for("gw", "/api/visit/x")[0].repo == "b" # type: ignore[index]
+ assert m.route_for("gw", "/api/other")[0].repo == "a" # type: ignore[index]
+ # Blockers draw no edge.
+ edges = {lk.provider_repo for lk in run_matching([], m.routes).service_links}
+ assert edges == {"a", "b"}
+
+
+# ---------------------------------------------------------------------------
+# What the matcher does with them
+# ---------------------------------------------------------------------------
+
+
+def _http(repo: str, role: str, path: str, method: str = "GET", file: str = "", **meta) -> Contract:
+ return Contract(
+ repo=repo,
+ contract_id=f"http::{method}::{path}",
+ contract_type="http",
+ role=role,
+ file_path=file or f"{role}.js",
+ symbol_name=path,
+ confidence=0.85 if role == "provider" else 0.75,
+ meta={"method": method, "path": path, **meta},
+ )
+
+
+def _gateway_map() -> ServiceNameMap:
+ m = ServiceNameMap(repos=frozenset({"gw", "customers", "vets", "web"}))
+ m.entries[("host", "gateway")] = ServiceName("gateway", "host", "gw", "spring_application_name", "gw/app.yml")
+ m.routes = (
+ GatewayRoute("gw", "/api/customer", "", "customers", "customers-service", "spring_gateway", "gw/app.yml"),
+ GatewayRoute("gw", "/api/vet", "", "vets", "vets-service", "spring_gateway", "cfg/gw.yml"),
+ )
+ return m
+
+
+def test_calls_through_a_gateway_link_on_the_forwarded_path() -> None:
+ contracts = [
+ _http("customers", "provider", "/owners/{param}"),
+ _http("vets", "provider", "/vets"),
+ _http("vets", "provider", "/owners/{param}"), # same path, wrong service
+ # The gateway's own page, relative; written twice in one file.
+ _http("gw", "consumer", "/api/customer/owners/{param}", file="Owner.js"),
+ _http("gw", "consumer", "/api/customer/owners/{param}", file="Owner.js"),
+ # Another repo calling the gateway by its host.
+ _http("web", "consumer", "/api/vet/vets", host="gateway"),
+ # Routed, but nothing there serves the path: a service-level edge.
+ _http("gw", "consumer", "/api/vet/specialties", file="Vets.js"),
+ # A relative call from another repo is not routed.
+ _http("web", "consumer", "/api/customer/pets", file="Pets.js"),
+ ]
+ m = _gateway_map()
+ annotate_consumer_targets(contracts, {}, m)
+ assert contracts[3].meta["route_path"] == "/owners/{param}"
+ assert contracts[3].meta["target_repo"] == "customers"
+ assert contracts[3].meta["target_via"] == "spring_gateway"
+ assert "route_path" not in contracts[-1].meta
+
+ state = run_matching(contracts, m.routes)
+ assert [(lk.consumer_repo, lk.provider_repo, lk.contract_id, lk.strategy) for lk in state.links] == [
+ ("gw", "customers", "http::GET::/owners/{param}", LinkStrategy.GATEWAY_ROUTE),
+ ("web", "vets", "http::GET::/vets", LinkStrategy.GATEWAY_ROUTE),
+ ]
+ assert state.links[0].consumer_contract_id == "http::GET::/api/customer/owners/{param}"
+ assert state.links[0].match_type == "exact"
+
+ by_strategy = {(lk.strategy, lk.consumer_repo, lk.provider_repo, lk.consumer_file) for lk in state.service_links}
+ assert by_strategy == {
+ (LinkStrategy.HOST_ONLY, "gw", "vets", "Vets.js"),
+ (LinkStrategy.GATEWAY_ROUTE, "gw", "customers", "app.yml"),
+ # The route file sits in a config repo: the gateway's repo root.
+ (LinkStrategy.GATEWAY_ROUTE, "gw", "vets", ""),
+ }
+
+ graph = build_system_graph(contracts, state.links, CrossRepoOverlay(), {}, service_links=state.service_links)
+ edges = {(e.source, e.target, e.kind) for e in graph.edges}
+ assert edges == {("gw", "customers", "http"), ("gw", "vets", "http"), ("web", "vets", "http")}
+
+
+def test_routes_round_trip_and_stale_route_meta_is_cleared() -> None:
+ m = _gateway_map()
+ again = ServiceNameMap.from_dict(m.to_dict("fp"))
+ assert again.routes == m.routes
+
+ consumer = _http("gw", "consumer", "/api/vet/vets")
+ annotate_consumer_targets([consumer], {}, m)
+ assert consumer.meta["route_path"] == "/vets"
+ annotate_consumer_targets([consumer], {}, ServiceNameMap())
+ assert "route_path" not in consumer.meta and "target_repo" not in consumer.meta
+
+ store = ContractStore(service_links=run_matching([], m.routes).service_links)
+ assert len(ContractStore.from_dict(store.to_dict()).service_links) == 2