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): apply Spring context-path and WebFlux base-path to provider routes, keep root routes (#4549)

Raghav Chamadiya255eaaf905df
diff --git a/docs/architecture/workspace.md b/docs/architecture/workspace.md
index f1e017bf6..ba49779e9 100644
--- a/docs/architecture/workspace.md
+++ b/docs/architecture/workspace.md
@@ -118,6 +118,9 @@ links are appended after it.
settle into one `name -> repo` entry; a name claimed for two repos is left
unmapped. The sources and their rules are in
[WORKSPACE_CONTRACTS.md](../reference/WORKSPACE_CONTRACTS.md#service-names).
+ A server base path (a Spring context-path) settles per repo module instead, and
+ `matching/base_paths.py::apply_base_paths` prefixes that module's routes before
+ matching, keeping the declared path in `meta` so a re-run recomputes it.
2. **Target resolution** (`matching/http.py::annotate_consumer_targets`): each HTTP
consumer's host or base token is resolved, in order, through a
`contracts.service_bases` entry, a repo alias (also the leading label of an
diff --git a/docs/reference/WORKSPACE_CONTRACTS.md b/docs/reference/WORKSPACE_CONTRACTS.md
index 860e18a13..07e3a4c3d 100644
--- a/docs/reference/WORKSPACE_CONTRACTS.md
+++ b/docs/reference/WORKSPACE_CONTRACTS.md
@@ -128,10 +128,15 @@ 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_base_path` | `.yml`, `.yaml`, `.properties` under `resources/`, `config/`, `configs/` or `shared/` | `server.servlet.context-path`, `server.context-path`, `spring.webflux.base-path`: a base path, not a name | A module's own `src/main/resources/application` or `bootstrap` file (not a profile file): that module. A config server's `<app>.yml`: the service named `<app>` |
| `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) |
+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
+none.
+
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
diff --git a/packages/core/src/repowise/core/workspace/contracts.py b/packages/core/src/repowise/core/workspace/contracts.py
index 1d84caa8d..d7dec572d 100644
--- a/packages/core/src/repowise/core/workspace/contracts.py
+++ b/packages/core/src/repowise/core/workspace/contracts.py
@@ -590,6 +590,7 @@ async def run_contract_extraction(
from .extractors.base import make_exclude_predicate
from .extractors.masstransit import MessageTypeIndex
from .matching import annotate_consumer_targets, run_matching
+ from .matching.base_paths import apply_base_paths
from .service_names import ServiceNameMap, build_service_name_map, service_names_fingerprint
contract_config = ws_config.contracts
@@ -671,6 +672,7 @@ async def run_contract_extraction(
names = ServiceNameMap.from_dict(prior.service_names)
else:
names = await asyncio.to_thread(build_service_name_map, repo_paths, workspace_root)
+ apply_base_paths(all_contracts, names.base_paths)
annotate_consumer_targets(all_contracts, contract_config.service_bases, names)
matched = run_matching(all_contracts, names.routes)
links = matched.links
diff --git a/packages/core/src/repowise/core/workspace/extractors/http/dialect.py b/packages/core/src/repowise/core/workspace/extractors/http/dialect.py
index ebe031850..2a5e51ecf 100644
--- a/packages/core/src/repowise/core/workspace/extractors/http/dialect.py
+++ b/packages/core/src/repowise/core/workspace/extractors/http/dialect.py
@@ -84,18 +84,19 @@ def build_provider_contract(
) -> Contract | None:
"""Build a provider contract, or ``None`` if the path is unusable.
- A match whose path normalizes to bare ``/`` only counts when the raw text
- actually carried a path — a template-variable-only or empty route is
- dropped, matching the legacy extractor's skip rule.
+ An empty path is dropped: with no prefix to stitch onto, nothing was
+ declared. A root route spelled ``/`` is kept; a service whose whole API is
+ ``POST /`` serves it there, and a base path applied later (a Spring
+ context-path) turns it into ``/accounts``.
*handler* is the expression the registration names, for frameworks that
declare a route away from its handler (an ASP.NET minimal API). It is what
lets :func:`.contracts.bind_symbol_ids` reach the handler rather than the
registration site; without it the line lookup binds to ``Program.cs``.
"""
- norm_path = normalize_http_path(path_raw)
- if (not norm_path or norm_path == "/") and not path_raw.strip("/"):
+ if not path_raw.strip():
return None
+ norm_path = normalize_http_path(path_raw)
return build_contract(
ctx,
diff --git a/packages/core/src/repowise/core/workspace/extractors/http/paths.py b/packages/core/src/repowise/core/workspace/extractors/http/paths.py
index e1b61866b..9585e6b56 100644
--- a/packages/core/src/repowise/core/workspace/extractors/http/paths.py
+++ b/packages/core/src/repowise/core/workspace/extractors/http/paths.py
@@ -47,6 +47,9 @@ def normalize_http_path(path: str) -> str:
s = re.sub(r"\[[^\]]+\]", "{param}", s)
# Unify JS template literal ${expr} → {param}
s = re.sub(r"\$\{[^}]+\}", "{param}", s)
+ # A whole-segment ``*`` (Spring ``/owners/*/pets``, Express ``/files/*``)
+ # matches one segment, as a parameter does.
+ s = re.sub(r"(?<=/)\*(?=/|$)", "{param}", s)
return s or "/"
diff --git a/packages/core/src/repowise/core/workspace/extractors/http/spring.py b/packages/core/src/repowise/core/workspace/extractors/http/spring.py
index 32f13cad2..f127a3520 100644
--- a/packages/core/src/repowise/core/workspace/extractors/http/spring.py
+++ b/packages/core/src/repowise/core/workspace/extractors/http/spring.py
@@ -49,7 +49,8 @@ class SpringDialect:
c = build_provider_contract(
ctx,
method=route.verb,
- path_raw=compose_prefix(prefix, route.path),
+ # An empty mapping on an unmapped class is the root route.
+ path_raw=compose_prefix(prefix, route.path) or "/",
framework="spring",
line=line_at(content, route.offset),
)
diff --git a/packages/core/src/repowise/core/workspace/matching/base_paths.py b/packages/core/src/repowise/core/workspace/matching/base_paths.py
new file mode 100644
index 000000000..45ce372b1
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/matching/base_paths.py
@@ -0,0 +1,70 @@
+"""Server base paths applied to the routes they prefix, before matching.
+
+A Spring service with ``server.servlet.context-path: /uaa`` declares
+``@PostMapping("/users")`` and serves ``POST /uaa/users``; its callers name the
+full path. The base path is often set in another repo (a config server's
+``auth-service.yml``), so it is applied here, once the service-name map has
+placed it, rather than at extraction.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from repowise.core.workspace.extractors.http.mounts import compose_prefix
+from repowise.core.workspace.extractors.http.paths import normalize_http_path
+
+if TYPE_CHECKING:
+ from collections.abc import Iterable
+
+ from repowise.core.workspace.contracts import Contract
+ from repowise.core.workspace.service_names import BasePath
+
+#: Frameworks a Spring base path prefixes. Ceiling: JAX-RS under Spring Boot
+#: (Jersey) and Micronaut's own ``micronaut.server.context-path`` are not read.
+_FRAMEWORKS = frozenset({"spring"})
+#: The path a provider declared, kept so a re-run recomputes rather than stacks.
+DECLARED_PATH = "declared_path"
+
+
+def _base_path_for(contract: Contract, by_repo: dict[str, list[BasePath]]) -> str:
+ """The base path of the deepest module holding *contract*'s file, ``""`` when none."""
+ best: BasePath | None = None
+ for b in by_repo.get(contract.repo, ()):
+ inside = not b.module or contract.file_path.startswith(b.module + "/")
+ if inside and (best is None or len(b.module) > len(best.module)):
+ best = b
+ return best.path if best is not None else ""
+
+
+def _declared_path(c: Contract) -> str | None:
+ """The path a Spring route provider declared, None for any other contract."""
+ if c.role != "provider" or c.contract_type != "http" or "method" not in c.meta:
+ return None
+ if c.meta.get("framework") not in _FRAMEWORKS:
+ return None
+ return c.meta.get(DECLARED_PATH, c.meta.get("path"))
+
+
+def apply_base_paths(contracts: list[Contract], base_paths: Iterable[BasePath]) -> None:
+ """Prefix each Spring provider route with its module's base path, in place.
+
+ Idempotent: a stored contract carried into the next run keeps the path it
+ declared in ``meta["declared_path"]``, and its id is rebuilt from that, so a
+ base path that changed or went away is applied fresh rather than stacked.
+ """
+ by_repo: dict[str, list[BasePath]] = {}
+ for b in base_paths:
+ by_repo.setdefault(b.repo, []).append(b)
+ for c in contracts:
+ declared = _declared_path(c)
+ if declared is None:
+ continue
+ base = _base_path_for(c, by_repo)
+ path = normalize_http_path(compose_prefix(base, declared)) if base else declared
+ c.contract_id = f"http::{c.meta['method']}::{path}"
+ c.meta["path"] = path
+ if base:
+ c.meta[DECLARED_PATH] = declared
+ else:
+ c.meta.pop(DECLARED_PATH, None)
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 db7bf6e71..85cfd400f 100644
--- a/packages/core/src/repowise/core/workspace/service_names/__init__.py
+++ b/packages/core/src/repowise/core/workspace/service_names/__init__.py
@@ -35,7 +35,16 @@ from typing import Any
from repowise.core.fs_walk import PRUNED_DIRS, walk_repo
-from . import aspire, compose, dockerfile, k8s_service, nginx, spring, spring_gateway
+from . import (
+ aspire,
+ compose,
+ dockerfile,
+ k8s_service,
+ nginx,
+ spring,
+ spring_base_path,
+ spring_gateway,
+)
from .base import ENV, HOST, Claim, Route, ServiceNameSource, SourceFile
_log = logging.getLogger("repowise.workspace.service_names")
@@ -47,6 +56,7 @@ SOURCES: tuple[ServiceNameSource, ...] = (
k8s_service.SOURCE,
nginx.SOURCE,
spring.SOURCE,
+ spring_base_path.SOURCE,
spring_gateway.SOURCE,
)
@@ -73,6 +83,21 @@ _PRUNE = PRUNED_DIRS | {
_MAX_BYTES = 512_000
+@dataclass(frozen=True)
+class BasePath:
+ """Every route the *module* of *repo* serves sits under *path*.
+
+ *module* is the module directory relative to the repo root (posix, ``""``
+ for the whole repo); *source* and *file* say where it was read.
+ """
+
+ repo: str
+ module: str
+ path: str
+ source: str
+ file: str
+
+
@dataclass(frozen=True)
class ServiceName:
"""One resolved name: the repo serving it and the source and file that said so."""
@@ -110,6 +135,8 @@ class ServiceNameMap:
entries: dict[tuple[str, str], ServiceName] = field(default_factory=dict)
#: Every workspace repo alias the map was built over.
repos: frozenset[str] = frozenset()
+ #: Server base paths (a Spring context-path), one per repo module.
+ base_paths: tuple[BasePath, ...] = ()
#: 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.
@@ -140,6 +167,7 @@ class ServiceNameMap:
def to_dict(self, fingerprint: str = "") -> dict[str, Any]:
return {
"fingerprint": fingerprint,
+ "base_paths": [asdict(b) for b in self.base_paths],
"repos": sorted(self.repos),
"entries": [asdict(e) for _, e in sorted(self.entries.items())],
"routes": [asdict(r) for r in self.routes],
@@ -149,6 +177,7 @@ class ServiceNameMap:
def from_dict(cls, data: dict[str, Any]) -> ServiceNameMap:
entries = [ServiceName(**e) for e in data.get("entries", [])]
return cls(
+ base_paths=tuple(BasePath(**b) for b in data.get("base_paths", [])),
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", [])),
@@ -317,6 +346,8 @@ def build_service_name_map(
}:
found.extend(_workspace_root_files(workspace_root))
+ base_found = [f for f in found if f.claim.base_path is not None]
+ found = [f for f in found if f.claim.base_path is None]
resolver = _Resolver(repo_paths)
out = ServiceNameMap(repos=frozenset(repo_paths))
claimed: dict[tuple[str, str], dict[str, tuple[str, str]]] = defaultdict(dict)
@@ -370,13 +401,77 @@ def build_service_name_map(
if out.ambiguous:
_log.debug("Service names left unmapped (claimed for several repos): %s", out.ambiguous)
+ out.base_paths = _settle_base_paths(base_found, out, resolver, repo_paths)
return out
+def _module_of(hit: ServiceName) -> str | None:
+ """The module whose own Spring config named *hit*, as a repo-relative directory.
+
+ None when the name came from anywhere else (a compose or k8s file in a
+ deploy repo): that does not say which module of the repo serves it.
+ """
+ if hit.source != spring.SOURCE.name:
+ return None
+ head = f"{hit.repo}/"
+ if not hit.file.startswith(head):
+ return None
+ parts = hit.file[len(head) :].split("/")[:-1]
+ if [p.lower() for p in parts[-1:]] == ["config"]:
+ parts = parts[:-1]
+ if [p.lower() for p in parts[-3:]] != ["src", "main", "resources"]:
+ return None
+ return "/".join(parts[:-3])
+
+
+def _place_base_path(
+ c: Claim, names: ServiceNameMap, resolver: _Resolver, repo_paths: dict[str, Path]
+) -> tuple[str, str] | None:
+ """``(repo, module)`` a base-path claim applies to, or None when unplaced."""
+ if c.at is not None:
+ repo = resolver.repo_at(c.at)
+ if repo is None:
+ return None
+ module = Path(os.path.relpath(c.at, repo_paths[repo])).as_posix()
+ return repo, "" if module == "." else module
+ hit = names.lookup(c.name, HOST)
+ module = _module_of(hit) if hit is not None else None
+ if hit is not None and module is not None:
+ return hit.repo, module
+ repo = resolver.named((c.name,))
+ return (repo, "") if repo is not None else None
+
+
+def _settle_base_paths(
+ found: list[_Found], names: ServiceNameMap, resolver: _Resolver, repo_paths: dict[str, Path]
+) -> tuple[BasePath, ...]:
+ """One base path per repo module; a module given two paths gets none.
+
+ A module's own file places itself (``at``); a config server's file names a
+ service, placed in the module whose own ``spring.application.name`` declared
+ it or, failing that, in the repo whose alias it is (the whole repo). A name
+ only a deploy file places says no module, so it places nothing.
+ """
+ paths: dict[tuple[str, str], dict[str, tuple[str, str]]] = defaultdict(dict)
+ for f in found:
+ placed = _place_base_path(f.claim, names, resolver, repo_paths)
+ if placed is not None:
+ paths[placed].setdefault(f.claim.base_path or "", (f.source.name, f.evidence))
+ settled: list[BasePath] = []
+ for (repo, module), by_path in sorted(paths.items()):
+ if len(by_path) == 1:
+ [(path, (source, evidence))] = by_path.items()
+ settled.append(BasePath(repo, module, path, source, evidence))
+ else:
+ _log.debug("Base path of %s/%s read several ways: %s", repo, module, sorted(by_path))
+ return tuple(settled)
+
+
__all__ = [
"ENV",
"HOST",
"SOURCES",
+ "BasePath",
"GatewayRoute",
"ServiceName",
"ServiceNameMap",
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 9883fd997..e522e7125 100644
--- a/packages/core/src/repowise/core/workspace/service_names/base.py
+++ b/packages/core/src/repowise/core/workspace/service_names/base.py
@@ -49,6 +49,9 @@ class Route:
class Claim:
"""One file's statement that *name* is served by some repo.
+ A claim with a ``base_path`` says instead that the module at ``at`` (or,
+ without ``at``, the service *name*) serves every route under that path.
+
Where it points, tried in order: ``at`` (the directory the service is
built from; the repo holding it serves *name*), ``aliases`` (repo aliases
the file names for it, such as an image basename or a selector label; the
@@ -65,6 +68,7 @@ class Claim:
name: str
kind: str = HOST
+ base_path: str | None = None
at: Path | None = None
aliases: tuple[str, ...] = ()
ref: str | None = None
diff --git a/packages/core/src/repowise/core/workspace/service_names/spring_base_path.py b/packages/core/src/repowise/core/workspace/service_names/spring_base_path.py
new file mode 100644
index 000000000..296028659
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/service_names/spring_base_path.py
@@ -0,0 +1,106 @@
+"""Spring's server base path: the prefix a module serves every route under.
+
+``server.servlet.context-path`` (Boot 2+), ``server.context-path`` (Boot 1) and
+``spring.webflux.base-path``, in YAML or ``.properties``, any relaxed spelling
+(``contextPath``, ``context_path``).
+
+Two places say it. A module's own ``application`` or ``bootstrap`` file in its
+``src/main/resources`` (or its ``config/`` child) applies to that module. A
+config server's ``<app>.yml`` (``shared/account-service.yml``) applies to the
+service the file is named after; the matcher places that name through the
+service-name map. Not read: an ``application`` file anywhere else (a config
+server's shared defaults would apply to every app at once) and a profile file
+(``application-dev.yml``): it holds only while that profile is active.
+A config server's ``<app>-<profile>.yml`` names no service, so it places nothing.
+"""
+
+from __future__ import annotations
+
+import re
+from collections.abc import Iterable, Iterator
+from pathlib import Path
+from typing import Any
+
+from .base import Claim, ServiceNameSource, SourceFile
+from .yaml_docs import load_yaml_docs
+
+# Relaxed binding: dashes and underscores dropped, lowercased.
+_KEYS = frozenset({"server.servlet.contextpath", "server.contextpath", "spring.webflux.basepath"})
+# Cheap check before a YAML parse: most gated files say none of these.
+_HINT_RE = re.compile(r"context[-_]?path|base[-_]?path", re.IGNORECASE)
+_PROPERTY_RE = re.compile(r"^\s*([A-Za-z][\w.\-]*)\s*[=:]\s*(\S*)\s*$", re.MULTILINE)
+_OWN_NAMES = frozenset({"application", "bootstrap"})
+# A document scoped to a profile (Boot 2.4+ and the legacy spelling).
+_PROFILE_KEYS = frozenset({"spring.config.activate.onprofile", "spring.profiles"})
+# The document separator of a multi-document ``.properties`` file.
+_PROPERTIES_DOC_RE = re.compile(r"^[#!]---\s*$", re.MULTILINE)
+
+
+def _relaxed(key: str) -> str:
+ return key.replace("-", "").replace("_", "").lower()
+
+
+def _flat(node: Any, key: str = "") -> Iterator[tuple[str, Any]]:
+ if isinstance(node, dict):
+ for k, v in node.items():
+ yield from _flat(v, f"{key}.{k}" if key else str(k))
+ else:
+ yield key, node
+
+
+def _docs(file: SourceFile) -> list[list[tuple[str, Any]]]:
+ """Each document's ``(key, value)`` pairs, a profile-scoped document left out:
+ it holds only while that profile is active."""
+ if file.path.suffix.lower() == ".properties":
+ docs = [_PROPERTY_RE.findall(d) for d in _PROPERTIES_DOC_RE.split(file.text)]
+ else:
+ docs = [list(_flat(doc)) for doc in load_yaml_docs(file.text)]
+ return [d for d in docs if not any(_relaxed(k) in _PROFILE_KEYS for k, _ in d)]
+
+
+def _values(file: SourceFile) -> set[str]:
+ out: set[str] = set()
+ for key, value in (kv for doc in _docs(file) for kv in doc):
+ if _relaxed(key) in _KEYS and isinstance(value, str):
+ path = value.strip().strip("'\"").rstrip("/").lower()
+ if path.startswith("/") and "$" not in path and "{" not in path:
+ out.add(path)
+ return out
+
+
+def read(file: SourceFile) -> Iterable[Claim]:
+ if not _HINT_RE.search(file.text):
+ return
+ stem = file.path.stem.lower()
+ module = _own_module(file.path) if stem in _OWN_NAMES else None
+ if stem.startswith(("application", "bootstrap")) and module is None:
+ return # shared defaults, a profile file, or a file no module loads
+ values = _values(file)
+ if len(values) != 1: # profiles disagreeing: no one base path to trust
+ return
+ [path] = values
+ if module is not None:
+ yield Claim(name="", base_path=path, at=module)
+ else:
+ yield Claim(name=stem, base_path=path)
+
+
+def _own_module(path: Path) -> Path | None:
+ """The module whose ``src/main/resources[/config]`` holds *path*, else None."""
+ d = path.parent
+ if d.name.lower() == "config":
+ d = d.parent
+ parts = [p.lower() for p in d.parts[-3:]]
+ return d.parent.parent.parent if parts == ["src", "main", "resources"] else None
+
+
+SOURCE = ServiceNameSource(
+ name="spring_base_path",
+ filenames=("*.yml", "*.yaml", "*.properties"),
+ # A module's resources, and where config servers keep their files. Ceiling:
+ # a git-backed config repo with its files at the root is not read; adding
+ # it is a gate on that repo's layout, not a glob.
+ under=frozenset({"resources", "config", "configs", "shared"}),
+ marker="path",
+ read=read,
+)
diff --git a/tests/fixtures/service_names/spring_pm/config/src/main/resources/shared/auth-service.yml b/tests/fixtures/service_names/spring_pm/config/src/main/resources/shared/auth-service.yml
new file mode 100644
index 000000000..137c067fb
--- /dev/null
+++ b/tests/fixtures/service_names/spring_pm/config/src/main/resources/shared/auth-service.yml
@@ -0,0 +1,13 @@
+spring:
+ data:
+ mongodb:
+ host: auth-mongodb
+ username: user
+ password: ${MONGODB_PASSWORD}
+ database: piggymetrics
+ port: 27017
+
+server:
+ servlet:
+ context-path: /uaa
+ port: 5000
diff --git a/tests/unit/workspace/test_base_paths.py b/tests/unit/workspace/test_base_paths.py
new file mode 100644
index 000000000..27b888dfb
--- /dev/null
+++ b/tests/unit/workspace/test_base_paths.py
@@ -0,0 +1,234 @@
+"""Server base paths (Spring context-path): read from config, placed by the
+service-name map, applied to the routes they prefix before matching."""
+
+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.matching.base_paths import apply_base_paths
+from repowise.core.workspace.origins import LinkStrategy
+from repowise.core.workspace.service_names import (
+ BasePath,
+ ServiceName,
+ ServiceNameMap,
+ build_service_name_map,
+)
+from repowise.core.workspace.service_names.base import HOST, SourceFile
+from repowise.core.workspace.service_names.spring_base_path import read
+
+FIXTURES = Path(__file__).resolve().parents[2] / "fixtures" / "service_names"
+
+
+def _paths(m: ServiceNameMap) -> set[tuple[str, str, str]]:
+ return {(b.repo, b.module, b.path) for b in m.base_paths}
+
+
+def _write(root: Path, rel: str, text: str) -> None:
+ path = root / rel
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(text, encoding="utf-8")
+
+
+# ---------------------------------------------------------------------------
+# Reading
+# ---------------------------------------------------------------------------
+
+
+def test_a_config_servers_app_file_sets_that_services_base_path() -> None:
+ # piggymetrics: the context-path lives in the config repo, not the service.
+ root = FIXTURES / "spring_pm"
+ m = build_service_name_map({a: root / a for a in ("account-service", "auth-service", "config")})
+ assert _paths(m) == {("account-service", "", "/accounts"), ("auth-service", "", "/uaa")}
+ [auth] = [b for b in m.base_paths if b.repo == "auth-service"]
+ assert (auth.source, auth.file) == (
+ "spring_base_path",
+ "config/src/main/resources/shared/auth-service.yml",
+ )
+
+
+ ("name", "text", "path"),
+ [
+ ("application.yml", "server:\n servlet:\n context-path: /api/\n", "/api"),
+ ("application.properties", "server.servlet.contextPath=/api\n", "/api"),
+ ("application.yml", "server:\n context_path: /legacy\n", "/legacy"),
+ ("bootstrap.yml", "spring:\n webflux:\n base-path: /flux\n", "/flux"),
+ ("application.yml", "server.servlet.context-path: /dotted\n", "/dotted"),
+ # Naming the active profile does not scope the document.
+ ("application.yml", "spring.profiles.active: dev\nserver.context-path: /act\n", "/act"),
+ ],
+)
+def test_every_spelling_is_read(name: str, text: str, path: str) -> None:
+ [claim] = read(SourceFile(Path("svc/src/main/resources") / name, text))
+ assert (claim.base_path, claim.at) == (path, Path("svc"))
+
+
+ ("rel", "text"),
+ [
+ # A placeholder, a root path, and a non-Spring key say nothing.
+ ("svc/src/main/resources/application.yml", "server:\n servlet:\n context-path: ${CTX}\n"),
+ ("svc/src/main/resources/application.yml", "server:\n servlet:\n context-path: /\n"),
+ ("svc/src/main/resources/openapi.yml", "basePath: /v2\n"),
+ # Two profiles disagreeing: no one value to trust.
+ (
+ "svc/src/main/resources/application.yml",
+ "server.servlet.context-path: /a\n---\nserver.servlet.context-path: /b\n",
+ ),
+ # A config server's shared defaults would apply to every app at once.
+ ("config/src/main/resources/shared/application.yml", "server.servlet.context-path: /x\n"),
+ ("cfg/config/application.yml", "server.servlet.context-path: /x\n"),
+ # A profile file holds only while that profile is active.
+ ("svc/src/main/resources/application-dev.yml", "server.servlet.context-path: /x\n"),
+ # So does a profile-scoped document in the default file, in any spelling.
+ (
+ "svc/src/main/resources/application.yml",
+ "server.port: 80\n---\nspring.config.activate.on-profile: docker\n"
+ "server.servlet.context-path: /x\n",
+ ),
+ (
+ "svc/src/main/resources/application.yml",
+ "server.port: 80\n---\nspring:\n profiles: docker\n"
+ "server:\n servlet:\n context-path: /x\n",
+ ),
+ (
+ "svc/src/main/resources/application.properties",
+ "server.port=80\n#---\nspring.config.activate.on-profile=docker\n"
+ "server.servlet.context-path=/x\n",
+ ),
+ ],
+)
+def test_what_is_not_a_base_path(rel: str, text: str) -> None:
+ assert list(read(SourceFile(Path(rel), text))) == []
+
+
+def test_a_config_server_file_names_the_app_it_is_called() -> None:
+ [claim] = read(SourceFile(Path("shared/orders.yml"), "server.servlet.context-path: /orders\n"))
+ assert (claim.name, claim.base_path, claim.at) == ("orders", "/orders", None)
+
+
+def test_a_name_only_a_deploy_file_places_says_no_module(tmp_path: Path) -> None:
+ # compose places auth-service in `backend`, but not which of its modules.
+ _write(tmp_path, "infra/docker-compose.yml",
+ "services:\n auth-service:\n build: ../backend/auth\n")
+ _write(tmp_path, "backend/auth/pom.xml", "<project/>\n")
+ _write(tmp_path, "backend/orders/pom.xml", "<project/>\n")
+ _write(tmp_path, "cfg/shared/auth-service.yml", "server.servlet.context-path: /uaa\n")
+ m = build_service_name_map({a: tmp_path / a for a in ("infra", "backend", "cfg")})
+ assert m.lookup("auth-service") is not None
+ assert m.base_paths == ()
+
+
+def test_each_module_of_a_monorepo_keeps_its_own_base_path(tmp_path: Path) -> None:
+ _write(tmp_path, "mono/orders/src/main/resources/application.yml",
+ "spring.application.name: orders\nserver.servlet.context-path: /orders\n")
+ _write(tmp_path, "mono/billing/src/main/resources/application.yml",
+ "spring.application.name: billing\n")
+ _write(tmp_path, "cfg/config/billing.yml", "server.servlet.context-path: /bill\n")
+ # Two values for one module: neither is applied.
+ _write(tmp_path, "mono/stock/src/main/resources/application.yml",
+ "spring.application.name: stock\nserver.servlet.context-path: /stock\n")
+ _write(tmp_path, "cfg/config/stock.yml", "server.servlet.context-path: /inventory\n")
+ m = build_service_name_map({"mono": tmp_path / "mono", "cfg": tmp_path / "cfg"})
+ assert _paths(m) == {("mono", "orders", "/orders"), ("mono", "billing", "/bill")}
+
+
+def test_base_paths_survive_the_stored_map() -> None:
+ m = ServiceNameMap(base_paths=(BasePath("auth", "", "/uaa", "spring_base_path", "cfg/a.yml"),))
+ assert ServiceNameMap.from_dict(m.to_dict("fp")).base_paths == m.base_paths
+
+
+# ---------------------------------------------------------------------------
+# Applying and matching
+# ---------------------------------------------------------------------------
+
+
+def _http(repo: str, role: str, path: str, method: str = "GET", file: str = "A.java", **meta: object) -> Contract:
+ return Contract(
+ repo=repo,
+ contract_id=f"http::{method}::{path}",
+ contract_type="http",
+ role=role,
+ file_path=file,
+ symbol_name=path,
+ confidence=0.9,
+ meta={"method": method, "path": path, **meta},
+ )
+
+
+def _spring(repo: str, path: str, method: str = "GET", file: str = "A.java") -> Contract:
+ return _http(repo, "provider", path, method, file, framework="spring")
+
+
+def test_a_base_path_prefixes_spring_routes_and_is_recomputed_not_stacked() -> None:
+ account = [_spring("account", "/{param}"), _spring("account", "/", "POST")]
+ express = _http("account", "provider", "/health", framework="express")
+ contracts = [*account, express]
+ base = (BasePath("account", "", "/accounts", "spring_base_path", "config/x.yml"),)
+ apply_base_paths(contracts, base)
+ apply_base_paths(contracts, base)
+ assert [c.contract_id for c in contracts] == [
+ "http::GET::/accounts/{param}",
+ "http::POST::/accounts",
+ "http::GET::/health", # not Spring: the context-path is Spring's
+ ]
+ apply_base_paths(contracts, ()) # the config line went away
+ assert [c.contract_id for c in account] == ["http::GET::/{param}", "http::POST::/"]
+ assert all("declared_path" not in c.meta for c in account)
+
+
+def test_a_module_base_path_stays_in_its_module() -> None:
+ orders = _spring("mono", "/{param}", file="orders/src/O.java")
+ billing = _spring("mono", "/{param}", file="billing/src/B.java")
+ apply_base_paths([orders, billing], (BasePath("mono", "orders", "/orders", "s", "f"),))
+ assert (orders.contract_id, billing.contract_id) == (
+ "http::GET::/orders/{param}",
+ "http::GET::/{param}",
+ )
+
+
+def test_a_call_naming_the_context_path_links_to_the_route() -> None:
+ # piggymetrics: AuthServiceClient posts /uaa/users; UserController maps /users.
+ contracts = [
+ _spring("auth", "/users", "POST"),
+ _spring("account", "/{param}"),
+ _spring("statistics", "/{param}"),
+ _http("account", "consumer", "/uaa/users", "POST", host="auth-service"),
+ _http("notification", "consumer", "/accounts/{param}", host="account-service"),
+ ]
+ names = ServiceNameMap(
+ entries={
+ (HOST, n): ServiceName(n, HOST, r, "spring_application_name", f"{r}/bootstrap.yml")
+ for n, r in (("auth-service", "auth"), ("account-service", "account"))
+ },
+ repos=frozenset({"auth", "account", "statistics", "notification"}),
+ base_paths=(
+ BasePath("auth", "", "/uaa", "spring_base_path", "config/auth-service.yml"),
+ BasePath("account", "", "/accounts", "spring_base_path", "config/account-service.yml"),
+ BasePath("statistics", "", "/statistics", "spring_base_path", "config/s.yml"),
+ ),
+ )
+ apply_base_paths(contracts, names.base_paths)
+ annotate_consumer_targets(contracts, {}, names)
+ state = run_matching(contracts)
+ assert sorted((lk.consumer_repo, lk.provider_repo, lk.contract_id, lk.strategy) for lk in state.links) == [
+ ("account", "auth", "http::POST::/uaa/users", LinkStrategy.SERVICE_MAPPED),
+ ("notification", "account", "http::GET::/accounts/{param}", LinkStrategy.SERVICE_MAPPED),
+ ]
+ assert state.service_links == []
+
+
+def test_a_star_segment_matches_a_parameter() -> None:
+ # petclinic: @RequestMapping("/owners/*/pets") on PetResource.
+ from repowise.core.workspace.extractors.http.paths import normalize_http_path
+
+ assert normalize_http_path("/owners/*/pets/{petId}") == "/owners/{param}/pets/{param}"
+ assert normalize_http_path("/**") == "/**" # a catch-all is not one segment
+ provider = _spring("customers", normalize_http_path("/owners/*/pets/{petId}"), "PUT")
+ consumer = _http("web", "consumer", "/owners/{param}/pets/{param}", "PUT")
+ [link] = run_matching([provider, consumer]).links
+ assert link.provider_repo == "customers"
diff --git a/tests/unit/workspace/test_flask_dialect.py b/tests/unit/workspace/test_flask_dialect.py
index 4134936ea..d7ab5c2b0 100644
--- a/tests/unit/workspace/test_flask_dialect.py
+++ b/tests/unit/workspace/test_flask_dialect.py
@@ -335,15 +335,14 @@ class TestFlaskRefusals:
(tmp_path / "users.py").write_text(USERS_PY, encoding="utf-8")
assert _providers(tmp_path) == {}
- def test_a_bare_slash_route_is_not_a_contract(self, tmp_path: Path) -> None:
- # A path that normalises to bare `/` carries nothing to match on, and
- # the shared builder drops it for every framework.
+ def test_a_root_route_is_a_contract(self, tmp_path: Path) -> None:
+ # A service whose whole API is `POST /` serves it at the root.
(tmp_path / "app.py").write_text(
"from flask import Flask\n\napp = Flask(__name__)\n\n"
- '@app.route("/")\ndef home(): ...\n',
+ '@app.route("/", methods=["POST"])\ndef talk(): ...\n',
encoding="utf-8",
)
- assert _providers(tmp_path) == {}
+ assert set(_providers(tmp_path)) == {"http::POST::/"}
def test_a_commented_out_route_is_not_an_endpoint(self, tmp_path: Path) -> None:
(tmp_path / "app.py").write_text(
diff --git a/tests/unit/workspace/test_framework_routes.py b/tests/unit/workspace/test_framework_routes.py
index 5f0a87dff..cef1ef782 100644
--- a/tests/unit/workspace/test_framework_routes.py
+++ b/tests/unit/workspace/test_framework_routes.py
@@ -861,8 +861,7 @@ def test_spring_contracts_compose_each_prefix_and_skip_what_they_cannot_read(
'@RestController\n@RequestMapping("/pets")\nclass PetController {\n'
' @GetMapping(path = ["/{id}"])\n fun one(): String = ""\n}\n'
)
- # A root route, bare or spelled "/", is dropped as JAX-RS and Micronaut roots
- # are: build_provider_contract refuses a path that normalizes to "/".
+ # A root route, bare or spelled "/", is the one route `GET /`.
(tmp_path / "Welcome.java").write_text(
"@RestController\npublic class Welcome {\n"
" @GetMapping\n public String a() { return null; }\n"
@@ -888,6 +887,7 @@ def test_spring_contracts_compose_each_prefix_and_skip_what_they_cannot_read(
"http::PUT::/v2/d",
"http::GET::/plain",
"http::GET::/pets/{param}",
+ "http::GET::/",
}
diff --git a/tests/unit/workspace/test_remix_dialect.py b/tests/unit/workspace/test_remix_dialect.py
index 51e387320..349f7f599 100644
--- a/tests/unit/workspace/test_remix_dialect.py
+++ b/tests/unit/workspace/test_remix_dialect.py
@@ -253,11 +253,10 @@ class TestRemixRefusals:
)
assert _providers(tmp_path) == {}
- def test_the_root_route_is_not_a_contract(self, tmp_path: Path) -> None:
- # A stated ceiling: a path that normalises to bare `/` carries nothing
- # to match on, and the shared builder drops it for every framework.
+ def test_the_root_route_is_a_contract(self, tmp_path: Path) -> None:
+ # The index route serves `/`, which a gateway or a resolved host can reach.
_write(tmp_path, "app/routes/_index.tsx", HEALTHCHECK_TSX)
- assert _providers(tmp_path) == {}
+ assert set(_providers(tmp_path)) == {"http::GET::/"}
# ---------------------------------------------------------------------------