Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(workspace): read C# gRPC clients registered through AddGrpcClient, injected, or named with their namespace (#4541)
Raghav Chamadiya2e4f984a68f9
diff --git a/docs/architecture/language-support.md b/docs/architecture/language-support.mdindex 6e9083fe8..693a50b1a 100644--- a/docs/architecture/language-support.md+++ b/docs/architecture/language-support.md@@ -1311,7 +1311,7 @@ mislead the masker.| Contract | Providers | Consumers ||----------|-----------|-----------|| **HTTP** | Express, Hono, Fastify, Koa, Elysia, NestJS, Next.js, Remix, FastAPI, Flask, Django, Spring, JAX-RS, Micronaut, Laravel, Go, ASP.NET, Axum/Actix/Rocket, OpenAPI 3.x | Client calls in JS/TS, Python, PHP, Java, Kotlin, Go, C#, Ruby and Rust; JS/TS client instances carry their base URL across files |-| **gRPC** | `.proto` IDL, Go, Java (bare or package-qualified `ImplBase`), Python, NestJS (`@GrpcMethod`), Node grpc-js (`server.addService(X.service)`), C# (gRPC-dotnet) | Go, Java, Python, C# |+| **gRPC** | `.proto` IDL, Go, Java (bare or package-qualified `ImplBase`), Python, NestJS (`@GrpcMethod`), Node grpc-js (`server.addService(X.service)`), C# (gRPC-dotnet, primary-constructor impls too) | Go, Java, Python, C# (`new X.XClient(...)`, `AddGrpcClient<X.XClient>`, and the class the client is injected into) || **Topic** | Kafka (Spring `KafkaTemplate` under any name, kafka-clients `ProducerRecord`, kafkajs, kafka-python, aiokafka, confluent-kafka for Python and .NET, Go sarama, segmentio/kafka-go and franz-go), RabbitMQ (Spring AMQP, amqplib, pika, php-amqplib), NATS, Redis pub/sub, BullMQ / Bull, SQS / SNS, NestJS `ClientProxy`, Laravel job dispatch | The same libraries' consumers (including pattern subscriptions and Laravel `ShouldQueue` classes), plus RabbitMQ queue bindings || **Socket** | SignalR `MapHub`, FastAPI `@app.websocket`, `ws`, NestJS gateways; socket.io `emit`, Laravel broadcast events, Pusher `trigger` | ClientWebSocket, SignalR client, NativeWebSocket, WebSocketSharp, `new WebSocket(url)`; socket.io `on`, Laravel Echo, pusher-js || **Data** | DDL `CREATE`/`ALTER`, Alembic `op.create_table`, Laravel `Schema::create`/`Schema::table`, Knex migrations, ORM models (SQLAlchemy, SQLModel, Django, JPA, EF Core, ActiveRecord, Eloquent, Prisma, TypeORM, Sequelize, Drizzle) | SQL string literals in app code (sqlglot-parsed, verb-anchored-regex fallback), Laravel `DB::table`, Knex queries |diff --git a/packages/core/src/repowise/core/workspace/extractors/grpc/languages.py b/packages/core/src/repowise/core/workspace/extractors/grpc/languages.pyindex 3fae5b0f1..a9e3c412e 100644--- a/packages/core/src/repowise/core/workspace/extractors/grpc/languages.py+++ b/packages/core/src/repowise/core/workspace/extractors/grpc/languages.py@@ -35,6 +35,16 @@ _CLIENT_CALL = ContractOrigin.CLIENT_CALL# `new XClient(` names any class so; nothing confirms it is a gRPC stub._NAME_HEURISTIC = ContractOrigin.NAME_HEURISTIC+#: A C# file that talks gRPC: a channel, a call invoker, a DI registration, or a+#: `using` of a namespace with a `Grpc` segment (`Grpc.Core`, `Shop.Basket.Grpc`).+_CSHARP_GRPC_GATE = re.compile(+ r"\bGrpcChannel\b|\bGrpc\.(?:Net|Core)\b|\bCallInvoker\b|\bChannelBase\b"+ r"|\bAddGrpcClient\b|\busing\s+(?:\w+\s*=\s*)?(?:[\w.]+\.)?Grpc\b"+)+#: The client class gRPC-dotnet generates, nested in its service's class:+#: `Basket.BasketClient`, namespace-qualified or not. Group 1 is the service.+_CSHARP_CLIENT_TYPE = r"(?:global::)?(?:[\w.]+\.)?(\w+)\.\1Client"+@dataclass(frozen=True)class _Rule:"""One recognisable shape. Group 1 is always the service name."""@@ -127,17 +137,26 @@ LANGUAGES: tuple[_Language, ...] = (# app.MapGrpcService<GreeterService>()_Rule("provider", re.compile(r"\.\s*MapGrpcService\s*<\s*(\w+)\s*>"),"cs:MapGrpcService<{service}>", "csharp_mapgrpc", _ROUTE_REGISTRATION),- # class Impl : ServiceName.ServiceNameBase+ # class Impl : ServiceName.ServiceNameBase, or class Impl(ILogger log) : ..._Rule("provider",- re.compile(r"class\s+\w+\s*:\s*(?:[\w.]+\.)?(\w+?)\s*\.\s*\1Base\b"),+ re.compile(r"class\s+\w+\s*(?:\([^()]*\)\s*)?:\s*(?:[\w.]+\.)?(\w+?)\s*\.\s*\1Base\b"),"cs:extends {service}.{service}ServiceBase", "csharp_base", _ROUTE_REGISTRATION),- # new AuthServiceClient(channel): TLS and HTTP classes match too, hence the gate.- _Rule("consumer", re.compile(r"\bnew\s+(\w+)Client\s*\("),+ # new AuthServiceClient(channel), new Shop.Basket.BasketClient(channel):+ # TLS and HTTP classes match too, hence the gate.+ _Rule("consumer", re.compile(r"\bnew\s+(?:global::)?(?:[\w.]+\.)?(\w+)Client\s*\("),"cs:new {service}Client", "csharp_client", _NAME_HEURISTIC,- gate=re.compile(- r"\bGrpcChannel\b|\bGrpc\.(?:Net|Core)\b|\bCallInvoker\b|\bChannelBase\b"- r"|\bAddGrpcClient\b|using\s+Grpc\b"- )),+ gate=_CSHARP_GRPC_GATE),+ # services.AddGrpcClient<Basket.BasketClient>(o => ...): the DI registration.+ _Rule("consumer", re.compile(r"\bAddGrpcClient\s*<\s*" + _CSHARP_CLIENT_TYPE + r"\s*>"),+ "cs:AddGrpcClient<{service}.{service}Client>", "csharp_add_grpc_client",+ _CLIENT_CALL),+ # The class the client is injected into: a constructor parameter typed by+ # the generated client, or a `using` alias of it.+ _Rule("consumer",+ re.compile(r"(?:\busing\s+\w+\s*=|[(,\]])\s*" + _CSHARP_CLIENT_TYPE+ + r"(?:\s*;|\??\s+\w)"),+ "cs:{service}.{service}Client", "csharp_client_type", _NAME_HEURISTIC,+ gate=_CSHARP_GRPC_GATE),),# The client gate's markers all hold `Grpc`, `CallInvoker` or `Base`.requires=("MapGrpcService", "Base", "Grpc", "CallInvoker"),@@ -158,9 +177,13 @@ class LanguageGrpcDialect:def extract(self, ctx: ScanContext) -> list[Contract]:lang = self._langout: list[Contract] = []+ gates: dict[re.Pattern[str], bool] = {} # a gate several rules share is searched oncefor rule in lang.rules:- if rule.gate is not None and not rule.gate.search(ctx.content):- continue+ if rule.gate is not None:+ if rule.gate not in gates:+ gates[rule.gate] = rule.gate.search(ctx.content) is not None+ if not gates[rule.gate]:+ continuefor m in code_matches(ctx, rule.pattern):service = m.group(1)if rule.role == "consumer" and service.lower().startswith(lang.false_prefixes):diff --git a/tests/unit/workspace/test_grpc_languages.py b/tests/unit/workspace/test_grpc_languages.pyindex 2941d27d6..4c954f5e6 100644--- a/tests/unit/workspace/test_grpc_languages.py+++ b/tests/unit/workspace/test_grpc_languages.py@@ -197,3 +197,99 @@ class TestNodeAddService:"s.addService(pkg.service.Billing.service, impl);\n",)assert [r[0] for r in rows] == ["grpc::Billing/*"]+++class TestCSharpGeneratedClients:+ """gRPC-dotnet nests the client in its service's class: `Basket.BasketClient`."""++ def test_a_dotted_new_names_the_service(self) -> None:+ # eShop's client app: the stub's namespace, the service class, its client.+ rows = _extract(+ ".cs",+ "using Grpc.Net.Client;\n"+ "_client = new BasketGrpcClient.Basket.BasketClient(_channel);\n"+ "var g = new global::Acme.Greeter.GreeterClient(channel);\n",+ )+ assert [(r[0], r[2]) for r in rows] == [+ ("grpc::Basket/*", "cs:new BasketClient"),+ ("grpc::Greeter/*", "cs:new GreeterClient"),+ ]++ def test_an_add_grpc_client_registration_is_a_consumer(self) -> None:+ rows = _extract(+ ".cs",+ "builder.Services.AddGrpcClient<Basket.BasketClient>(o => o.Address = new(\"http://basket-api\"));\n"+ "services.AddGrpcClient< Shop.Rpc.Greeter.GreeterClient >();\n",+ )+ assert rows == [+ (+ "grpc::Basket/*",+ "consumer",+ "cs:AddGrpcClient<Basket.BasketClient>",+ 0.75,+ (("service", "Basket"), ("source", "csharp_add_grpc_client")),+ ),+ (+ "grpc::Greeter/*",+ "consumer",+ "cs:AddGrpcClient<Greeter.GreeterClient>",+ 0.75,+ (("service", "Greeter"), ("source", "csharp_add_grpc_client")),+ ),+ ]++ def test_the_class_the_client_is_injected_into_is_a_consumer(self) -> None:+ # eShop's web app aliases the client; the usual shape is a constructor parameter.+ aliased = (+ "using GrpcBasketClient = eShop.Basket.API.Grpc.Basket.BasketClient;\n"+ "public class BasketService(GrpcBasketClient basketClient) {}\n"+ )+ injected = (+ "using Grpc.Core;\n"+ "public Worker(ILogger<Worker> log, Greeter.GreeterClient client) {}\n"+ )+ assert [(r[0], r[2]) for r in _extract(".cs", aliased)] == [+ ("grpc::Basket/*", "cs:Basket.BasketClient")+ ]+ assert [r[0] for r in _extract(".cs", injected)] == ["grpc::Greeter/*"]+ # An attribute before the parameter, or a nullable one.+ attributed = (+ "using Grpc.Core;\n"+ "public Page([FromServices] Greeter.GreeterClient a, Basket.BasketClient? b) {}\n"+ )+ assert [r[0] for r in _extract(".cs", attributed)] == ["grpc::Greeter/*", "grpc::Basket/*"]++ def test_typeof_nameof_and_generics_are_not_injection(self) -> None:+ rows = _extract(+ ".cs",+ "using Grpc.Core;\n"+ "var t = typeof(Greeter.GreeterClient);\nvar n = nameof(Greeter.GreeterClient);\n"+ "var l = new List<Greeter.GreeterClient>();\n",+ )+ assert rows == []++ def test_an_sdk_named_after_its_namespace_is_not_a_grpc_client(self) -> None:+ # `Stripe.StripeClient` has the generated shape; nothing in the file says gRPC.+ assert not _extract(+ ".cs",+ "using Client = Stripe.StripeClient;\n"+ "public Billing(Stripe.StripeClient client) {}\n"+ "var c = new Stripe.StripeClient(key);\n",+ )++ def test_a_type_that_only_starts_like_the_client_is_not_one(self) -> None:+ rows = _extract(+ ".cs",+ "using Grpc.Core;\n"+ "public Svc(Basket.BasketClientFactory f, Basket.BasketClientOptions o) {}\n",+ )+ assert rows == []++ def test_a_primary_constructor_impl_is_a_provider(self) -> None:+ rows = _extract(+ ".cs",+ "public class BasketService(\n"+ " IBasketRepository repository,\n"+ " ILogger<BasketService> logger) : Basket.BasketBase\n{\n}\n",+ )+ assert [(r[0], r[1]) for r in rows] == [("grpc::Basket/*", "provider")]diff --git a/tests/unit/workspace/test_grpc_shared_idl.py b/tests/unit/workspace/test_grpc_shared_idl.pyindex d32a34114..a3f32ecb2 100644--- a/tests/unit/workspace/test_grpc_shared_idl.py+++ b/tests/unit/workspace/test_grpc_shared_idl.py@@ -201,3 +201,27 @@ class TestProjectGrpcServices:{"src/Web/Web.csproj": project, "src/shared/shop.proto": _PROTO, "api/own.proto": _PROTO},)assert {c.file_path for c in contracts} == {"api/own.proto"}+++class TestCSharpClients:+ def test_di_and_dotted_clients_reach_the_package_qualified_proto(self, tmp_path: Path) -> None:+ # eShop split per project: the server's proto has a package, the clients do not.+ proto = 'syntax = "proto3";\npackage BasketApi;\nservice Basket {\n rpc GetBasket(Req) returns (Res) {}\n}\n'+ web = {+ "Extensions.cs": "builder.Services.AddGrpcClient<Basket.BasketClient>(o => o.Address = new(\"http://basket-api\"));\n",+ }+ app = {+ "BasketService.cs": (+ "using Grpc.Net.Client;\n"+ "var client = new BasketGrpcClient.Basket.BasketClient(GrpcChannel.ForAddress(url));\n"+ ),+ }+ contracts = [+ *_repo(tmp_path, "basket", {"Proto/basket.proto": proto}),+ *_repo(tmp_path, "webapp", web),+ *_repo(tmp_path, "clientapp", app),+ ]+ assert _pairs(contracts) == {+ ("webapp", "basket", "Proto/basket.proto"),+ ("clientapp", "basket", "Proto/basket.proto"),+ }