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 Feign clients with Spring MVC annotations and Spring HttpExchange interfaces as calls (#4531)

Raghav Chamadiyabf876c57f196
diff --git a/docs/scale/WORKSPACES.md b/docs/scale/WORKSPACES.md
index 7daac5e50..1c0c4cdc8 100644
--- a/docs/scale/WORKSPACES.md
+++ b/docs/scale/WORKSPACES.md
@@ -141,7 +141,7 @@ Scans source files for HTTP routes, gRPC services, database tables, message topi
| JS / TS | Express, Hono, Fastify, Koa, Elysia; NestJS controllers; Next.js App Router; Remix | `fetch`; axios, ky, got, ofetch and their instances; Angular `HttpClient`; HTTP-named wrappers |
| Python | FastAPI, Flask, Django | requests, httpx (aiohttp through wrappers the index confirms) |
| PHP | Laravel | Guzzle, Laravel `Http` |
-| Java / Kotlin | Spring, JAX-RS, Micronaut | Feign, `java.net.http`, `RestTemplate`, Ktor (Kotlin) |
+| Java / Kotlin | Spring, JAX-RS, Micronaut | Feign (`@RequestLine`, and `@FeignClient` with Spring MVC annotations, its `name` read as the host), Spring `@HttpExchange` interfaces, `java.net.http`, `RestTemplate`, Ktor (Kotlin) |
| Go | gin, echo, chi, net/http | net/http |
| C# | ASP.NET (attribute and minimal API) | HttpClient (`GetAsync`, `GetFromJsonAsync`, `PostAsJsonAsync`, `GetStringAsync`, `new HttpRequestMessage(HttpMethod.X, url)`; a URL held in a local or a `const` / `readonly` field), UnityWebRequest, Best.HTTP |
| Ruby | | HTTParty, RestClient, Faraday, Net::HTTP |
diff --git a/packages/core/src/repowise/core/ingestion/framework_routes.py b/packages/core/src/repowise/core/ingestion/framework_routes.py
index 0f25c27e0..7c2477916 100644
--- a/packages/core/src/repowise/core/ingestion/framework_routes.py
+++ b/packages/core/src/repowise/core/ingestion/framework_routes.py
@@ -1498,6 +1498,49 @@ _SPRING_ARRAY_REST_RE = re.compile(r'"\s*"|[\s,]')
_SPRING_VERB_WORD_RE = re.compile(r"\b(GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS|TRACE)\b")
+@dataclass(frozen=True)
+class SpringMappingFamily:
+ """One annotation family that maps a Java or Kotlin method to an HTTP route.
+
+ ``method`` matches the method-level annotation with a ``verb`` group, whose
+ ``generic`` spelling names its verbs in ``method = ...`` instead; ``type_``
+ matches the type-level annotation whose path is the prefix; ``path_key``
+ is where a named path argument starts; ``marker`` is a substring every
+ method annotation in the family holds and ``type_marker`` one the type
+ annotation holds, the cheap gates.
+ """
+
+ method: re.Pattern[str]
+ type_: re.Pattern[str]
+ path_key: re.Pattern[str]
+ generic: str
+ marker: str
+ type_marker: str
+
+
+#: Spring MVC / WebFlux: ``@RequestMapping`` and its verb shortcuts.
+SPRING_MVC = SpringMappingFamily(
+ method=_SPRING_MAPPING_RE,
+ type_=_SPRING_CLASS_RE,
+ path_key=_SPRING_PATH_KEY_RE,
+ generic="Request",
+ marker="Mapping",
+ type_marker="@RequestMapping",
+)
+
+#: Spring 6 HTTP interfaces: ``@HttpExchange`` and its verb shortcuts. A client
+#: declaration, so every route it reads is a call out. The path is ``value``
+#: or ``url`` and the verb is a string, ``method = "GET"``.
+SPRING_EXCHANGE = SpringMappingFamily(
+ method=re.compile(r"@(?P<verb>Get|Post|Put|Delete|Patch|Http)Exchange\b"),
+ type_=re.compile(r"@HttpExchange\b"),
+ path_key=re.compile(r"[(,]\s*(?:value|url)\s*=\s*"),
+ generic="Http",
+ marker="Exchange",
+ type_marker="@HttpExchange",
+)
+
+
def _blank_strings(text: str) -> str:
"""*text* with every string literal's body blanked, offsets kept."""
return _JVM_STRING_RE.sub(lambda m: '"' + " " * (len(m.group()) - 2) + '"', text)
@@ -1512,7 +1555,7 @@ def _spring_args(content: str, at: int) -> str:
return content[opened.end() - 1 : len(content) if close == -1 else close + 1]
-def _spring_paths(args: str) -> tuple[str, ...] | None:
+def _spring_paths(args: str, path_key: re.Pattern[str] = _SPRING_PATH_KEY_RE) -> tuple[str, ...] | None:
"""The paths a mapping's *args* declare.
``("",)`` when they name none, which Spring serves at the type prefix.
@@ -1520,7 +1563,7 @@ def _spring_paths(args: str) -> tuple[str, ...] | None:
is a path, just not this file's to know.
"""
masked = _blank_strings(args)
- key = _SPRING_PATH_KEY_RE.search(masked) or _SPRING_POSITIONAL_RE.match(masked)
+ key = path_key.search(masked) or _SPRING_POSITIONAL_RE.match(masked)
if key is None:
return ("",)
read = _spring_literals(args, masked, key.end())
@@ -1542,18 +1585,21 @@ def _spring_literals(args: str, masked: str, at: int) -> tuple[tuple[str, ...],
return tuple(s.group()[1:-1] for s in _JVM_STRING_RE.finditer(args, m.end(), close)), close + 1
-def _spring_verbs(verb: str, args: str) -> tuple[str, ...]:
- """The verbs a mapping serves; ``ALL`` for a ``@RequestMapping`` naming none."""
- if verb != "Request":
+def _spring_verbs(verb: str, args: str, generic: str = "Request") -> tuple[str, ...]:
+ """The verbs a mapping serves; ``ALL`` for a *generic* mapping naming none."""
+ if verb != generic:
return (verb.upper(),)
masked = _blank_strings(args)
key = _SPRING_METHOD_KEY_RE.search(masked)
if key is None:
return ("ALL",)
+ # The value's extent is read with strings blanked, its words from the text:
+ # `RequestMethod.GET` and `"GET"` both name the verb.
if masked.startswith(("{", "["), key.end()):
- value = masked[key.end() : _jvm_match_paren(masked, key.end()) + 1]
+ value = args[key.end() : _jvm_match_paren(masked, key.end()) + 1]
else:
- value = re.split(r"[,)]", masked[key.end() :], maxsplit=1)[0]
+ end = re.search(r"[,)]", masked[key.end() :])
+ value = args[key.end() : key.end() + end.start()] if end else args[key.end() :]
return tuple(dict.fromkeys(_SPRING_VERB_WORD_RE.findall(value))) or ("ALL",)
@@ -1581,19 +1627,19 @@ def _spring_type_bodies(
def spring_class_paths(
- content: str, annotations: set[int] | None = None
+ content: str, annotations: set[int] | None = None, family: SpringMappingFamily = SPRING_MVC
) -> list[tuple[int, int, tuple[str, ...] | None]]:
- """``(body start, body end, prefixes)`` per type-level ``@RequestMapping``, ascending.
+ """``(body start, body end, prefixes)`` per type-level mapping of *family*, ascending.
``prefixes`` is ``None`` when the mapping names a path this cannot read; the
routes under it are refused rather than served at their bare sub-path.
"""
- if "@RequestMapping" not in content:
+ if family.type_marker not in content:
return []
code = micronaut_annotations(content) if annotations is None else annotations
out: list[tuple[int, int, tuple[str, ...] | None]] = []
- for name_end, start, end in _spring_type_bodies(content, code, _SPRING_CLASS_RE):
- paths = _spring_paths(_spring_args(content, name_end))
+ for name_end, start, end in _spring_type_bodies(content, code, family.type_):
+ paths = _spring_paths(_spring_args(content, name_end), family.path_key)
out.append((start, end, None if paths is None else tuple(p.rstrip("/") for p in paths)))
return out
@@ -1609,38 +1655,67 @@ def spring_route_prefixes(
return found
-def _spring_method_mappings(content: str, annotations: set[int]) -> Iterator[re.Match[str]]:
- """Mapping annotations written as code on a method outside any Feign client."""
+def spring_feign_clients(
+ content: str, annotations: set[int] | None = None
+) -> list[tuple[int, int, str]]:
+ """``(body start, body end, annotation arguments)`` per ``@FeignClient`` type, ascending.
+
+ The arguments are the annotation's parenthesised source text, ``""`` when
+ it has none; the client's ``name``, ``url`` and ``path`` sit in it.
+ """
+ if "@FeignClient" not in content:
+ return []
+ code = micronaut_annotations(content) if annotations is None else annotations
+ return [
+ (start, end, _spring_args(content, name_end))
+ for name_end, start, end in _spring_type_bodies(content, code, _SPRING_CLIENT_RE)
+ ]
+
+
+def _spring_method_mappings(
+ content: str, annotations: set[int], family: SpringMappingFamily, feign: bool
+) -> Iterator[re.Match[str]]:
+ """Method mapping annotations written as code, inside Feign clients or outside them."""
clients = (
- [(s, e) for _, s, e in _spring_type_bodies(content, annotations, _SPRING_CLIENT_RE)]
- if "@FeignClient" in content
+ [(s, e) for s, e, _ in spring_feign_clients(content, annotations)]
+ if family is SPRING_MVC
else []
)
- for m in _SPRING_MAPPING_RE.finditer(content):
- if m.start() not in annotations or any(s < m.start() < e for s, e in clients):
+ for m in family.method.finditer(content):
+ if m.start() not in annotations:
+ continue
+ if any(s < m.start() < e for s, e in clients) != feign:
continue
# A type's own mapping is its prefix, read by spring_class_paths.
if not _JVM_TYPE_RE.search(content, m.end(), _jaxrs_decl_end(content, m.start())):
yield m
-def spring_routes(content: str, annotations: set[int] | None = None) -> Iterator[RouteMatch]:
- """Method-level mappings in *content*, one per verb and path.
+def spring_routes(
+ content: str,
+ annotations: set[int] | None = None,
+ family: SpringMappingFamily = SPRING_MVC,
+ *,
+ feign: bool = False,
+) -> Iterator[RouteMatch]:
+ """Method-level mappings of *family* in *content*, one per verb and path.
``path`` is the method's own sub-path, ``""`` when it names none and
``None`` when it names one this cannot read; the type prefix is the
consumer's to stitch, from :func:`spring_class_paths`. The handler is the
method the annotation sits on, which every Spring route has, so ``offset``
- is all a consumer needs to find it. Mappings inside a ``@FeignClient`` type
- are calls out and are skipped.
+ is all a consumer needs to find it.
+
+ Spring MVC mappings inside a ``@FeignClient`` type are calls out: they are
+ skipped by default and are the only ones read with *feign*.
"""
- if "Mapping" not in content:
+ if family.marker not in content:
return
code = micronaut_annotations(content) if annotations is None else annotations
- for m in _spring_method_mappings(content, code):
+ for m in _spring_method_mappings(content, code, family, feign):
args = _spring_args(content, m.end())
- paths: tuple[str | None, ...] = _spring_paths(args) or (None,)
- for verb in _spring_verbs(m.group("verb"), args):
+ paths: tuple[str | None, ...] = _spring_paths(args, family.path_key) or (None,)
+ for verb in _spring_verbs(m.group("verb"), args, family.generic):
for path in paths:
yield RouteMatch(
verb=verb,
diff --git a/packages/core/src/repowise/core/workspace/extractors/http/__init__.py b/packages/core/src/repowise/core/workspace/extractors/http/__init__.py
index d89e55884..9cb7f4ef6 100644
--- a/packages/core/src/repowise/core/workspace/extractors/http/__init__.py
+++ b/packages/core/src/repowise/core/workspace/extractors/http/__init__.py
@@ -29,7 +29,7 @@ from .fastapi import FastApiDialect
from .flask import FlaskDialect
from .go import GoDialect
from .go_clients import GoClientsDialect
-from .java_clients import JavaClientsDialect
+from .java_clients import JavaClientsDialect, SpringClientsDialect
from .jaxrs import JaxRsDialect
from .js_clients import JsClientsDialect
from .kotlin_clients import KotlinClientsDialect
@@ -87,6 +87,7 @@ CONSUMER_DIALECTS: tuple[ContractDialect, ...] = (
KotlinClientsDialect(),
PhpClientsDialect(),
ApexCalloutsDialect(),
+ SpringClientsDialect(),
)
diff --git a/packages/core/src/repowise/core/workspace/extractors/http/java_clients.py b/packages/core/src/repowise/core/workspace/extractors/http/java_clients.py
index 775776f33..c7eb5497f 100644
--- a/packages/core/src/repowise/core/workspace/extractors/http/java_clients.py
+++ b/packages/core/src/repowise/core/workspace/extractors/http/java_clients.py
@@ -13,6 +13,12 @@ Three call shapes, each with its own source for the verb:
the verb in the callee, ``exchange(uri, HttpMethod.GET, ...)`` names it in the
second argument.
+Spring's declarative clients, Java or Kotlin, are read by their own dialect:
+an ``@FeignClient`` interface written with the controller annotations, and a
+Spring 6 ``@HttpExchange`` interface. Both are parsed by the Spring provider
+reader in ``ingestion.framework_routes``, so a client and the controller it
+calls read one grammar.
+
A chain with no terminal verb is refused rather than defaulted to GET, and a URL
that is a bare variable is refused unless the file assigns it a string literal
exactly once. OkHttp is left out: the corpus builds its ``Request.Builder`` from
@@ -22,14 +28,24 @@ a URL validated upstream, so no site carries a path this layer could read.
from __future__ import annotations
import re
-from collections.abc import Iterator
+from collections.abc import Callable, Iterator
from typing import TYPE_CHECKING
+from repowise.core.ingestion.framework_routes import (
+ SPRING_EXCHANGE,
+ RouteMatch,
+ micronaut_annotations,
+ spring_class_paths,
+ spring_feign_clients,
+ spring_route_prefixes,
+ spring_routes,
+)
from repowise.core.workspace.origins import ContractOrigin
-from ..langs import JAVA
+from ..langs import JAVA, KOTLIN
from ..strings import JAVA_SYNTAX, call_arguments, match_paren, string_constants
from .client_calls import VERBS, ClientCallMatch, consumer_contracts, method_from_argument
+from .mounts import compose_prefix
if TYPE_CHECKING:
from repowise.core.workspace.contracts import Contract
@@ -178,3 +194,188 @@ class JavaClientsDialect:
*consumer_contracts(ctx, named, JAVA_SYNTAX, constants=constants),
*consumer_contracts(ctx, ambiguous, JAVA_SYNTAX, constants=constants, path_only=True),
]
+
+
+# A literal argument of a Spring annotation: `key = "value"`, or the positional
+# first argument, which is `value`.
+_ANNOTATION_STRING_RE = re.compile(
+ r'(?:,\s*(?P<key>\w+)\s*=\s*|\(\s*(?:(?P<first>\w+)\s*=\s*)?)"(?P<value>[^"\\\n]*)"\s*(?=[,)])'
+)
+
+# A controller in the same file: `@HttpExchange` there declares a route served.
+# The guard is per file; a shared interface a controller elsewhere implements
+# still reads as a client.
+_CONTROLLER_RE = re.compile(r"@(?:Rest)?Controller\b")
+
+# A host the service-name map can look up: a bare service id, no placeholder.
+_SERVICE_ID_RE = re.compile(r"[\w.-]+")
+
+
+def _top_level(args: str) -> str:
+ """*args* with every nested ``(...)``, ``{...}`` and ``[...]`` blanked, offsets kept.
+
+ A nested annotation's ``path`` or ``url`` (``configuration = @Cfg(path = ...)``)
+ is not the client's.
+ """
+ out = list(args)
+ depth = 0
+ quoted = False
+ for i, ch in enumerate(args):
+ if ch == '"' and (i == 0 or args[i - 1] != "\\"):
+ quoted = not quoted
+ elif not quoted and ch in "([{":
+ depth += 1
+ elif not quoted and ch in ")]}":
+ depth -= 1
+ if depth >= 1:
+ out[i] = " "
+ continue
+ if depth > 1:
+ out[i] = " "
+ return "".join(out)
+
+
+def _annotation_strings(args: str) -> dict[str, str]:
+ """The literal arguments of an annotation's *args*, by key."""
+ out: dict[str, str] = {}
+ for m in _ANNOTATION_STRING_RE.finditer(args):
+ out.setdefault(m.group("key") or m.group("first") or "value", m.group("value"))
+ return out
+
+
+def _names_key(args: str, key: str) -> bool:
+ """Whether *args* passes *key* at all, literal or not."""
+ return re.search(rf"[(,]\s*{key}\s*=", args) is not None
+
+
+def _feign_base(args: str) -> tuple[str, str] | None:
+ """``(base URL, path prefix)`` a ``@FeignClient`` declares, ``None`` when unreadable.
+
+ ``url`` is where the client sends, literal or a ``${property}`` placeholder
+ the base resolver reads like any other. With no ``url`` the client calls
+ the service its ``name`` (or ``value``) registers under, which becomes the
+ host so the service-name map can place it; a placeholder name, or a ``url``
+ held in a constant, leaves the call a bare path. A ``path`` this cannot
+ read leaves every route under the client unknown.
+ """
+ args = _top_level(args)
+ strings = _annotation_strings(args)
+ prefix = strings.get("path", "")
+ if "${" in prefix or ("path" not in strings and _names_key(args, "path")):
+ return None
+ return _feign_host(args, strings), prefix
+
+
+def _feign_host(args: str, strings: dict[str, str]) -> str:
+ """The base URL a Feign client sends to: its ``url``, else its service name, else ``""``."""
+ if "url" in strings:
+ return strings["url"].rstrip("/")
+ name = strings.get("name") or strings.get("value") or ""
+ if _names_key(args, "url") or not _SERVICE_ID_RE.fullmatch(name):
+ return ""
+ return f"http://{name.lower()}"
+
+
+def _composed_paths(
+ class_paths: list[tuple[int, int, tuple[str, ...] | None]], route: RouteMatch, prefix: str
+) -> Iterator[str]:
+ """Each concrete path *route* reaches under its type prefixes and the client *prefix*."""
+ for type_prefix in spring_route_prefixes(class_paths, route.offset) or ():
+ path = compose_prefix(prefix, compose_prefix(type_prefix, route.path or ""))
+ if path.strip("/"):
+ yield path
+
+
+def _interface_rows(
+ routes: Iterator[RouteMatch],
+ class_paths: list[tuple[int, int, tuple[str, ...] | None]],
+ base_at: Callable[[int], tuple[str, str] | None],
+ *,
+ client: str,
+ unrestricted: str | None,
+) -> Iterator[ClientCallMatch]:
+ """Rows for a client interface's *routes*, each composed onto its type prefix and base.
+
+ *base_at* gives the ``(base URL, path prefix)`` of the client around an
+ offset. *unrestricted* is the verb the client sends for a mapping that
+ names none; ``None`` refuses such a mapping.
+ """
+ for route in routes:
+ base = None if route.path is None else base_at(route.offset)
+ verb = unrestricted if route.verb == "ALL" else route.verb
+ if base is None or verb is None or verb.lower() not in VERBS:
+ continue
+ url_base, prefix = base
+ for path in _composed_paths(class_paths, route, prefix):
+ yield ClientCallMatch(
+ client=client,
+ # The resolver reads a literal, so hand it one.
+ url=f'"{url_base}/{path.lstrip("/")}"',
+ offset=route.offset,
+ method=verb,
+ origin=ContractOrigin.CLIENT_CALL,
+ )
+
+
+def feign_interface_calls(content: str, annotations: set[int]) -> Iterator[ClientCallMatch]:
+ """Calls an ``@FeignClient`` interface declares with Spring MVC annotations."""
+ clients = spring_feign_clients(content, annotations)
+ if not clients:
+ return
+
+ def base_at(offset: int) -> tuple[str, str] | None:
+ inner = [args for start, end, args in clients if start < offset < end]
+ return _feign_base(inner[-1]) if inner else None
+
+ yield from _interface_rows(
+ spring_routes(content, annotations, feign=True),
+ spring_class_paths(content, annotations),
+ base_at,
+ client="feign",
+ unrestricted="GET", # Feign sends a mapping that names no verb as a GET
+ )
+
+
+def http_exchange_calls(content: str, annotations: set[int]) -> Iterator[ClientCallMatch]:
+ """Calls a Spring 6 ``@HttpExchange`` interface declares.
+
+ The base URL is set where the proxy is built, out of this file's sight, so
+ each row is a path. A file holding a controller is skipped: there the same
+ annotations declare routes served, not calls.
+ """
+ if _CONTROLLER_RE.search(content):
+ return
+ yield from _interface_rows(
+ spring_routes(content, annotations, SPRING_EXCHANGE),
+ spring_class_paths(content, annotations, SPRING_EXCHANGE),
+ lambda _offset: ("", ""),
+ client="http-exchange",
+ unrestricted=None,
+ )
+
+
+class SpringClientsDialect:
+ name = "spring-clients"
+ extensions = JAVA | KOTLIN
+ requires = (
+ "@FeignClient",
+ "@HttpExchange",
+ "@GetExchange",
+ "@PostExchange",
+ "@PutExchange",
+ "@DeleteExchange",
+ "@PatchExchange",
+ )
+
+ def extract(self, ctx: ScanContext) -> list[Contract]:
+ content = ctx.content
+ annotations = micronaut_annotations(content)
+ rows = [
+ *feign_interface_calls(content, annotations),
+ *http_exchange_calls(content, annotations),
+ ]
+ if not rows:
+ return []
+ # The URL text is built here, not read from the file, so it resolves as
+ # a plain literal whatever the file's language.
+ return consumer_contracts(ctx, rows, JAVA_SYNTAX)
diff --git a/tests/unit/workspace/test_spring_clients.py b/tests/unit/workspace/test_spring_clients.py
new file mode 100644
index 000000000..c02b62e5b
--- /dev/null
+++ b/tests/unit/workspace/test_spring_clients.py
@@ -0,0 +1,254 @@
+"""Spring's declarative HTTP clients as consumers.
+
+An ``@FeignClient`` interface written with the controller annotations, and a
+Spring 6 ``@HttpExchange`` interface, declare the calls a service makes. The
+claim under test is that each mapping becomes one consumer at the path the
+client composes (client ``path``, type mapping, method mapping), that a Feign
+client's ``name`` is the host the service-name map places, and that anything
+the file does not settle (a constant path, a controller's own mappings) emits
+nothing.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from repowise.core.workspace.extractors.base import ScanContext
+from repowise.core.workspace.extractors.http import HttpExtractor
+from repowise.core.workspace.extractors.http.java_clients import SpringClientsDialect
+from repowise.core.workspace.extractors.http.spring import SpringDialect
+from repowise.core.workspace.matching import match_contracts
+
+# piggymetrics account-service: a Feign client to the auth service.
+AUTH_CLIENT = """package com.piggymetrics.account.client;
+
+@FeignClient(name = "auth-service")
+public interface AuthServiceClient {
+
+ @RequestMapping(method = RequestMethod.POST, value = "/uaa/users", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
+ void createUser(User user);
+
+}
+"""
+
+# piggymetrics statistics-service: a third-party API behind a property.
+RATES_CLIENT = """package com.piggymetrics.statistics.client;
+
+@FeignClient(url = "${rates.url}", name = "rates-client", fallback = ExchangeRatesClientFallback.class)
+public interface ExchangeRatesClient {
+
+ @RequestMapping(method = RequestMethod.GET, value = "/latest")
+ ExchangeRatesContainer getRates(@RequestParam("base") Currency base);
+
+}
+"""
+
+PREFIXED_CLIENT = """package com.example;
+
+@FeignClient(value = "orders", path = "/api")
+@RequestMapping("/orders")
+interface OrdersClient {
+ @GetMapping("/{id}")
+ Order get(@PathVariable String id);
+
+ @RequestMapping("/recent")
+ List<Order> recent();
+
+ // @DeleteMapping("/{id}")
+ // void delete(@PathVariable String id);
+}
+"""
+
+LITERAL_URL_CLIENT = """@FeignClient(name = "github", url = "https://api.github.com/")
+interface GitHub {
+ @GetMapping("/repos/{owner}/{repo}")
+ Repo repo(@PathVariable String owner, @PathVariable String repo);
+}
+"""
+
+CONSTANT_PATH_CLIENT = """@FeignClient(name = "orders", path = Paths.ORDERS)
+interface OrdersClient {
+ @GetMapping("/{id}")
+ Order get(@PathVariable String id);
+}
+"""
+
+CONSTANT_URL_CLIENT = """@FeignClient(name = "orders", url = Urls.ORDERS)
+interface OrdersClient {
+ @GetMapping("/orders/{id}")
+ Order get(@PathVariable String id);
+}
+"""
+
+KOTLIN_CLIENT = """@FeignClient("inventory")
+interface InventoryClient {
+ @PostMapping("/stock/reserve")
+ fun reserve(@RequestBody req: Reservation)
+}
+"""
+
+# A controller beside a Feign client in one file: one is served, one is called.
+CONTROLLER_AND_CLIENT = """@RestController
+@RequestMapping("/carts")
+class CartController {
+ @GetMapping("/{id}")
+ Cart get(@PathVariable String id) { return null; }
+}
+
+@FeignClient(name = "pricing")
+interface PricingClient {
+ @GetMapping("/prices/{sku}")
+ Price price(@PathVariable String sku);
+}
+"""
+
+EXCHANGE_CLIENT = """package com.example;
+
+@HttpExchange("/customers")
+public interface CustomersClient {
+ @GetExchange("/{id}")
+ Customer get(@PathVariable String id);
+
+ @HttpExchange(method = "POST", url = "/search")
+ List<Customer> search(@RequestBody Query q);
+
+ @HttpExchange("/any")
+ Object any();
+}
+"""
+
+EXCHANGE_CONTROLLER = """@RestController
+@HttpExchange("/customers")
+class CustomersController implements CustomersApi {
+ @GetExchange("/{id}")
+ Customer get(@PathVariable String id) { return null; }
+}
+"""
+
+
+def contracts(content: str, rel_path: str = "Client.java") -> list:
+ suffix = "." + rel_path.rsplit(".", 1)[1]
+ ctx = ScanContext("svc", rel_path, suffix, content, {}, None)
+ return SpringClientsDialect().extract(ctx)
+
+
+def rows(content: str, rel_path: str = "Client.java") -> list[tuple[str, str | None]]:
+ return [(c.contract_id, c.meta.get("host")) for c in contracts(content, rel_path)]
+
+
+class TestFeignInterfaces:
+ def test_a_feign_mapping_is_a_call_to_the_named_service(self) -> None:
+ (c,) = contracts(AUTH_CLIENT)
+ assert c.role == "consumer"
+ assert c.contract_id == "http::POST::/uaa/users"
+ assert c.meta["host"] == "auth-service"
+ assert c.meta["client"] == "feign"
+ assert c.line == 6
+
+ def test_a_url_property_is_a_base_the_resolver_reads(self) -> None:
+ (c,) = contracts(RATES_CLIENT)
+ assert c.contract_id == "http::GET::/latest"
+ assert "host" not in c.meta
+ assert c.meta.get("base_stripped") is True
+
+ def test_client_path_type_mapping_and_method_mapping_compose(self) -> None:
+ # The bare @RequestMapping is sent as a GET; the commented one is not read.
+ assert rows(PREFIXED_CLIENT) == [
+ ("http::GET::/api/orders/{param}", "orders"),
+ ("http::GET::/api/orders/recent", "orders"),
+ ]
+
+ def test_a_literal_url_is_the_host(self) -> None:
+ assert rows(LITERAL_URL_CLIENT) == [
+ ("http::GET::/repos/{param}/{param}", "api.github.com")
+ ]
+
+ def test_a_path_held_in_a_constant_refuses_the_client(self) -> None:
+ assert contracts(CONSTANT_PATH_CLIENT) == []
+
+ def test_a_url_held_in_a_constant_is_no_host(self) -> None:
+ # The name would place the call at a service the url overrides.
+ assert rows(CONSTANT_URL_CLIENT) == [("http::GET::/orders/{param}", None)]
+
+ def test_kotlin_positional_name(self) -> None:
+ assert rows(KOTLIN_CLIENT, "InventoryClient.kt") == [
+ ("http::POST::/stock/reserve", "inventory")
+ ]
+
+ def test_a_controller_beside_a_client_stays_a_provider(self) -> None:
+ assert rows(CONTROLLER_AND_CLIENT) == [("http::GET::/prices/{param}", "pricing")]
+ ctx = ScanContext("svc", "Cart.java", ".java", CONTROLLER_AND_CLIENT, {}, None)
+ assert [c.contract_id for c in SpringDialect().extract(ctx)] == ["http::GET::/carts/{param}"]
+
+
+class TestHttpExchangeInterfaces:
+ def test_exchange_mappings_compose_onto_the_type_prefix(self) -> None:
+ # `@HttpExchange("/any")` names no verb, and a client sends exactly one.
+ assert rows(EXCHANGE_CLIENT) == [
+ ("http::GET::/customers/{param}", None),
+ ("http::POST::/customers/search", None),
+ ]
+ assert {c.meta["client"] for c in contracts(EXCHANGE_CLIENT)} == {"http-exchange"}
+
+ def test_a_controller_file_serves_its_exchange_mappings(self) -> None:
+ assert contracts(EXCHANGE_CONTROLLER) == []
+
+
+class TestCrossRepoLink:
+ def test_feign_consumer_links_to_the_controller_it_calls(self) -> None:
+ extractor = HttpExtractor()
+ provider = """@RestController
+@RequestMapping("/uaa/users")
+public class UserController {
+ @RequestMapping(method = RequestMethod.POST)
+ public void createUser(@RequestBody User user) {}
+}
+"""
+ providers = extractor.extract(
+ Path("."), "auth-service", files=[("UserController.java", ".java", provider)]
+ )
+ consumers = extractor.extract(
+ Path("."), "account-service", files=[("AuthServiceClient.java", ".java", AUTH_CLIENT)]
+ )
+ assert [c.role for c in providers] == ["provider"]
+ assert [c.role for c in consumers] == ["consumer"]
+ links = match_contracts(providers + consumers)
+ assert [(k.consumer_repo, k.provider_repo) for k in links] == [
+ ("account-service", "auth-service")
+ ]
+
+
+NESTED_ANNOTATION_CLIENT = """@FeignClient(name = "a", configuration = @Cfg(path = "/z", url = "http://x"))
+interface C {
+ @GetMapping("/items")
+ String f();
+}
+"""
+
+CONSTANT_NAME_CLIENT = """@FeignClient(name = Services.ORDERS)
+interface OrdersClient {
+ @GetMapping("/orders/{id}")
+ Order get(@PathVariable String id);
+}
+"""
+
+KOTLIN_ARRAY_CLIENT = """@FeignClient(name = "catalog")
+interface CatalogClient {
+ @GetMapping(path = ["/items", "/products"])
+ fun list(): List<Item>
+}
+"""
+
+
+class TestFeignArguments:
+ def test_a_nested_annotation_s_arguments_are_not_the_client_s(self) -> None:
+ assert rows(NESTED_ANNOTATION_CLIENT) == [("http::GET::/items", "a")]
+
+ def test_a_name_held_in_a_constant_is_no_host(self) -> None:
+ assert rows(CONSTANT_NAME_CLIENT) == [("http::GET::/orders/{param}", None)]
+
+ def test_a_kotlin_path_array_fans_out(self) -> None:
+ assert rows(KOTLIN_ARRAY_CLIENT, "CatalogClient.kt") == [
+ ("http::GET::/items", "catalog"),
+ ("http::GET::/products", "catalog"),
+ ]