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
fix(workspace): read NATS calls only in files that import a NATS client (#4650)
Raghav Chamadiya74b86a41c496
diff --git a/docs/architecture/language-support.md b/docs/architecture/language-support.mdindex 693a50b1a..ef1c7627a 100644--- a/docs/architecture/language-support.md+++ b/docs/architecture/language-support.md@@ -1312,7 +1312,7 @@ mislead the masker.|----------|-----------|-----------|| **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, 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 |+| **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 (nats.go, jnats, nats.js, nats-py; read only in a file importing one), 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 || **Topic (C# integration events)** | `IntegrationEvent` subclasses constructed and passed to a publish call, keyed by short type name | `AddSubscription<T, TH>`, `Subscribe<T, TH>`, `IIntegrationEventHandler<T>` |diff --git a/docs/scale/WORKSPACES.md b/docs/scale/WORKSPACES.mdindex 9f42173e0..8bc29a38f 100644--- a/docs/scale/WORKSPACES.md+++ b/docs/scale/WORKSPACES.md@@ -168,7 +168,7 @@ Scans source files for HTTP routes, gRPC services, database tables, message topi| Type | Providers | Consumers ||------|-----------|-----------|| gRPC | `.proto` service definitions, plus per-language dialects (Go, Java, Python, C#, TypeScript, NestJS `@GrpcMethod`) | gRPC client stubs |-| Topics | 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 (ioredis/node-redis, redis-py, Laravel `Redis::publish`), BullMQ / Bull (`new Queue`, `@InjectQueue`, flows), SQS and SNS (AWS SDK v2/v3, boto3), NestJS `ClientProxy.emit`/`send`, MassTransit `Publish`/`Send`/`IRequestClient` (C#, VB.NET), Laravel job dispatch (`X::dispatch()->onQueue()`, `dispatch()`, `Queue::push*`, scheduled jobs) | The corresponding consumers (`new Worker`, `@Processor`, `ReceiveMessageCommand`, sqs-consumer, `subscribe`/`psubscribe`, `@EventPattern`/`@MessagePattern`, Laravel `ShouldQueue` classes on the queues they run on, MassTransit `IConsumer<T>`, open-generic consumers and saga events), plus RabbitMQ queue bindings (`bindQueue`, `queue_bind`) |+| Topics | 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 (nats.go, jnats, nats.js, nats-py; read only in a file importing one), Redis pub/sub (ioredis/node-redis, redis-py, Laravel `Redis::publish`), BullMQ / Bull (`new Queue`, `@InjectQueue`, flows), SQS and SNS (AWS SDK v2/v3, boto3), NestJS `ClientProxy.emit`/`send`, MassTransit `Publish`/`Send`/`IRequestClient` (C#, VB.NET), Laravel job dispatch (`X::dispatch()->onQueue()`, `dispatch()`, `Queue::push*`, scheduled jobs) | The corresponding consumers (`new Worker`, `@Processor`, `ReceiveMessageCommand`, sqs-consumer, `subscribe`/`psubscribe`, `@EventPattern`/`@MessagePattern`, Laravel `ShouldQueue` classes on the queues they run on, MassTransit `IConsumer<T>`, open-generic consumers and saga events), plus RabbitMQ queue bindings (`bindQueue`, `queue_bind`) || Socket / WebSocket | SignalR `MapHub<T>("/path")`, FastAPI `@app.websocket("/path")`, `ws` `WebSocketServer({ path })`, NestJS `@WebSocketGateway`; events: socket.io `emit` (server and client), Laravel broadcast events (`broadcastOn` / `broadcastAs`), `Broadcast::on`, Pusher `trigger` | ClientWebSocket `ConnectAsync`, SignalR `HubConnectionBuilder.WithUrl`, NativeWebSocket and WebSocketSharp `new WebSocket(...)`, browser/Node `new WebSocket(url)`; events: socket.io `on` / `@SubscribeMessage`, Laravel Echo `listen` and `useEcho`, pusher-js `bind` || Topics: C# integration events | `new T(...)` of an `IntegrationEvent` subclass the repo declares, reaching `PublishAsync` / `Publish` or a repo method taking an `IntegrationEvent`; the id is the short type name, which the event bus routes by | `AddSubscription<T, TH>()`, `Subscribe<T, TH>()` on a declared event, and `IIntegrationEventHandler<T>` classes for events no registration subscribes || Topics: JMS | Spring `JmsTemplate` / `JmsMessagingTemplate` `convertAndSend` / `send` / `sendAndReceive` / `convertSendAndReceive` on a receiver named for JMS (`jmsTemplate`, `orderJmsTemplate`, `getJmsTemplate()`) with a destination argument; ActiveMQ and IBM MQ `queue://` names read as the bare queue | `@JmsListener(destination = ...)`, `receive` / `receiveAndConvert`, `DefaultMessageListenerContainer.setDestinationName` |diff --git a/packages/core/src/repowise/core/workspace/extractors/topic/__init__.py b/packages/core/src/repowise/core/workspace/extractors/topic/__init__.pyindex 05f3b12bd..3cb234465 100644--- a/packages/core/src/repowise/core/workspace/extractors/topic/__init__.py+++ b/packages/core/src/repowise/core/workspace/extractors/topic/__init__.py@@ -22,8 +22,8 @@ from .rabbitmq import RABBITMQfrom .redis import REDIS# Order settles which broker names a call two dialects read alike: the first-# contract per file, id and role is kept, so Redis (read only where a Redis-# client is imported) precedes NATS (read on any `client.publish`).+# contract per file, id and role is kept, so in a file importing both a Redis+# and a NATS client a `client.publish` is Redis.DIALECTS: tuple[ContractDialect, ...] = (KAFKA,RABBITMQ,diff --git a/packages/core/src/repowise/core/workspace/extractors/topic/nats.py b/packages/core/src/repowise/core/workspace/extractors/topic/nats.pyindex 6e60ca228..8594d8be6 100644--- a/packages/core/src/repowise/core/workspace/extractors/topic/nats.py+++ b/packages/core/src/repowise/core/workspace/extractors/topic/nats.py@@ -1,8 +1,10 @@"""NATS publishers and subscribers.-The receiver must carry a NATS-idiomatic name, so an RxJS or EventEmitter-``subscribe``/``publish`` is not read as a subject. A subscription subject-with ``*`` or ``>`` is a pattern the matcher expands.+``client.publish`` is also MQTT, Ably and every other pub/sub SDK, so a call+is read only in a file importing a NATS client, and its receiver must still+carry a NATS-idiomatic name, so an RxJS or EventEmitter ``subscribe`` beside+one is not read as a subject. A subscription subject with ``*`` or ``>`` is a+pattern the matcher expands."""from __future__ import annotations@@ -17,6 +19,12 @@ from .dialect import TopicCall, TopicDialect_RECEIVER = r"(?:nc|nats|conn|js|client)\s*\.\s*"_LANGUAGES = GO | JAVA | JS_TS | PYTHON+# nats.go (`github.com/nats-io/...`), jnats (`io.nats.client`), nats.js and+# nats.ws (`'nats'`, `@nats-io/...`, `nats.ws`, Deno `npm:nats` / `/x/nats`)+# and nats-py (`import nats`).+_CLIENT = (+ "nats-io/", "io.nats.", "'nats'", '"nats"', "nats.ws", "npm:nats", "/x/nats", "import nats", "from nats"+)NATS = TopicDialect(name="nats",@@ -29,7 +37,7 @@ NATS = TopicDialect(name=Arg(pos=0),kind=TOPIC_KIND_SUBJECT,pattern=TOPIC_PATTERN_NATS,- requires=("Subscribe", "subscribe"),+ requires=_CLIENT,),TopicCall(head=re.compile(_RECEIVER + r"(?:Publish|publish)\s*\("),@@ -38,7 +46,7 @@ NATS = TopicDialect(extensions=_LANGUAGES,name=Arg(pos=0),kind=TOPIC_KIND_SUBJECT,- requires=("Publish", "publish"),+ requires=_CLIENT,),),)diff --git a/tests/unit/workspace/test_async_links.py b/tests/unit/workspace/test_async_links.pyindex 8433b885e..313bbb8d8 100644--- a/tests/unit/workspace/test_async_links.py+++ b/tests/unit/workspace/test_async_links.py@@ -76,8 +76,10 @@ def test_a_bullmq_queue_is_not_a_laravel_queue_of_the_same_name(tmp_path: Path)def test_a_nats_wildcard_subscription(tmp_path: Path) -> None:- api = _repo(tmp_path, "api", {"p.go": 'nc.Publish("orders.created", d)\n'})- audit = _repo(tmp_path, "audit", {"s.ts": "nc.subscribe('orders.>');\n"})+ api = _repo(+ tmp_path, "api", {"p.go": 'import "github.com/nats-io/nats.go"\nnc.Publish("orders.created", d)\n'}+ )+ audit = _repo(tmp_path, "audit", {"s.ts": "import { connect } from 'nats';\nnc.subscribe('orders.>');\n"})assert _links(api, audit) == {("api", "audit", "topic::orders.created")}diff --git a/tests/unit/workspace/test_dialect_registry.py b/tests/unit/workspace/test_dialect_registry.pyindex 48c7dce6f..88f837967 100644--- a/tests/unit/workspace/test_dialect_registry.py+++ b/tests/unit/workspace/test_dialect_registry.py@@ -88,15 +88,18 @@ class _CountingText(str):def test_a_token_is_searched_for_once_per_file_however_many_dialects_name_it() -> None:- # `producer` gates the kafka dialect and two of its rows; `publish` gates- # NATS and one of its rows. Each is looked for once.+ # `producer` gates the kafka dialect and two of its rows; `'nats'` gates+ # NATS and both of its rows. Each is looked for once.counts: dict[str, int] = {}- text = _CountingText("producer.send({ topic: 'orders' })\nnc.publish('audit', x)\n", counts)+ text = _CountingText(+ "import { connect } from 'nats';\nproducer.send({ topic: 'orders' })\nnc.publish('audit', x)\n",+ counts,+ )ctx = ScanContext("svc", "src/a.ts", ".ts", text)for dialect in topic.DIALECTS:run_dialect(dialect, ctx)assert counts.get("producer") == 1- assert counts.get("publish") == 1+ assert counts.get("'nats'") == 1def test_a_dialect_is_not_run_on_a_file_without_its_tokens() -> None:diff --git a/tests/unit/workspace/test_extractor_traversal.py b/tests/unit/workspace/test_extractor_traversal.pyindex b1157851a..54479b872 100644--- a/tests/unit/workspace/test_extractor_traversal.py+++ b/tests/unit/workspace/test_extractor_traversal.py@@ -67,12 +67,12 @@ def test_topic_extractor_skips_nested_git_repo(tmp_path: Path) -> None:# A NATS producer in the repo is found; an identical one inside a nested# repo is not (the nested repo is a hard boundary).(tmp_path / "producer.py").write_text(- 'nc.publish("events.user")', encoding="utf-8"+ 'import nats\nnc.publish("events.user")', encoding="utf-8")nested = tmp_path / "bench"nested.mkdir()(nested / ".git").mkdir()- (nested / "other.py").write_text('nc.publish("events.foreign")', encoding="utf-8")+ (nested / "other.py").write_text('import nats\nnc.publish("events.foreign")', encoding="utf-8")contracts = TopicExtractor().extract(tmp_path, "primary")topics = {c.meta["topic"] for c in contracts}diff --git a/tests/unit/workspace/test_topic_dialects.py b/tests/unit/workspace/test_topic_dialects.pyindex 13b057d91..8f80d09b6 100644--- a/tests/unit/workspace/test_topic_dialects.py+++ b/tests/unit/workspace/test_topic_dialects.py@@ -366,9 +366,13 @@ class TestPythonClassConstants:assert (c.contract_id, c.meta["routing_key"]) == ("topic::robot-shop", "orders")+_NATS_GO = 'import "github.com/nats-io/nats.go"\n'+_NATS_TS = "import { connect } from 'nats';\n"++class TestNats:def test_subscribe_and_publish(self, tmp_path: Path) -> None:- src = 'nc.Subscribe("events.created", h)\nnc.Publish("events.deleted", d)\n'+ src = _NATS_GO + 'nc.Subscribe("events.created", h)\nnc.Publish("events.deleted", d)\n'rows = _extract(tmp_path, "main.go", src)assert {(c.role, c.contract_id) for c in rows} == {("consumer", "topic::events.created"),@@ -379,28 +383,47 @@ class TestNats:@pytest.mark.parametrize(("rel", "src", "role"),[- ("sub.py", 'await nc.subscribe("events.created", cb=h)\n', "consumer"),- ("Pub.java", 'nc.publish("events.created", data);', "provider"),- ("pub.ts", "nc.publish('events.created', sc.encode(x));", "provider"),+ ("sub.py", 'import nats\nawait nc.subscribe("events.created", cb=h)\n', "consumer"),+ ("Pub.java", 'import io.nats.client.Connection;\nnc.publish("events.created", data);', "provider"),+ ("pub.ts", _NATS_TS + "nc.publish('events.created', sc.encode(x));", "provider"),+ ("pub.mjs", "import { connect } from '@nats-io/transport-node';\nnc.publish('events.created', x);", "provider"),+ ("ws.js", 'import { connect } from "nats.ws";\nnc.publish("events.created", x);', "provider"),+ ("cjs.js", 'const { connect } = require("nats");\nnc.publish("events.created", x);', "provider"),+ ("aio.py", "from nats.aio.client import Client\nawait nc.publish('events.created', b)\n", "provider"),+ ("deno.ts", 'import { connect } from "npm:nats@2";\nnc.publish("events.created", x);', "provider"),],)def test_nats_in_other_languages(self, tmp_path: Path, rel: str, src: str, role: str) -> None:c = _one(_extract(tmp_path, rel, src), role)assert c.contract_id == "topic::events.created"+ @pytest.mark.parametrize(+ ("rel", "src"),+ [+ ("mqtt.js", "const mqtt = require('mqtt');\nclient.publish('home/kitchen/temp', v);\nclient.subscribe('home/#');\n"),+ ("paho.py", "import paho.mqtt.client as mqtt\nclient.publish('home/kitchen/temp', v)\nclient.subscribe('home/#')\n"),+ ("ably.ts", "import * as Ably from 'ably';\nclient.publish('orders', d);\n"),+ ("main.go", 'nc.Publish("events.created", d)\n'),+ ],+ )+ def test_nothing_without_a_nats_client(self, tmp_path: Path, rel: str, src: str) -> None:+ assert _extract(tmp_path, rel, src) == []+def test_an_unrelated_receiver_is_not_nats(self, tmp_path: Path) -> None:- assert _extract(tmp_path, "x.ts", "store.subscribe('state', h);") == []+ assert _extract(tmp_path, "x.ts", _NATS_TS + "store.subscribe('state', h);") == []def test_bare_sub_is_not_a_nats_receiver(self, tmp_path: Path) -> None:- assert _extract(tmp_path, "x.ts", "sub.subscribe('events.created', h);") == []+ assert _extract(tmp_path, "x.ts", _NATS_TS + "sub.subscribe('events.created', h);") == []@pytest.mark.parametrize("subject", ["events.*", "events.>"])def test_a_wildcard_subscription_is_a_pattern(self, tmp_path: Path, subject: str) -> None:- c = _one(_extract(tmp_path, "sub.go", f'nc.Subscribe("{subject}", h)\n'), "consumer")+ src = _NATS_GO + f'nc.Subscribe("{subject}", h)\n'+ c = _one(_extract(tmp_path, "sub.go", src), "consumer")assert c.meta["pattern"] == "nats"def test_a_plain_subject_is_not_a_pattern(self, tmp_path: Path) -> None:- c = _one(_extract(tmp_path, "sub.go", 'nc.Subscribe("events.created", h)\n'), "consumer")+ src = _NATS_GO + 'nc.Subscribe("events.created", h)\n'+ c = _one(_extract(tmp_path, "sub.go", src), "consumer")assert "pattern" not in c.meta