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 Azure Functions HttpTrigger routes as HTTP providers (#4547)

Raghav Chamadiyac5fce6a8a513
diff --git a/docs/scale/WORKSPACES.md b/docs/scale/WORKSPACES.md
index eb3848593..bb7d3024d 100644
--- a/docs/scale/WORKSPACES.md
+++ b/docs/scale/WORKSPACES.md
@@ -147,6 +147,7 @@ Scans source files for HTTP routes, gRPC services, database tables, message topi
| Ruby | | HTTParty, RestClient, Faraday, Net::HTTP |
| Rust | Axum, Actix, Rocket | reqwest |
| Apex | `@RestResource` classes (`/services/apexrest` + `urlMapping`) | `HttpRequest` callouts (literal endpoint and verb) |
+| C# (Azure Functions) | `[HttpTrigger]` routes under the default `/api` prefix; the function name when no `Route` is set | |
| Any | OpenAPI 3.x documents | |
**Database tables:**
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 f1cb15dd7..cd6c1cc8f 100644
--- a/packages/core/src/repowise/core/workspace/extractors/http/__init__.py
+++ b/packages/core/src/repowise/core/workspace/extractors/http/__init__.py
@@ -22,6 +22,7 @@ from ..langs import PYTHON
from .apex_callouts import ApexCalloutsDialect
from .apex_rest import ApexRestDialect
from .aspnet import AspNetDialect
+from .azure_functions import AzureFunctionsDialect
from .csharp_http import CSharpHttpDialect
from .django import DjangoDialect
from .express import ExpressDialect
@@ -73,6 +74,7 @@ PROVIDER_DIALECTS: tuple[ContractDialect, ...] = (
NextAppDialect(),
RemixDialect(),
ApexRestDialect(),
+ AzureFunctionsDialect(),
)
# HTTP-client call recognisers (one client/language each).
diff --git a/packages/core/src/repowise/core/workspace/extractors/http/azure_functions.py b/packages/core/src/repowise/core/workspace/extractors/http/azure_functions.py
new file mode 100644
index 000000000..1fe34760d
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/extractors/http/azure_functions.py
@@ -0,0 +1,120 @@
+"""Azure Functions (C#) HTTP trigger dialect.
+
+A function serves HTTP through the trigger attribute on its request parameter,
+in both the in-process and the isolated worker model::
+
+ [FunctionName("GetOrder")] // isolated: [Function("GetOrder")]
+ public static IActionResult Run(
+ [HttpTrigger(AuthorizationLevel.Function, "get", Route = "orders/{id}")] HttpRequest req)
+
+The route is ``Route``, or the function's name when the attribute sets none,
+served under the host's route prefix. A trigger that lists no method accepts
+every verb, so like Express ``all`` it names no single route and is skipped.
+"""
+
+from __future__ import annotations
+
+import re
+from typing import TYPE_CHECKING
+
+from repowise.core.ingestion.framework_routes import HTTP_METHODS
+
+from ..base import line_at
+from ..calls import Call, call_sites
+from ..langs import CSHARP
+from ..strings import Arg, select_argument
+from .dialect import build_provider_contract
+from .mounts import compose_prefix
+
+if TYPE_CHECKING:
+ from repowise.core.workspace.contracts import Contract
+
+ from ..base import ScanContext
+ from ..calls import FileStrings
+
+_TRIGGER = Call(
+ head=re.compile(r"\[\s*(?:[\w.]+\.)?HttpTrigger(?:Attribute)?\s*\("),
+ extensions=CSHARP,
+ requires=("HttpTrigger",),
+)
+# [FunctionName("X")] (in-process) and [Function("X")] (isolated worker).
+_NAME = Call(
+ head=re.compile(r"\[\s*(?:[\w.]+\.)?(?:FunctionName|Function)(?:Attribute)?\s*\("),
+ extensions=CSHARP,
+ requires=("Function",),
+)
+_ROUTE = Arg(keys=("Route",))
+_NAMEOF_RE = re.compile(r"nameof\s*\(\s*(?:[\w.]+\.)?(\w+)\s*\)")
+_PROPERTY_RE = re.compile(r"\w+\s*=(?!=)")
+
+# The host's default `extensions.http.routePrefix`. Ceiling: a host.json that
+# changes it is not read (a .json walk for one key), so such an app's routes
+# miss their callers rather than link wrongly; read host.json when an estate
+# shows it.
+_ROUTE_PREFIX = "api"
+
+
+def _function_name(args: list[str], strings: FileStrings) -> str | None:
+ if not args:
+ return None
+ m = _NAMEOF_RE.fullmatch(args[0])
+ return m.group(1) if m else strings.text(args[0])
+
+
+def _own_name(content: str, names: list[tuple[int, str | None]], trigger: int) -> str | None:
+ """The name attribute of the function whose parameter holds *trigger*.
+
+ The last one before it, and only when no member body or statement
+ (``{`` / ``;``) lies between, so a timer function's or any other
+ member's name is never borrowed.
+ """
+ before = [n for n in names if n[0] < trigger]
+ if not before:
+ return None
+ start, name = before[-1]
+ gap = content[start:trigger]
+ return None if "{" in gap or ";" in gap else name
+
+
+class AzureFunctionsDialect:
+ name = "azure-functions"
+ extensions = CSHARP
+ requires = _TRIGGER.requires
+
+ def extract(self, ctx: ScanContext) -> list[Contract]:
+ triggers = list(call_sites(ctx, (_TRIGGER,), empty=True))
+ if not triggers:
+ return []
+ strings = triggers[0][3]
+ # Unreadable names stay in (as None) so they still claim their function.
+ names = sorted(
+ (m.start(), _function_name(args, strings))
+ for _, args, m, _ in call_sites(ctx, (_NAME,), strings)
+ )
+
+ out: list[Contract] = []
+ for _, args, m, _ in triggers:
+ verbs = {
+ text.upper()
+ for a in args
+ if not _PROPERTY_RE.match(a) and (text := strings.text(a))
+ } & HTTP_METHODS
+ if not verbs:
+ continue
+ route_expr = select_argument(args, _ROUTE)
+ route = strings.text(route_expr[0]) if route_expr and route_expr[0] != "null" else ""
+ if route == "": # unset or empty: Azure serves the function's name
+ route = _own_name(ctx.content, names, m.start())
+ if route is None or "${" in route:
+ continue # a route this file cannot spell
+ for verb in sorted(verbs):
+ c = build_provider_contract(
+ ctx,
+ method=verb,
+ path_raw=compose_prefix(_ROUTE_PREFIX, route),
+ framework="azure-functions",
+ line=line_at(ctx.content, m.start()),
+ )
+ if c is not None:
+ out.append(c)
+ return out
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 259dcb25d..e1b61866b 100644
--- a/packages/core/src/repowise/core/workspace/extractors/http/paths.py
+++ b/packages/core/src/repowise/core/workspace/extractors/http/paths.py
@@ -11,6 +11,9 @@ import re
from ..strings import match_paren
+# `{id?}`, `{id:int?}`, `{*rest?}`: a route parameter marked optional.
+_OPTIONAL_PARAM_RE = re.compile(r"\{(\*{0,2}[A-Za-z_]\w*(?::[^{}?]*)?)\?\}")
+
def normalize_http_path(path: str) -> str:
"""Normalize an HTTP path for matching.
@@ -21,8 +24,12 @@ def normalize_http_path(path: str) -> str:
3. Lowercase
4. Strip trailing slash (but keep root ``/``)
5. Unify param styles: ``:param``, ``{param}``, ``[param]`` → ``{param}``
+
+ An optional route parameter (ASP.NET and Laravel ``{id?}``,
+ ``{id:int?}``) loses its ``?`` first, so the query-string cut does not
+ end the path inside the brace.
"""
- s = path.strip().split("?")[0].lower()
+ s = _OPTIONAL_PARAM_RE.sub(r"{\1}", path.strip()).split("?")[0].lower()
if s != "/":
s = s.rstrip("/")
# ASP.NET routes commonly omit the leading slash; add one so all
diff --git a/tests/unit/workspace/test_contracts.py b/tests/unit/workspace/test_contracts.py
index d6ee6636e..819df8aad 100644
--- a/tests/unit/workspace/test_contracts.py
+++ b/tests/unit/workspace/test_contracts.py
@@ -56,6 +56,11 @@ class TestNormalizeHttpPath:
def test_root_path(self) -> None:
assert normalize_http_path("/") == "/"
+ def test_optional_param_keeps_its_brace_and_the_rest_of_the_path(self) -> None:
+ assert normalize_http_path("/brand/{brandId?}") == "/brand/{param}"
+ assert normalize_http_path("orders/{id:int?}/lines") == "/orders/{param}/lines"
+ assert normalize_http_path("/users/{id}?page={page}") == "/users/{param}"
+
# ---------------------------------------------------------------------------
# HttpExtractor
diff --git a/tests/unit/workspace/test_dotnet_workspace.py b/tests/unit/workspace/test_dotnet_workspace.py
index 4d717e519..fd5d64d30 100644
--- a/tests/unit/workspace/test_dotnet_workspace.py
+++ b/tests/unit/workspace/test_dotnet_workspace.py
@@ -97,6 +97,77 @@ class TestAspNetHttpExtraction:
)
+class TestAzureFunctionsHttpTriggers:
+ def _providers(self, tmp_path: Path, source: str) -> set[tuple[str, str]]:
+ (tmp_path / "Orders.cs").write_text(dedent(source))
+ contracts = HttpExtractor().extract(tmp_path, repo_alias="fn")
+ return {
+ (c.meta["method"], c.meta["path"])
+ for c in contracts
+ if c.role == "provider" and c.meta.get("framework") == "azure-functions"
+ }
+
+ def test_route_and_methods_are_served_under_the_api_prefix(self, tmp_path: Path) -> None:
+ found = self._providers(
+ tmp_path,
+ """\
+ public static class Orders {
+ [FunctionName("GetOrder")]
+ public static Task<IActionResult> Run(
+ [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "orders/{id:int?}")] HttpRequest req) => null;
+ }
+ """,
+ )
+ assert found == {("GET", "/api/orders/{param}"), ("POST", "/api/orders/{param}")}
+
+ def test_without_a_route_the_function_name_is_the_route(self, tmp_path: Path) -> None:
+ found = self._providers(
+ tmp_path,
+ """\
+ public class Orders {
+ [Function(nameof(ListOrders))]
+ public HttpResponseData ListOrders([HttpTrigger(AuthorizationLevel.Anonymous, "get")] HttpRequestData req) => null;
+
+ [Function("Ping")]
+ public HttpResponseData Ping([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequestData req) => null;
+ }
+ """,
+ )
+ assert found == {("GET", "/api/listorders"), ("GET", "/api/ping")}
+
+ def test_a_trigger_that_cannot_be_spelled_is_skipped(self, tmp_path: Path) -> None:
+ found = self._providers(
+ tmp_path,
+ """\
+ public class Orders {
+ [Function("Any")]
+ public HttpResponseData AnyVerb([HttpTrigger(AuthorizationLevel.Anonymous, Route = "any")] HttpRequestData req) => null;
+
+ [Function(Names.Hidden)]
+ public HttpResponseData Hidden([HttpTrigger(AuthorizationLevel.Anonymous, "delete")] HttpRequestData req) => null;
+
+ // [HttpTrigger(AuthorizationLevel.Anonymous, "put", Route = "commented")]
+
+ [Function("Nightly")]
+ public void Nightly([TimerTrigger("0 0 * * *")] TimerInfo t) { }
+ public HttpResponseData Unnamed([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "")] HttpRequestData req) => null;
+ }
+ """,
+ )
+ # No method: every verb, no single route. A trigger whose own name is
+ # unreadable or missing never borrows another member's.
+ assert found == set()
+
+ def test_an_optional_minimal_api_parameter_keeps_the_path(self, tmp_path: Path) -> None:
+ (tmp_path / "Program.cs").write_text(
+ 'app.MapGet("/items/type/{typeId}/brand/{brandId?}", GetItems);\n'
+ )
+ contracts = HttpExtractor().extract(tmp_path, repo_alias="api")
+ assert [c.meta["path"] for c in contracts if c.role == "provider"] == [
+ "/items/type/{param}/brand/{param}"
+ ]
+
+
# ---------------------------------------------------------------------------
# gRPC-dotnet
# ---------------------------------------------------------------------------