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): read Ocelot and YARP gateway routes into the service-name map (#4548)

Raghav Chamadiya7fa03b777bd2
diff --git a/docs/architecture/workspace.md b/docs/architecture/workspace.md
index ba49779e9..214ad4593 100644
--- a/docs/architecture/workspace.md
+++ b/docs/architecture/workspace.md
@@ -424,6 +424,8 @@ add its case to `test_graph_evidence.py`.
than the gateway's is not routed, since nothing says which gateway serves it.
nginx regex locations are not read, and `${VAR}` resolves as an env key only in a
`*.template` / `*.tmpl` file (envsubst); in a plain config it is an nginx variable.
+- YARP routes built in code (`LoadFromMemory`, Aspire `AddYarp`) are not read, and
+ `MapForwarder` only in `Program.cs` / `Startup.cs`.
- 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 07e3a4c3d..4dd44efb6 100644
--- a/docs/reference/WORKSPACE_CONTRACTS.md
+++ b/docs/reference/WORKSPACE_CONTRACTS.md
@@ -132,6 +132,9 @@ records `target_via` (the source) and `target_evidence` (the file).
| `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) |
| `dockerfile_env` | `Dockerfile`, `Dockerfile.*`, `*.Dockerfile` holding `ENV` | `ENV` keys whose value is an address (`CATALOGUE_HOST=catalogue`) | The host the value names |
| `nginx` | `*.conf`, `*.conf.template`, `*.conf.tmpl` holding `proxy_pass` | Prefix `location` blocks with `proxy_pass` to a host, an `upstream` of one host, or an envsubst `${X_HOST}` in a template | A gateway route (below) |
+| `ocelot` | `ocelot*.json`, `configuration.json` holding `UpstreamPathTemplate` | Ocelot `Routes` (or `ReRoutes`): `ServiceName`, or the one host in `DownstreamHostAndPorts` | A gateway route (below) |
+| `yarp` | `appsettings*.json`, `yarp*.json` holding `ReverseProxy` | YARP `Routes` and the one host their cluster's `Destinations` name | A gateway route (below) |
+| `yarp_forwarder` | `Program.cs`, `Startup.cs` holding `MapForwarder` | The destination host of `MapForwarder(pattern, destination[, template])` | A gateway route (below) |
A base path prefixes every Spring route of its module before matching, so `@PostMapping("/users")`
under `context-path: /uaa` is `POST /uaa/users`. A module given two different base paths gets
@@ -154,6 +157,9 @@ a shorter prefix from claiming the paths under it. A call that reaches the gatew
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.
+Ocelot, YARP `PathPattern` and `MapForwarder` templates rewrite the prefix when both
+templates end in the same variables (`/catalog-api/{everything}` to `/{everything}`); any
+other template is a blocker. Blockers alone at one prefix each keep their edge.
## Contracts over REST
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 85cfd400f..79249c2b9 100644
--- a/packages/core/src/repowise/core/workspace/service_names/__init__.py
+++ b/packages/core/src/repowise/core/workspace/service_names/__init__.py
@@ -41,9 +41,12 @@ from . import (
dockerfile,
k8s_service,
nginx,
+ ocelot,
spring,
spring_base_path,
spring_gateway,
+ yarp,
+ yarp_forwarder,
)
from .base import ENV, HOST, Claim, Route, ServiceNameSource, SourceFile
@@ -55,9 +58,12 @@ SOURCES: tuple[ServiceNameSource, ...] = (
dockerfile.SOURCE,
k8s_service.SOURCE,
nginx.SOURCE,
+ ocelot.SOURCE,
spring.SOURCE,
spring_base_path.SOURCE,
spring_gateway.SOURCE,
+ yarp.SOURCE,
+ yarp_forwarder.SOURCE,
)
# Test, example and build-output trees declare services that are not the
@@ -316,6 +322,9 @@ def _settle_routes(
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.
+ Blockers alone at a prefix dispute nothing (each forwards some paths under it,
+ as ``/api/{version}/c/{all}`` and ``/api/{version}/b/{all}`` do), so each keeps
+ its target and its edge.
"""
by_key: dict[tuple[str, str], dict[tuple[str, str | None], GatewayRoute]] = defaultdict(dict)
for f in found:
@@ -324,6 +333,9 @@ def _settle_routes(
by_key[(row.gateway, row.prefix)].setdefault((row.repo, row.upstream), row)
settled: list[GatewayRoute] = []
for (gateway, prefix), ways in sorted(by_key.items()):
+ if all(upstream is None for _, upstream in ways):
+ settled.extend(ways.values())
+ continue
first = next(iter(ways.values()))
if len(ways) > 1:
targets = sorted({t for t, _ in ways})
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 e522e7125..934c0f144 100644
--- a/packages/core/src/repowise/core/workspace/service_names/base.py
+++ b/packages/core/src/repowise/core/workspace/service_names/base.py
@@ -162,6 +162,33 @@ def literal_prefix(pattern: str) -> tuple[str, str]:
return ("/" + "/".join(literal) if literal else ""), EXACT
+def _variable(seg: str) -> str:
+ """A whole-segment variable by name: ``{**rest}``, ``{*rest}`` and ``{rest:int}`` are ``{rest}``."""
+ return "{" + seg[1:-1].lstrip("*").split(":")[0].split("=")[0].rstrip("?").lower() + "}"
+
+
+def template_upstream(pattern: str, forwarded: str) -> str | None:
+ """What a gateway forwarding path template *pattern* as *forwarded* puts in place of
+ *pattern*'s literal prefix, or None when that is not a prefix rewrite.
+
+ ``/api/c/{everything}`` forwarded as ``/{everything}`` is ``""`` (stripped);
+ ``/posts/{id}`` as ``/api/posts/{id}`` is ``/api/posts``. Both must end in the
+ same whole-segment variables, in order. A literal after a variable
+ (``/api/{version}/c/{all}``), a segment mixing text and a variable, or a fully
+ literal pattern (it serves one path, not a prefix) is None.
+ """
+ heads: list[str] = []
+ tails: list[list[str]] = []
+ for template in (pattern, forwarded):
+ head, kind = literal_prefix(template)
+ tail = [s for s in template.strip().split("/") if s][head.count("/") :]
+ if kind != PREFIX or not all(_WHOLE_SEGMENT_RE.match(s) for s in tail):
+ return None
+ heads.append(head)
+ tails.append([_variable(s) for s in tail])
+ return heads[1] if tails[0] == tails[1] else None
+
+
def host_of(key: str, value: str) -> str | None:
"""The host config entry *key* = *value* names, or None when it is not an address.
@@ -190,4 +217,5 @@ __all__ = [
"host_of",
"join_config_path",
"literal_prefix",
+ "template_upstream",
]
diff --git a/packages/core/src/repowise/core/workspace/service_names/json_config.py b/packages/core/src/repowise/core/workspace/service_names/json_config.py
new file mode 100644
index 000000000..76c0e30ec
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/service_names/json_config.py
@@ -0,0 +1,30 @@
+"""A JSON config file as .NET reads it: ``//`` and ``/* */`` comments and trailing commas allowed."""
+
+from __future__ import annotations
+
+import json
+import re
+from typing import Any
+
+_TRAILING_COMMA_RE = re.compile(r",\s*([}\]])")
+
+
+def load_json_config(text: str) -> Any:
+ """The file's value, or None when it does not parse even with comments removed."""
+ try:
+ return json.loads(text)
+ except ValueError:
+ pass
+ from repowise.core.ingestion.tsconfig_resolver import _strip_jsonc_comments
+
+ try:
+ return json.loads(_TRAILING_COMMA_RE.sub(r"\1", _strip_jsonc_comments(text)))
+ except ValueError:
+ return None
+
+
+def field(node: Any, name: str) -> Any:
+ """*node*'s value under *name* (lowercase), case-insensitive as .NET configuration binds it."""
+ if not isinstance(node, dict):
+ return None
+ return next((v for k, v in node.items() if str(k).lower() == name), None)
diff --git a/packages/core/src/repowise/core/workspace/service_names/ocelot.py b/packages/core/src/repowise/core/workspace/service_names/ocelot.py
new file mode 100644
index 000000000..93c28a96f
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/service_names/ocelot.py
@@ -0,0 +1,67 @@
+"""Ocelot routes: which path an Ocelot gateway forwards to which service.
+
+Each entry of ``Routes`` (``ReRoutes`` before Ocelot 16) forwards calls matching
+its ``UpstreamPathTemplate`` to ``DownstreamPathTemplate`` on the service its
+``ServiceName`` (service discovery) or ``DownstreamHostAndPorts`` hosts name.
+``/api/catalog/{everything}`` forwarded as ``/{everything}`` strips the prefix,
+and any pair ending in the same variables rewrites it
+(:func:`.base.template_upstream`). The gateway is the repo holding the file.
+
+A route the reader cannot rewrite through is still stated, with no forwarded
+path, so it keeps a shorter prefix from claiming its calls: a template whose
+variables differ or sit before a literal (``/api/{version}/c/{everything}``),
+a fully literal template (it serves one path, not a prefix), an
+``UpstreamHost`` or ``UpstreamHeaderTemplates`` rule, or a
+``DownstreamHttpMethod`` that changes the verb. ``UpstreamHttpMethod`` is not
+read: a routed call links only to a provider that serves its own verb. A
+catch-all ``/{everything}`` is skipped, and so are ``Aggregates`` and
+``DynamicRoutes``.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterable
+
+from .base import Claim, Route, ServiceNameSource, SourceFile, literal_prefix, template_upstream
+from .json_config import field, load_json_config
+
+#: Rules that narrow which calls take a route, or change the verb it forwards.
+_UNREAD = ("upstreamhost", "upstreamheadertemplates", "downstreamhttpmethod")
+
+
+def _target(route: dict) -> str:
+ """The service a route forwards to: its ``ServiceName``, else its one downstream host."""
+ service = field(route, "servicename")
+ if isinstance(service, str) and service.strip():
+ return service.strip().lower()
+ entries = field(route, "downstreamhostandports")
+ hosts = {
+ str(field(h, "host") or "").strip().lower()
+ for h in (entries if isinstance(entries, list) else [])
+ if isinstance(h, dict)
+ }
+ return hosts.pop() if len(hosts) == 1 else "" # several hosts are no one service
+
+
+def read(file: SourceFile) -> Iterable[Claim]:
+ config = load_json_config(file.text)
+ routes = field(config, "routes") or field(config, "reroutes")
+ for route in routes if isinstance(routes, list) else ():
+ upstream, downstream = field(route, "upstreampathtemplate"), field(route, "downstreampathtemplate")
+ if not isinstance(upstream, str) or not isinstance(downstream, str):
+ continue
+ prefix, _ = literal_prefix(upstream)
+ if not prefix:
+ continue # a catch-all is never more specific than a real route
+ readable = not any(field(route, k) for k in _UNREAD)
+ forwarded = template_upstream(upstream, downstream) if readable else None
+ yield Claim(name=_target(route), route=Route(prefix, forwarded))
+
+
+SOURCE = ServiceNameSource(
+ name="ocelot",
+ # ``ocelot.json``, its environment and merge files, and the older ``configuration.json``.
+ filenames=("ocelot*.json", "configuration.json"),
+ marker="UpstreamPathTemplate",
+ read=read,
+)
diff --git a/packages/core/src/repowise/core/workspace/service_names/yarp.py b/packages/core/src/repowise/core/workspace/service_names/yarp.py
new file mode 100644
index 000000000..ab4bfaf5e
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/service_names/yarp.py
@@ -0,0 +1,134 @@
+"""YARP ``ReverseProxy`` config: which path a YARP gateway forwards to which service.
+
+Each route under ``ReverseProxy:Routes`` sends calls matching ``Match:Path``
+(``/api/catalog/{**catch-all}``) to its ``ClusterId``; the cluster's
+``Destinations`` addresses name the service (``http://catalog-api``, or Aspire's
+``https+http://catalog-api``) and any base path the forwarded path is appended
+to. ``PathRemovePrefix``, ``PathPrefix`` and a ``PathPattern`` ending in the
+route's own variables (:func:`.base.template_upstream`) shape what is
+forwarded. The gateway is the repo holding the file.
+
+A route the reader cannot rewrite through is still stated, with no forwarded
+path, so it keeps a shorter prefix from claiming its calls: a ``Path`` not
+ending in a catch-all (``{id}`` matches one segment, not a prefix), a ``Hosts``, ``Headers`` or ``QueryParameters``
+match, ``PathSet`` or another path transform, a ``PathRemovePrefix`` reaching
+into the wildcard part, or destinations with different base paths. A cluster
+whose destinations name several hosts has no one target. ``Methods`` is not
+read: a routed call links only to a provider that serves its own verb. A
+catch-all ``{**catch-all}`` is skipped. Ceiling: routes built in code
+(``LoadFromMemory``, Aspire ``AddYarp(...).WithConfiguration``) are not read.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterable, Iterator
+from typing import Any
+from urllib.parse import urlsplit
+
+from .base import (
+ PREFIX,
+ Claim,
+ Route,
+ ServiceNameSource,
+ SourceFile,
+ host_of,
+ literal_prefix,
+ template_upstream,
+)
+from .json_config import field, load_json_config
+
+#: Match rules that narrow which calls take a route.
+_NARROWING = ("hosts", "headers", "queryparameters")
+
+
+def _values(node: Any) -> list[Any]:
+ """A config section's entries: a dict's values, or a list (older YARP configs)."""
+ if isinstance(node, dict):
+ return list(node.values())
+ return node if isinstance(node, list) else []
+
+
+def _path(value: Any) -> str:
+ return "/" + str(value).strip().strip("/").lower() if str(value).strip("/ ") else ""
+
+
+def base_path(address: str) -> str | None:
+ """The path a destination address carries (``""`` for none), None when it does not parse."""
+ try:
+ return _path(urlsplit(address).path)
+ except ValueError:
+ return None
+
+
+def catch_all(pattern: str) -> bool:
+ """True when a YARP pattern ends in a catch-all (``{**rest}``, ``{*rest}``): only that
+ matches every path under its prefix, while ``{id}`` matches one segment."""
+ segments = [s for s in pattern.strip().split("/") if s]
+ return bool(segments) and segments[-1].startswith("{*")
+
+
+def _destination(cluster: Any) -> tuple[str, str | None]:
+ """The one host a cluster's destinations name (``""`` if none or several), and their
+ one base path (None when they differ)."""
+ addresses = [str(field(d, "address") or "") for d in _values(field(cluster, "destinations"))]
+ hosts = {host_of("address", a) or "" for a in addresses}
+ bases = {base_path(a) for a in addresses}
+ host = hosts.pop() if len(hosts) == 1 else ""
+ return host, (bases.pop() if len(bases) == 1 else None)
+
+
+def _forwarded(pattern: str, prefix: str, transforms: Any) -> str | None:
+ """What *prefix* is forwarded as after the route's path transforms, or None."""
+ current = prefix
+ for transform in _values(transforms):
+ for key, value in (transform.items() if isinstance(transform, dict) else ()):
+ key = str(key).lower()
+ if key == "pathremoveprefix":
+ strip = _path(value)
+ if strip.startswith(current + "/"):
+ return None # removes part of the wildcard: the rest is unknown
+ if current == strip or current.startswith(strip + "/"):
+ current = current[len(strip) :]
+ elif key == "pathprefix":
+ current = _path(value) + current
+ elif key == "pathpattern":
+ if (current := template_upstream(pattern, str(value))) is None: # type: ignore[assignment]
+ return None
+ elif key.startswith("path"):
+ return None # PathSet, or a path transform not read
+ return current
+
+
+def _routes(proxy: Any) -> Iterator[Claim]:
+ section = field(proxy, "clusters")
+ clusters = {str(k).lower(): v for k, v in section.items()} if isinstance(section, dict) else {}
+ for route in _values(field(proxy, "routes")):
+ match = field(route, "match")
+ pattern = field(match, "path")
+ if not isinstance(pattern, str):
+ continue
+ prefix, kind = literal_prefix(pattern)
+ if not prefix:
+ continue # a catch-all is never more specific than a real route
+ host, base = _destination(clusters.get(str(field(route, "clusterid") or "").lower()))
+ readable = (
+ kind == PREFIX
+ and catch_all(pattern)
+ and base is not None
+ and not any(field(match, k) for k in _NARROWING)
+ )
+ forwarded = _forwarded(pattern, prefix, field(route, "transforms")) if readable else None
+ upstream = None if forwarded is None else (base or "") + forwarded
+ yield Claim(name=host, route=Route(prefix, upstream))
+
+
+def read(file: SourceFile) -> Iterable[Claim]:
+ yield from _routes(field(load_json_config(file.text), "reverseproxy"))
+
+
+SOURCE = ServiceNameSource(
+ name="yarp",
+ filenames=("appsettings*.json", "yarp*.json"),
+ marker="ReverseProxy",
+ read=read,
+)
diff --git a/packages/core/src/repowise/core/workspace/service_names/yarp_forwarder.py b/packages/core/src/repowise/core/workspace/service_names/yarp_forwarder.py
new file mode 100644
index 000000000..05865f1dc
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/service_names/yarp_forwarder.py
@@ -0,0 +1,63 @@
+"""YARP direct forwarding: ``app.MapForwarder(pattern, destination[, targetTemplate])``.
+
+``MapForwarder("/api/{**rest}", "http://catalog-api")`` forwards calls under
+``/api`` unchanged to the service the destination names (Aspire's
+``https+http://`` scheme included), after any base path it carries; a target
+template ending in the pattern's own variables rewrites the prefix
+(:func:`.base.template_upstream`). The gateway is the repo holding the file.
+
+A forwarder the reader cannot rewrite through is still stated, with no
+forwarded path: a pattern not ending in a catch-all (``{**rest}``), a template that moves or adds
+segments (``/product-images/{id}`` to ``/api/catalog/items/{id}/pic``), or any
+other third argument (a request config or transformer). Only string literals
+are read, and only in ``Program.cs`` and ``Startup.cs``, where endpoints are
+mapped; widening that gate is one glob.
+"""
+
+from __future__ import annotations
+
+import re
+from collections.abc import Iterable
+
+from .base import (
+ PREFIX,
+ Claim,
+ Route,
+ ServiceNameSource,
+ SourceFile,
+ host_of,
+ literal_prefix,
+ template_upstream,
+)
+from .yarp import base_path, catch_all
+
+_FORWARDER_RE = re.compile(
+ r"\.MapForwarder\s*\(\s*@?\"([^\"]*)\"\s*,\s*@?\"([^\"]*)\"\s*(?:,\s*@?\"([^\"]*)\"\s*)?([,)])"
+)
+
+
+def read(file: SourceFile) -> Iterable[Claim]:
+ for m in _FORWARDER_RE.finditer(file.text):
+ line = file.text[file.text.rfind("\n", 0, m.start()) + 1 : m.start()]
+ if line.lstrip().startswith(("//", "/*", "*")):
+ continue # commented out
+ pattern, destination, template, end = m.groups()
+ prefix, kind = literal_prefix(pattern)
+ if not prefix:
+ continue # a catch-all is never more specific than a real route
+ upstream: str | None = None
+ base = base_path(destination)
+ if end == ")" and kind == PREFIX and catch_all(pattern) and base is not None:
+ upstream = prefix if template is None else template_upstream(pattern, template)
+ yield Claim(
+ name=host_of("destination", destination) or "",
+ route=Route(prefix, None if upstream is None or base is None else base + upstream),
+ )
+
+
+SOURCE = ServiceNameSource(
+ name="yarp_forwarder",
+ filenames=("Program.cs", "Startup.cs"),
+ marker="MapForwarder",
+ read=read,
+)
diff --git a/tests/fixtures/service_names/eshop/webapp/Program.cs b/tests/fixtures/service_names/eshop/webapp/Program.cs
new file mode 100644
index 000000000..fe2026e73
--- /dev/null
+++ b/tests/fixtures/service_names/eshop/webapp/Program.cs
@@ -0,0 +1,34 @@
+using eShop.WebApp.Components;
+using eShop.ServiceDefaults;
+
+var builder = WebApplication.CreateBuilder(args);
+
+builder.AddServiceDefaults();
+
+builder.Services.AddRazorComponents().AddInteractiveServerComponents();
+
+builder.AddApplicationServices();
+
+var app = builder.Build();
+
+app.MapDefaultEndpoints();
+
+// Configure the HTTP request pipeline.
+if (!app.Environment.IsDevelopment())
+{
+ app.UseExceptionHandler("/Error");
+ // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
+ app.UseHsts();
+}
+
+app.UseAntiforgery();
+
+app.UseHttpsRedirection();
+
+app.UseStaticFiles();
+
+app.MapRazorComponents<App>().AddInteractiveServerRenderMode();
+
+app.MapForwarder("/product-images/{id}", "https+http://catalog-api", "/api/catalog/items/{id}/pic");
+
+app.Run();
diff --git a/tests/fixtures/service_names/eshoponc/basket.api/.keep b/tests/fixtures/service_names/eshoponc/basket.api/.keep
new file mode 100644
index 000000000..e69de29bb
diff --git a/tests/fixtures/service_names/eshoponc/catalog.api/.keep b/tests/fixtures/service_names/eshoponc/catalog.api/.keep
new file mode 100644
index 000000000..e69de29bb
diff --git a/tests/fixtures/service_names/eshoponc/ordering.api/.keep b/tests/fixtures/service_names/eshoponc/ordering.api/.keep
new file mode 100644
index 000000000..e69de29bb
diff --git a/tests/fixtures/service_names/eshoponc/ordering.signalrhub/.keep b/tests/fixtures/service_names/eshoponc/ordering.signalrhub/.keep
new file mode 100644
index 000000000..e69de29bb
diff --git a/tests/fixtures/service_names/eshoponc/payment.api/.keep b/tests/fixtures/service_names/eshoponc/payment.api/.keep
new file mode 100644
index 000000000..e69de29bb
diff --git a/tests/fixtures/service_names/eshoponc/web.bff.shopping/apigw/configuration.json b/tests/fixtures/service_names/eshoponc/web.bff.shopping/apigw/configuration.json
new file mode 100644
index 000000000..b3e01d773
--- /dev/null
+++ b/tests/fixtures/service_names/eshoponc/web.bff.shopping/apigw/configuration.json
@@ -0,0 +1,130 @@
+{
+ "ReRoutes": [
+ {
+ "DownstreamPathTemplate": "/api/{version}/{everything}",
+ "DownstreamScheme": "http",
+ "DownstreamHostAndPorts": [
+ {
+ "Host": "catalog.api",
+ "Port": 80
+ }
+ ],
+ "UpstreamPathTemplate": "/api/{version}/c/{everything}",
+ "UpstreamHttpMethod": [ "GET" ]
+ },
+ {
+ "DownstreamPathTemplate": "/api/{version}/{everything}",
+ "DownstreamScheme": "http",
+ "DownstreamHostAndPorts": [
+ {
+ "Host": "basket.api",
+ "Port": 80
+ }
+ ],
+ "UpstreamPathTemplate": "/api/{version}/b/{everything}",
+ "UpstreamHttpMethod": [],
+ "AuthenticationOptions": {
+ "AuthenticationProviderKey": "IdentityApiKey",
+ "AllowedScopes": []
+ }
+ },
+ {
+ "DownstreamPathTemplate": "/api/{version}/{everything}",
+ "DownstreamScheme": "http",
+ "DownstreamHostAndPorts": [
+ {
+ "Host": "ordering.api",
+ "Port": 80
+ }
+ ],
+ "UpstreamPathTemplate": "/api/{version}/o/{everything}",
+ "UpstreamHttpMethod": [],
+ "AuthenticationOptions": {
+ "AuthenticationProviderKey": "IdentityApiKey",
+ "AllowedScopes": []
+ }
+ },
+ {
+ "DownstreamPathTemplate": "/{everything}",
+ "DownstreamScheme": "http",
+ "DownstreamHostAndPorts": [
+ {
+ "Host": "webshoppingagg",
+ "Port": 80
+ }
+ ],
+ "UpstreamPathTemplate": "/{everything}",
+ "UpstreamHttpMethod": [ "POST", "PUT", "GET" ],
+ "AuthenticationOptions": {
+ "AuthenticationProviderKey": "IdentityApiKey",
+ "AllowedScopes": []
+ }
+ },
+ {
+ "DownstreamPathTemplate": "/{everything}",
+ "DownstreamScheme": "http",
+ "DownstreamHostAndPorts": [
+ {
+ "Host": "ordering.api",
+ "Port": 80
+ }
+ ],
+ "UpstreamPathTemplate": "/orders-api/{everything}",
+ "UpstreamHttpMethod": []
+ },
+ {
+ "DownstreamPathTemplate": "/{everything}",
+ "DownstreamScheme": "http",
+ "DownstreamHostAndPorts": [
+ {
+ "Host": "ordering.signalrhub",
+ "Port": 80
+ }
+ ],
+ "UpstreamPathTemplate": "/hub/{everything}",
+ "UpstreamHttpMethod": []
+ },
+ {
+ "DownstreamPathTemplate": "/{everything}",
+ "DownstreamScheme": "http",
+ "DownstreamHostAndPorts": [
+ {
+ "Host": "basket.api",
+ "Port": 80
+ }
+ ],
+ "UpstreamPathTemplate": "/basket-api/{everything}",
+ "UpstreamHttpMethod": []
+ },
+ {
+ "DownstreamPathTemplate": "/{everything}",
+ "DownstreamScheme": "http",
+ "DownstreamHostAndPorts": [
+ {
+ "Host": "catalog.api",
+ "Port": 80
+ }
+ ],
+ "UpstreamPathTemplate": "/catalog-api/{everything}",
+ "UpstreamHttpMethod": []
+ },
+ {
+ "DownstreamPathTemplate": "/{everything}",
+ "DownstreamScheme": "http",
+ "DownstreamHostAndPorts": [
+ {
+ "Host": "payment.api",
+ "Port": 80
+ }
+ ],
+ "UpstreamPathTemplate": "/payment-api/{everything}",
+ "UpstreamHttpMethod": []
+ }
+
+ ],
+ "GlobalConfiguration": {
+ "RequestIdKey": "OcRequestId",
+ "AdministrationPath": "/administration"
+ }
+ }
+
\ No newline at end of file
diff --git a/tests/unit/workspace/test_ocelot_yarp_routes.py b/tests/unit/workspace/test_ocelot_yarp_routes.py
new file mode 100644
index 000000000..6530886da
--- /dev/null
+++ b/tests/unit/workspace/test_ocelot_yarp_routes.py
@@ -0,0 +1,200 @@
+"""Ocelot routes, YARP ``ReverseProxy`` config and ``MapForwarder`` in the service-name map."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from repowise.core.workspace.contracts import Contract
+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 (
+ ServiceNameMap,
+ build_service_name_map,
+ ocelot,
+ yarp,
+ yarp_forwarder,
+)
+from repowise.core.workspace.service_names.base import Route, SourceFile, template_upstream
+
+FIXTURES = Path(__file__).resolve().parents[2] / "fixtures" / "service_names"
+ESHOPONC = ("web.bff.shopping", "catalog.api", "basket.api", "ordering.api", "ordering.signalrhub", "payment.api")
+
+
+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(module, text: str, name: str) -> list[tuple[str, Route]]:
+ return [(c.name, c.route) for c in module.read(SourceFile(Path(name), text)) if c.route]
+
+
+def _http(repo: str, role: str, method: str, path: str) -> Contract:
+ return Contract(
+ repo=repo,
+ contract_id=f"http::{method}::{path}",
+ contract_type="http",
+ role=role,
+ file_path=f"{role}.cs",
+ symbol_name=path,
+ confidence=0.85 if role == "provider" else 0.75,
+ meta={"method": method, "path": path},
+ )
+
+
+ ("pattern", "forwarded", "expected"),
+ [
+ ("/catalog-api/{everything}", "/{everything}", ""),
+ ("/posts/{id}", "/api/posts/{id}", "/api/posts"),
+ ("/api/{**catch-all}", "/v2/{**catch-all}", "/v2"),
+ ("/api/{*rest}", "/v2/{**rest}", "/v2"), # one variable, two spellings
+ ("/a/{x}/{y}", "/b/{y}/{x}", None), # reordered
+ ("/api/{version}/c/{everything}", "/api/{version}/{everything}", None), # literal after a variable
+ ("/product-images/{id}", "/api/catalog/items/{id}/pic", None),
+ ("/values", "/api/values", None), # one path, not a prefix
+ ("/files/{name}.json", "/{name}.json", None),
+ ],
+)
+def test_template_upstream(pattern: str, forwarded: str, expected: str | None) -> None:
+ assert template_upstream(pattern, forwarded) == expected
+
+
+def test_eshoponcontainers_ocelot_gateway_routes_each_service() -> None:
+ root = FIXTURES / "eshoponc"
+ m = build_service_name_map({a: root / a for a in ESHOPONC}, root)
+ assert _routes(m) == {
+ # /api/{version}/<letter>/{everything}: three routes under one literal prefix,
+ # none a prefix rewrite. Blockers dispute nothing, so each keeps its edge.
+ ("web.bff.shopping", "/api", None, "catalog.api"),
+ ("web.bff.shopping", "/api", None, "basket.api"),
+ ("web.bff.shopping", "/api", None, "ordering.api"),
+ ("web.bff.shopping", "/orders-api", "", "ordering.api"),
+ ("web.bff.shopping", "/hub", "", "ordering.signalrhub"),
+ ("web.bff.shopping", "/basket-api", "", "basket.api"),
+ ("web.bff.shopping", "/catalog-api", "", "catalog.api"),
+ ("web.bff.shopping", "/payment-api", "", "payment.api"),
+ }
+ contracts = [
+ _http("catalog.api", "provider", "GET", "/api/v1/catalog/items"),
+ _http("web.bff.shopping", "consumer", "GET", "/catalog-api/api/v1/catalog/items"),
+ _http("web.bff.shopping", "consumer", "GET", "/api/v1/c/catalog/items"), # not rewritten
+ ]
+ annotate_consumer_targets(contracts, {}, m)
+ assert contracts[1].meta["route_path"] == "/api/v1/catalog/items"
+ assert "route_path" not in contracts[2].meta
+ state = run_matching(contracts, m.routes)
+ assert [(lk.consumer_repo, lk.provider_repo, lk.strategy) for lk in state.links] == [
+ ("web.bff.shopping", "catalog.api", LinkStrategy.GATEWAY_ROUTE)
+ ]
+ assert {lk.provider_repo for lk in state.service_links} == set(ESHOPONC[1:])
+
+
+def test_ocelot_route_shapes() -> None:
+ text = """{
+ // Ocelot 16 renamed ReRoutes; both are read.
+ "Routes": [
+ {"UpstreamPathTemplate": "/api/orders/{everything}", "DownstreamPathTemplate": "/{everything}",
+ "UpstreamHttpMethod": ["Get"], "DownstreamHostAndPorts": [{"Host": "Ordering", "Port": 80}]},
+ {"UpstreamPathTemplate": "/api/c/{all}", "DownstreamPathTemplate": "/api/{all}",
+ "ServiceName": "catalog", "DownstreamHostAndPorts": [{"Host": "localhost", "Port": 1}]},
+ {"UpstreamPathTemplate": "/api/pool/{all}", "DownstreamPathTemplate": "/{all}",
+ "DownstreamHostAndPorts": [{"Host": "a", "Port": 80}, {"Host": "b", "Port": 80}]},
+ {"UpstreamPathTemplate": "/api/host/{all}", "DownstreamPathTemplate": "/{all}",
+ "UpstreamHost": "shop.example.com", "ServiceName": "basket"},
+ {"UpstreamPathTemplate": "/api/verb/{all}", "DownstreamPathTemplate": "/{all}",
+ "DownstreamHttpMethod": "POST", "ServiceName": "basket"},
+ {"UpstreamPathTemplate": "/{everything}", "DownstreamPathTemplate": "/{everything}",
+ "ServiceName": "web"},
+ ],
+ }"""
+ assert _read(ocelot, text, "ocelot.json") == [
+ ("ordering", Route("/api/orders", "")),
+ ("catalog", Route("/api/c", "/api")), # service discovery wins over hosts
+ ("", Route("/api/pool", "")), # two hosts: no one service
+ ("basket", Route("/api/host", None)),
+ ("basket", Route("/api/verb", None)),
+ ]
+ assert _read(ocelot, '{"ReRoutes": [{"UpstreamPathTemplate": "/x/{a}", '
+ '"DownstreamPathTemplate": "/{a}", "ServiceName": "x"}]}', "configuration.json") == [
+ ("x", Route("/x", ""))
+ ]
+ assert _read(ocelot, "{ not json", "ocelot.json") == []
+
+
+def test_yarp_route_shapes() -> None:
+ text = """{
+ "Logging": {},
+ "ReverseProxy": {
+ "Routes": {
+ "catalog": {"ClusterId": "catalog", "Match": {"Path": "/catalog/{**catch-all}"},
+ "Transforms": [{"PathRemovePrefix": "/catalog"}, {"RequestHeader": "X", "Set": "1"}]},
+ "basket": {"ClusterId": "basket", "Match": {"Path": "/basket/{**rest}", "Methods": ["GET"]},
+ "Transforms": [{"PathPattern": "/api/v1/basket/{**rest}"}]},
+ "prefixed": {"ClusterId": "Basket", "Match": {"Path": "/b2/{**rest}"},
+ "Transforms": [{"PathPrefix": "/v2"}]},
+ "deep": {"ClusterId": "catalog", "Match": {"Path": "/c2/{**rest}"},
+ "Transforms": [{"PathRemovePrefix": "/c2/items"}]},
+ "set": {"ClusterId": "catalog", "Match": {"Path": "/set/{**rest}"},
+ "Transforms": [{"PathSet": "/x"}]},
+ "hosted": {"ClusterId": "catalog", "Match": {"Path": "/h/{**rest}", "Hosts": ["a.example.com"]}},
+ "exact": {"ClusterId": "catalog", "Match": {"Path": "/health"}},
+ "pool": {"ClusterId": "pool", "Match": {"Path": "/pool/{**rest}"}},
+ "one": {"ClusterId": "catalog", "Match": {"Path": "/posts/{id}"},
+ "Transforms": [{"PathPattern": "/api/posts/{id}"}]},
+ "bad": {"ClusterId": "bad", "Match": {"Path": "/bad/{**rest}"}},
+ "all": {"ClusterId": "catalog", "Match": {"Path": "{**catch-all}"}},
+ },
+ "Clusters": {
+ "catalog": {"Destinations": {"d1": {"Address": "https+http://catalog-api"}}},
+ "basket": {"Destinations": {"d1": {"Address": "http://basket-api:8080/base/"}}},
+ "pool": {"Destinations": {"a": {"Address": "http://a/"}, "b": {"Address": "http://b/"}}},
+ "bad": {"Destinations": {"d1": {"Address": "http://[bad"}}},
+ },
+ },
+ }"""
+ assert _read(yarp, text, "appsettings.json") == [
+ ("catalog-api", Route("/catalog", "")),
+ ("basket-api", Route("/basket", "/base/api/v1/basket")),
+ ("basket-api", Route("/b2", "/base/v2/b2")), # cluster ids bind case-insensitively
+ ("catalog-api", Route("/c2", None)), # removes part of the wildcard
+ ("catalog-api", Route("/set", None)),
+ ("catalog-api", Route("/h", None)),
+ ("catalog-api", Route("/health", None)),
+ ("", Route("/pool", "/pool")), # two hosts: no one service
+ ("catalog-api", Route("/posts", None)), # {id} matches one segment, not a prefix
+ ("", Route("/bad", None)), # an address that does not parse
+ ]
+
+
+def test_eshop_map_forwarder_is_a_gateway_edge_without_a_rewrite() -> None:
+ root = FIXTURES / "eshop"
+ m = build_service_name_map({a: root / a for a in ("webapp", "catalog.api", "eshop.apphost")}, root)
+ # /product-images/{id} goes out as /api/catalog/items/{id}/pic: not a prefix rewrite.
+ assert _routes(m) == {("webapp", "/product-images", None, "catalog.api")}
+ [route] = m.routes
+ assert (route.name, route.source, route.file) == ("catalog-api", "yarp_forwarder", "webapp/Program.cs")
+ state = run_matching([], m.routes)
+ assert [(lk.consumer_repo, lk.provider_repo, lk.strategy) for lk in state.service_links] == [
+ ("webapp", "catalog.api", LinkStrategy.GATEWAY_ROUTE)
+ ]
+
+
+def test_map_forwarder_shapes() -> None:
+ text = """
+ app.MapForwarder("/api/{**rest}", "http://catalog:8080");
+ app.MapForwarder("/v1/{**rest}", "http://catalog/base", "/v2/{**rest}");
+ app.MapForwarder("/cfg/{**rest}", "http://catalog", requestConfig);
+ // app.MapForwarder("/old/{**rest}", "http://catalog");
+ app.MapForwarder("/{**rest}", "http://catalog");
+ app.MapForwarder("/one/{id}", "http://catalog");
+ var u = "http://x"; app.MapForwarder("/same-line/{**rest}", "http://catalog");
+ """
+ assert _read(yarp_forwarder, text, "Program.cs") == [
+ ("catalog", Route("/api", "/api")), # forwarded unchanged
+ ("catalog", Route("/v1", "/base/v2")),
+ ("catalog", Route("/cfg", None)),
+ ("catalog", Route("/one", None)),
+ ("catalog", Route("/same-line", "/same-line")),
+ ]