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 Kafka clients by their declared type, and Go Kafka libraries (#4534)
Raghav Chamadiya15e5e71e5888
diff --git a/docs/architecture/language-support.md b/docs/architecture/language-support.mdindex eea57aa6e..7bc425cb7 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, Python, NestJS (`@GrpcMethod`), C# (gRPC-dotnet) | Go, Java, Python, C# |-| **Topic** | Kafka (Spring Kafka, kafkajs, kafka-python/confluent, sarama), 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, 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/docs/architecture/workspace.md b/docs/architecture/workspace.mdindex 97de1a955..4acf6f363 100644--- a/docs/architecture/workspace.md+++ b/docs/architecture/workspace.md@@ -339,7 +339,9 @@ support a score, a cycle verdict or an empty impact set.1. Pick the contract type and create one module in `extractors/http/`, `topic/`,`socket/`, `grpc/` or `data/`. A broker or client that fits an existing tableshape (`TopicCall`, `SocketCall`, the gRPC stub rules in `grpc/languages.py`) is- rows in a table, not new code.+ rows in a table, not new code. A client whose methods are too common to read on+ any receiver (`send`, `produce`) is a `ReceiverCall` row: read on the names the+ file declares with the client's type.2. Declare `name` and `extensions` (from `extractors/langs.py`).3. Declare `requires`: tokens one of which every match needs, such as the library'simport or the decorator's name. Each table row declares its own. Usediff --git a/docs/scale/WORKSPACES.md b/docs/scale/WORKSPACES.mdindex 0b099104d..f46df0cc5 100644--- a/docs/scale/WORKSPACES.md+++ b/docs/scale/WORKSPACES.md@@ -167,7 +167,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 Kafka, kafkajs, kafka-python/confluent, sarama), 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, 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` |Socket detection is toggled by `detect_socket` in the `contracts:` block below.diff --git a/packages/core/src/repowise/core/workspace/extractors/calls.py b/packages/core/src/repowise/core/workspace/extractors/calls.pyindex c77b0703c..15e9ec9fa 100644--- a/packages/core/src/repowise/core/workspace/extractors/calls.py+++ b/packages/core/src/repowise/core/workspace/extractors/calls.py@@ -253,6 +253,54 @@ def typed_receivers(content: str, type_re: re.Pattern[str]) -> list[str]:return names+# `KafkaTemplate<String, Order> template;` (Java, C#): the type's generics (two+# levels deep), then the name, then what ends a field, parameter or local.+_GENERIC_ARGS_RE = re.compile(r"<(?:[^<>()]|<(?:[^<>()]|<[^<>()]*>)*>)*>")+_DECLARED_NAME_RE = re.compile(r"\??[ \t]+(?P<name>[A-Za-z_]\w*)[ \t]*[;,)=]")+# `producer = Producer(conf)`, `self._p = Producer(conf)`,+# `var p = new ProducerBuilder<K, V>(cfg)`: a constructed client assigned to a name.+_ASSIGNED_RE = re.compile(+ r"(?<![\w$.])(?:(?:this|self)\s*\.\s*)?(?P<name>[A-Za-z_$][\w$]*)\s*(?::[^=\n]+)?"+ r"(?<![=!<>])=\s*(?:await\s+)?(?:new\s+)?$"+)+_CONSTRUCTED_RE = re.compile(r"\s*(?:<(?:[^<>()]|<[^<>()]*>)*>)?\s*\(")+++def declared_receivers(content: str, type_re: re.Pattern[str]) -> list[str]:+ """Names declared with, or assigned a new instance of, a type *type_re* matches.++ The Java / C# declaration ``KafkaTemplate<K, V> template``, the assignment+ ``p = Producer(conf)`` / ``var p = new ProducerBuilder<K, V>(cfg)``, and the+ annotation ``producer: Producer`` (Python, Kotlin, TypeScript). *type_re*+ bounds its own names (``\\bProducer\\b``) and spells any module qualifier+ it accepts (``(?:confluent_kafka\\.)?``): a type reached through another+ member (``other.Producer``) is not the client's. A member of an instance+ (``self.p = ...``) is named without its qualifier.++ Ceiling: a name holds for the whole file, so a second variable of the same+ name in another method is read as the client too. The caller's gate (the+ client's import) and its verbs keep that rare; scoping names to the+ declaring method is the upgrade path.+ """+ names: dict[str, None] = {}+ for m in type_re.finditer(content):+ start, end = m.start(), m.end()+ before = content[max(0, start - _DECLARATION_WINDOW) : start]+ if before.endswith("."):+ continue+ generics = _GENERIC_ARGS_RE.match(content, end)+ declared = _DECLARED_NAME_RE.match(content, generics.end() if generics else end)+ if declared is not None:+ found = declared+ elif _CONSTRUCTED_RE.match(content, end):+ found = _ASSIGNED_RE.search(before)+ else:+ found = _TYPED_RE.search(before)+ if found is not None:+ names[found.group("name")] = None+ return list(names)++# Whitespace and comments between decorators and the member they decorate._GAP_RE = re.compile(r"(?:\s+|//[^\n]*|/\*.*?\*/)*", re.DOTALL)_DECORATOR_NAME_RE = re.compile(r"@[\w$.]+")@@ -290,6 +338,7 @@ __all__ = ["call_chain","call_sites","code_matches",+ "declared_receivers","decorated_member","file_strings","outside_comments",diff --git a/packages/core/src/repowise/core/workspace/extractors/strings.py b/packages/core/src/repowise/core/workspace/extractors/strings.pyindex 41b79dc06..a200b60ad 100644--- a/packages/core/src/repowise/core/workspace/extractors/strings.py+++ b/packages/core/src/repowise/core/workspace/extractors/strings.py@@ -177,10 +177,13 @@ def call_arguments(content: str, paren_offset: int, close: int | None = None) ->``None`` when the argument list does not close, so a recogniser can tell ascanner failure from a call with no arguments. *close* is the matching- ``)`` when the caller has already found it.+ ``)`` when the caller has already found it. A ``{`` at *paren_offset*+ opens a composite literal (Go ``sarama.ProducerMessage{Topic: t}``), whose+ fields are read as its arguments."""if close is None:- close = match_paren(content, paren_offset)+ closer = "}" if content[paren_offset] == "{" else ")"+ close = match_paren(content, paren_offset, closer=closer)if close < 0:return Noneinner = content[paren_offset + 1 : close]@@ -627,11 +630,14 @@ class Arg:``keys`` match a keyword argument (``queue='jobs'``, ``topics = "a"``) or akey of a map-literal argument (``{ topic: 'a' }``, ``['queue' => 'a']``).- A value that is an array literal yields each element.+ A value that is an array literal yields each element. ``variadic`` reads+ every positional argument from ``pos`` on (``ConsumeTopics("a", "b")``),+ keyword arguments left out."""keys: tuple[str, ...] = ()pos: int | None = None+ variadic: bool = False# One map entry's key: a quoted string or an identifier, then `:` or `=>`.@@ -661,26 +667,47 @@ def _map_entries(text: str) -> list[str] | None:return None+# A typed collection literal's head, before its `{`: `new[]`, `new string[]`,+# `new List<string>` (C#, Java arrays), `[]string` (Go).+_TYPED_COLLECTION_RE = re.compile(+ r"(?:new\s*(?:[A-Za-z_][\w.]*\s*(?:<[^<>]*>)?)?\s*(?:\[\s*\])?|\[\]\s*[A-Za-z_][\w.]*)\s*(?=\{)"+)+# A keyword argument, which a variadic read leaves out (`bootstrap_servers=x`).+_KEYWORD_ARG_RE = re.compile(r"^[A-Za-z_]\w*\s*=(?!=)")+++def _elements(value: str) -> list[str]:+ """*value*'s elements if it is an array or typed collection literal, else ``[value]``."""+ head = _TYPED_COLLECTION_RE.match(value)+ if head is not None and value.endswith("}"):+ value = value[head.end() :]+ if _bracketed(value) and _map_entries(value) is None:+ return [e.strip() for e in split_top_level(value[1:-1], ",") if e.strip()]+ return [value]+++def _keyword_value(args: list[str], keys: tuple[str, ...]) -> str | None:+ """The value of the first keyword argument or map entry named one of *keys*."""+ pattern = _keyword_re(keys)+ for a in args:+ for entry in _map_entries(a) or [a]:+ m = pattern.match(entry)+ if m is not None:+ return m.group("value").strip()+ return None++def select_argument(args: list[str], arg: Arg) -> list[str]:"""The source text of the value(s) *arg* selects from *args*, arrays expanded."""- value: str | None = None- if arg.keys:- pattern = _keyword_re(arg.keys)- for a in args:- for entry in _map_entries(a) or [a]:- m = pattern.match(entry)- if m is not None:- value = m.group("value").strip()- break- if value is not None:- break+ value = _keyword_value(args, arg.keys) if arg.keys else None+ if value is None and arg.variadic and arg.pos is not None:+ rest = [a for a in args[arg.pos :] if not _KEYWORD_ARG_RE.match(a)]+ return [e for a in rest for e in _elements(a)]if value is None and arg.pos is not None and arg.pos < len(args):value = args[arg.pos]if value is None:return []- if _bracketed(value) and _map_entries(value) is None:- return [e.strip() for e in split_top_level(value[1:-1], ",") if e.strip()]- return [value]+ return _elements(value)def resolve_argument(diff --git a/packages/core/src/repowise/core/workspace/extractors/topic/dialect.py b/packages/core/src/repowise/core/workspace/extractors/topic/dialect.pyindex 8b3c02762..21c9645a4 100644--- a/packages/core/src/repowise/core/workspace/extractors/topic/dialect.py+++ b/packages/core/src/repowise/core/workspace/extractors/topic/dialect.py@@ -10,7 +10,9 @@ A value that cannot be settled inside the file is refused.from __future__ import annotations+import refrom dataclasses import dataclass+from functools import lru_cachefrom typing import TYPE_CHECKINGfrom repowise.core.workspace.contracts import (@@ -26,11 +28,10 @@ from repowise.core.workspace.contracts import (from repowise.core.workspace.origins import ContractOriginfrom ..base import line_at-from ..calls import call_sites+from ..calls import call_sites, declared_receiversfrom ..dialect import build_contract, rows_gateif TYPE_CHECKING:- import refrom collections.abc import Callablefrom repowise.core.workspace.contracts import Contract@@ -72,6 +73,44 @@ class TopicCall:pattern: str = ""+@dataclass(frozen=True)+class ReceiverCall:+ """A broker call read on any name the file declares with one of the client's types.++ ``send`` and ``produce`` are too common to read on any receiver, and the+ receiver's name is the author's choice (``KafkaTemplate<K, V> kt``), so the+ file's own declarations of *types* (:func:`..calls.declared_receivers`)+ name the receivers, and ``verbs`` (a regex alternation) are read on those+ alone. The other fields are a :class:`TopicCall`'s.+ """++ types: re.Pattern[str]+ verbs: str+ role: str+ label: str+ extensions: frozenset[str]+ name: Arg+ requires: tuple[str, ...]+ origin: ContractOrigin = ContractOrigin.CLIENT_CALL+++@lru_cache(maxsize=256)+def _receiver_call(row: ReceiverCall, receivers: tuple[str, ...]) -> TopicCall:+ alts = "|".join(re.escape(r) for r in receivers)+ head = re.compile(+ rf"(?<![\w$.])(?:(?:this|self)\s*\.\s*)?(?:{alts})\s*\.\s*(?:{row.verbs})\s*\("+ )+ return TopicCall(+ head=head,+ role=row.role,+ label=row.label,+ extensions=row.extensions,+ name=row.name,+ origin=row.origin,+ requires=row.requires,+ )++def topic_contract(ctx: ScanContext,*,@@ -157,15 +196,35 @@ def call_contracts(class TopicDialect:"""One broker library's calls, for the files whose extension its calls read."""- def __init__(self, name: str, calls: tuple[TopicCall, ...]) -> None:+ def __init__(+ self,+ name: str,+ calls: tuple[TopicCall, ...],+ receivers: tuple[ReceiverCall, ...] = (),+ ) -> None:self.name = nameself.calls = calls- self.extensions = frozenset().union(*(c.extensions for c in calls))- self.requires = rows_gate(calls)+ self.receivers = receivers+ rows = (*receivers, *calls)+ self.extensions = frozenset().union(*(c.extensions for c in rows))+ self.requires = rows_gate(rows)++ def _typed_calls(self, ctx: ScanContext) -> list[TopicCall]:+ """A :class:`TopicCall` per receiver row, on the names this file declares."""+ out: list[TopicCall] = []+ for row in self.receivers:+ if ctx.suffix not in row.extensions or not ctx.has_any(row.requires):+ continue+ names = declared_receivers(ctx.content, row.types)+ if names:+ out.append(_receiver_call(row, tuple(sorted(names))))+ return outdef extract(self, ctx: ScanContext) -> list[Contract]:out: list[Contract] = []- for call, args, m, strings in call_sites(ctx, self.calls):+ # Typed rows first: a call both read is kept with the typed row's origin.+ calls = [*self._typed_calls(ctx), *self.calls]+ for call, args, m, strings in call_sites(ctx, calls):out.extend(call_contracts(ctx, self.name, call, args, m.start(), strings))return out@@ -193,6 +252,7 @@ def last_segment(sep: str) -> Callable[[str], str | None]:__all__ = [+ "ReceiverCall","TopicCall","TopicDialect","last_segment",diff --git a/packages/core/src/repowise/core/workspace/extractors/topic/kafka.py b/packages/core/src/repowise/core/workspace/extractors/topic/kafka.pyindex b5f60350f..ca336947b 100644--- a/packages/core/src/repowise/core/workspace/extractors/topic/kafka.py+++ b/packages/core/src/repowise/core/workspace/extractors/topic/kafka.py@@ -1,4 +1,13 @@-"""Kafka producers and consumers: Spring Kafka, kafkajs, kafka-python / confluent, sarama."""+"""Kafka producers and consumers.++Spring Kafka, kafka-clients, kafkajs, kafka-python, aiokafka, confluent-kafka+(Python and .NET), and Go sarama, segmentio/kafka-go and franz-go. A client+whose calls (``send``, ``produce``, ``subscribe``) are too common to read on+any receiver is a :class:`.dialect.ReceiverCall`: read on the names the file+declares with the client's type, whatever they are called. Go clients name+the topic in a struct literal's ``Topic`` field, read as the literal's+arguments.+"""from __future__ import annotations@@ -7,15 +16,87 @@ import refrom repowise.core.workspace.contracts import TOPIC_PATTERN_REGEXfrom repowise.core.workspace.origins import ContractOrigin-from ..langs import GO, JAVA, JS_TS, PYTHON+from ..langs import CSHARP, GO, JAVA, JS_TS, PYTHONfrom ..strings import Arg, unescape_backslashes-from .dialect import TopicCall, TopicDialect+from .dialect import ReceiverCall, TopicCall, TopicDialect_TOPIC = Arg(keys=("topics", "topic"))_FIRST = Arg(pos=0)+_TOPIC_OR_FIRST = Arg(keys=("topics", "topic"), pos=0)+_GO_TOPIC = Arg(keys=("Topic",))+_SARAMA = ("sarama",)+_KAFKA_GO = ("segmentio/kafka-go",)+_FRANZ = ("franz-go/pkg/kgo",)+_CONFLUENT_PY = ("confluent_kafka",)+_CONFLUENT_NET = ("Confluent.Kafka",)KAFKA = TopicDialect(name="kafka",+ receivers=(+ ReceiverCall(+ types=re.compile(r"\b(?:KafkaTemplate|KafkaOperations|ReactiveKafkaProducerTemplate)\b"),+ verbs="send",+ role="provider",+ label="KafkaTemplate.send",+ extensions=JAVA,+ name=_FIRST,+ requires=("KafkaTemplate", "KafkaOperations", "ReactiveKafkaProducerTemplate"),+ ),+ ReceiverCall(+ types=re.compile(r"\b(?:confluent_kafka\.)?(?:SerializingProducer|Producer)\b"),+ verbs="produce",+ role="provider",+ label="Producer.produce",+ extensions=PYTHON,+ name=Arg(keys=("topic",), pos=0),+ requires=_CONFLUENT_PY,+ ),+ ReceiverCall(+ types=re.compile(r"\b(?:confluent_kafka\.)?(?:DeserializingConsumer|Consumer)\b"),+ verbs="subscribe",+ role="consumer",+ label="Consumer.subscribe",+ extensions=PYTHON,+ name=_TOPIC_OR_FIRST,+ requires=_CONFLUENT_PY,+ ),+ ReceiverCall(+ types=re.compile(r"\b(?:AIO)?KafkaProducer\b"),+ verbs="send|send_and_wait",+ role="provider",+ label="KafkaProducer.send",+ extensions=PYTHON,+ name=Arg(keys=("topic",), pos=0),+ requires=("KafkaProducer",),+ ),+ ReceiverCall(+ types=re.compile(r"\b(?:AIO)?KafkaConsumer\b"),+ verbs="subscribe",+ role="consumer",+ label="KafkaConsumer.subscribe",+ extensions=PYTHON,+ name=_TOPIC_OR_FIRST,+ requires=("KafkaConsumer",),+ ),+ ReceiverCall(+ types=re.compile(r"\b(?:IProducer|ProducerBuilder)\b"),+ verbs="ProduceAsync|Produce",+ role="provider",+ label="IProducer.Produce",+ extensions=CSHARP,+ name=Arg(keys=("topic",), pos=0),+ requires=_CONFLUENT_NET,+ ),+ ReceiverCall(+ types=re.compile(r"\b(?:IConsumer|ConsumerBuilder)\b"),+ verbs="Subscribe",+ role="consumer",+ label="IConsumer.Subscribe",+ extensions=CSHARP,+ name=Arg(keys=("topics", "topic"), pos=0),+ requires=_CONFLUENT_NET,+ ),+ ),calls=(TopicCall(head=re.compile(r"@KafkaListener\s*\("),@@ -64,7 +145,7 @@ KAFKA = TopicDialect(role="consumer",label="KafkaConsumer",extensions=PYTHON,- name=_FIRST,+ name=Arg(pos=0, variadic=True), # `KafkaConsumer(*topics, group_id=...)`requires=("KafkaConsumer",),),TopicCall(@@ -84,6 +165,73 @@ KAFKA = TopicDialect(name=_FIRST,requires=("ConsumePartition",),),+ TopicCall(+ head=re.compile(r"new\s+ProducerRecord\s*(?:<[^<>()]*>)?\s*\("),+ role="provider",+ label="ProducerRecord",+ extensions=JAVA,+ name=_FIRST,+ requires=("org.apache.kafka.clients.producer",),+ ),+ TopicCall(+ head=re.compile(r"sarama\.ProducerMessage\s*\{"),+ role="provider",+ label="sarama.ProducerMessage",+ extensions=GO,+ name=_GO_TOPIC,+ requires=_SARAMA,+ ),+ TopicCall(+ # ConsumerGroup.Consume(ctx, []string{"orders"}, handler): the topic+ # list literal is required, as `Consume` alone is any receiver's.+ head=re.compile(r"\.Consume\s*\((?=[^,]*,\s*\[\]string\s*\{)"),+ role="consumer",+ label="ConsumerGroup.Consume",+ extensions=GO,+ name=Arg(pos=1),+ requires=("ConsumerGroup",),+ ),+ TopicCall(+ # Not `kafka.Message{Topic: t}`: a consumer builds one to commit an offset.+ head=re.compile(r"kafka\.(?:Writer|WriterConfig)\s*\{"),+ role="provider",+ label="kafka.Writer",+ extensions=GO,+ name=_GO_TOPIC,+ requires=_KAFKA_GO,+ ),+ TopicCall(+ head=re.compile(r"kafka\.ReaderConfig\s*\{"),+ role="consumer",+ label="kafka.ReaderConfig",+ extensions=GO,+ name=Arg(keys=("Topic", "GroupTopics")),+ requires=_KAFKA_GO,+ ),+ TopicCall(+ head=re.compile(r"kgo\.Record\s*\{"),+ role="provider",+ label="kgo.Record",+ extensions=GO,+ name=_GO_TOPIC,+ requires=_FRANZ,+ ),+ TopicCall(+ head=re.compile(r"kgo\.DefaultProduceTopic\s*\("),+ role="provider",+ label="kgo.DefaultProduceTopic",+ extensions=GO,+ name=_FIRST,+ requires=_FRANZ,+ ),+ TopicCall(+ head=re.compile(r"kgo\.ConsumeTopics\s*\("),+ role="consumer",+ label="kgo.ConsumeTopics",+ extensions=GO,+ name=Arg(pos=0, variadic=True),+ requires=_FRANZ,+ ),),)diff --git a/tests/unit/workspace/test_dialect_registry.py b/tests/unit/workspace/test_dialect_registry.pyindex ab0c9e6d9..48c7dce6f 100644--- a/tests/unit/workspace/test_dialect_registry.py+++ b/tests/unit/workspace/test_dialect_registry.py@@ -54,6 +54,9 @@ def test_every_table_row_declares_a_gate_and_an_origin(dialect) -> None:for row in rows:assert row.requires, f"{dialect.name}: a row with head {row.head.pattern!r} has no gate"assert isinstance(row.origin, ContractOrigin), f"{dialect.name}: {row.head.pattern!r}"+ for row in getattr(dialect, "receivers", ()): # rows read on a typed receiver+ assert row.requires, f"{dialect.name}: receiver row {row.label!r} has no gate"+ assert isinstance(row.origin, ContractOrigin), f"{dialect.name}: {row.label!r}"language = getattr(dialect, "_lang", None) # a gRPC stub tablefor rule in getattr(language, "rules", ()):assert isinstance(rule.origin, ContractOrigin), f"{dialect.name}: {rule.pattern.pattern!r}"diff --git a/tests/unit/workspace/test_origins.py b/tests/unit/workspace/test_origins.pyindex 9991238ea..ee81e1095 100644--- a/tests/unit/workspace/test_origins.py+++ b/tests/unit/workspace/test_origins.py@@ -39,6 +39,7 @@ def _declared_rows() -> list[object]:rows: list[object] = list(_HANDLERS)for dialect in (*topic.DIALECTS, *socket.DIALECTS):rows.extend(getattr(dialect, "calls", ()))+ rows.extend(getattr(dialect, "receivers", ()))for lang in grpc.LANGUAGES:rows.extend(lang.rules)return rowsdiff --git a/tests/unit/workspace/test_strings.py b/tests/unit/workspace/test_strings.pyindex 93a503801..0207d58ac 100644--- a/tests/unit/workspace/test_strings.py+++ b/tests/unit/workspace/test_strings.py@@ -9,6 +9,7 @@ from repowise.core.workspace.extractors.strings import (PHP_SYNTAX,PYTHON_SYNTAX,Arg,+ call_arguments,inline_names,resolve_argument,resolve_string,@@ -31,12 +32,22 @@ class TestSelectArgument:(["['orders:a', 'orders:b']"], Arg(pos=0), ["'orders:a'", "'orders:b'"]),(["'a'"], Arg(pos=3), []),(["x == 'a'"], Arg(keys=("x",)), []),+ (['new[] { "a", "b" }'], Arg(pos=0), ['"a"', '"b"']),+ (['new List<string> { "a" }'], Arg(pos=0), ['"a"']),+ (["ctx", '[]string{"a", "b"}'], Arg(pos=1), ['"a"', '"b"']),+ (["'a'", "'b'", "group_id='g'"], Arg(pos=0, variadic=True), ["'a'", "'b'"]),+ (['"a"', '[]string{"b"}'], Arg(pos=0, variadic=True), ['"a"', '"b"']),],)def test_selection(self, args: list[str], arg: Arg, expected: list[str]) -> None:assert select_argument(args, arg) == expected+def test_a_composite_literal_reads_its_fields_as_arguments() -> None:+ src = 'm := &sarama.ProducerMessage{Topic: "orders", Value: enc(f(x))}'+ assert call_arguments(src, src.index("{")) == ['Topic: "orders"', "Value: enc(f(x))"]++class TestResolveArgument:def test_a_constant_folds(self) -> None:got = resolve_argument(["QUEUE"], Arg(pos=0), PYTHON_SYNTAX, {"QUEUE": "'jobs'"})diff --git a/tests/unit/workspace/test_topic_dialects.py b/tests/unit/workspace/test_topic_dialects.pyindex a54ad395d..0f5d615fe 100644--- a/tests/unit/workspace/test_topic_dialects.py+++ b/tests/unit/workspace/test_topic_dialects.py@@ -7,6 +7,7 @@ from pathlib import Pathimport pytestfrom repowise.core.workspace.extractors.topic import TopicExtractor+from repowise.core.workspace.origins import ContractOrigindef _extract(tmp_path: Path, rel: str, content: str, alias: str = "svc"):@@ -454,3 +455,185 @@ class TestNestMicroservices:def test_handlers_need_the_microservices_import(self, tmp_path: Path) -> None:assert _extract(tmp_path, "c.ts", "@EventPattern('x')\nf() {}\n") == []+++class TestKafkaByReceiverType:+ """A client read on whatever name the file declares it with."""++ def test_kafka_template_under_any_name(self, tmp_path: Path) -> None:+ src = (+ "import org.springframework.kafka.core.KafkaTemplate;\n"+ "class Pub {\n"+ " private final KafkaTemplate<String, Map<String, Object>> kt;\n"+ ' void f() { kt.send("orders", o); this.kt.send("refunds", o); other.send("x", o); }\n'+ "}\n"+ )+ rows = _extract(tmp_path, "Pub.java", src)+ assert sorted(c.contract_id for c in rows) == ["topic::orders", "topic::refunds"]+ assert {c.origin for c in rows} == {ContractOrigin.CLIENT_CALL}++ def test_a_kafka_template_bean_method_names_no_receiver(self, tmp_path: Path) -> None:+ src = (+ "import org.springframework.kafka.core.KafkaTemplate;\n"+ "KafkaTemplate<String, String> kafkaTemplate(ProducerFactory pf) { return null; }\n"+ 'void f() { template.send("orders", o); }\n'+ )+ assert _extract(tmp_path, "Cfg.java", src) == []++ def test_kafka_clients_producer_record(self, tmp_path: Path) -> None:+ src = (+ "import org.apache.kafka.clients.producer.ProducerRecord;\n"+ 'p.send(new ProducerRecord<>("payments", k, v));\n'+ )+ c = _one(_extract(tmp_path, "P.java", src), "provider")+ assert c.contract_id == "topic::payments"++ def test_confluent_python_on_a_member_and_a_local(self, tmp_path: Path) -> None:+ src = (+ "from confluent_kafka import Producer, Consumer\n"+ "class P:\n"+ " def __init__(self, conf):\n"+ " self._p = Producer(conf)\n"+ " c = Consumer(conf)\n"+ " c.subscribe(['shipments', 'returns'])\n"+ " def go(self):\n"+ " self._p.produce('invoices', value=b'x')\n"+ )+ rows = _extract(tmp_path, "pub.py", src)+ assert {(c.role, c.contract_id) for c in rows} == {+ ("consumer", "topic::shipments"),+ ("consumer", "topic::returns"),+ ("provider", "topic::invoices"),+ }++ def test_a_qualified_constructor_is_read_only_through_confluent(self, tmp_path: Path) -> None:+ src = (+ "import confluent_kafka\n"+ "p = confluent_kafka.Producer(conf)\n"+ "p.produce('invoices')\n"+ "q = other.Producer(conf)\n"+ "q.produce('nothere')\n"+ )+ rows = _extract(tmp_path, "pub.py", src)+ assert [c.contract_id for c in rows] == ["topic::invoices"]++ def test_a_producer_class_without_confluent_is_not_read(self, tmp_path: Path) -> None:+ src = "p = Producer(conf)\np.produce('invoices')\n"+ assert _extract(tmp_path, "pub.py", src) == []++ def test_kafka_python_and_aiokafka(self, tmp_path: Path) -> None:+ src = (+ "from kafka import KafkaProducer, KafkaConsumer\n"+ "from aiokafka import AIOKafkaProducer\n"+ "pub = KafkaProducer(bootstrap_servers='b')\n"+ "pub.send('audit', b'x')\n"+ "aio = AIOKafkaProducer(bootstrap_servers='b')\n"+ "await aio.send_and_wait('metrics', b'x')\n"+ "cons = KafkaConsumer('a1', 'a2', group_id='g')\n"+ )+ rows = _extract(tmp_path, "kp.py", src)+ assert {(c.role, c.contract_id) for c in rows} == {+ ("provider", "topic::audit"),+ ("provider", "topic::metrics"),+ ("consumer", "topic::a1"),+ ("consumer", "topic::a2"),+ }++ def test_confluent_dotnet(self, tmp_path: Path) -> None:+ src = (+ "using Confluent.Kafka;\n"+ "public class Pub {\n"+ " private readonly IProducer<Null, string> _producer;\n"+ " public Pub(IConsumer<Ignore, string> consumer) {\n"+ ' consumer.Subscribe(new[] { "in.a", "in.b" });\n'+ " }\n"+ " void Build(ProducerConfig cfg) {\n"+ " using var p = new ProducerBuilder<Null, string>(cfg).Build();\n"+ ' p.Produce("out.b", m);\n'+ " }\n"+ ' async Task Go() { await _producer.ProduceAsync("out.a", m); }\n'+ "}\n"+ )+ rows = _extract(tmp_path, "Pub.cs", src)+ assert {(c.role, c.contract_id) for c in rows} == {+ ("consumer", "topic::in.a"),+ ("consumer", "topic::in.b"),+ ("provider", "topic::out.a"),+ ("provider", "topic::out.b"),+ }++ def test_dotnet_needs_the_confluent_import(self, tmp_path: Path) -> None:+ src = 'class P { IProducer<string> p; void F() { p.Produce("x", m); } }\n'+ assert _extract(tmp_path, "P.cs", src) == []++ def test_a_commented_out_send_is_not_read(self, tmp_path: Path) -> None:+ src = (+ "import org.springframework.kafka.core.KafkaTemplate;\n"+ "KafkaTemplate<String, String> kt;\n"+ '// kt.send("orders", o);\n'+ )+ assert _extract(tmp_path, "Pub.java", src) == []+++class TestGoKafka:+ def test_sarama_message_and_consumer_group(self, tmp_path: Path) -> None:+ src = (+ 'import "github.com/IBM/sarama"\n'+ 'const Orders = "orders"\n'+ "var group sarama.ConsumerGroup\n"+ "msg := &sarama.ProducerMessage{Topic: Orders, Value: sarama.StringEncoder(b)}\n"+ 'group.Consume(ctx, []string{"payments"}, h)\n'+ )+ rows = _extract(tmp_path, "main.go", src)+ assert {(c.role, c.contract_id) for c in rows} == {+ ("provider", "topic::orders"),+ ("consumer", "topic::payments"),+ }++ def test_segmentio_writer_and_reader(self, tmp_path: Path) -> None:+ src = (+ 'import kafka "github.com/segmentio/kafka-go"\n'+ 'w := &kafka.Writer{Addr: kafka.TCP("b"), Topic: "out"}\n'+ 'r := kafka.NewReader(kafka.ReaderConfig{Brokers: []string{"b"}, Topic: "in"})\n'+ )+ rows = _extract(tmp_path, "main.go", src)+ assert {(c.role, c.contract_id) for c in rows} == {+ ("provider", "topic::out"),+ ("consumer", "topic::in"),+ }++ def test_franz_go(self, tmp_path: Path) -> None:+ src = (+ 'import "github.com/twmb/franz-go/pkg/kgo"\n'+ 'cl, _ := kgo.NewClient(kgo.ConsumeTopics("a", "b"))\n'+ 'cl.Produce(ctx, &kgo.Record{Topic: "c", Value: v}, nil)\n'+ )+ rows = _extract(tmp_path, "main.go", src)+ assert {(c.role, c.contract_id) for c in rows} == {+ ("consumer", "topic::a"),+ ("consumer", "topic::b"),+ ("provider", "topic::c"),+ }++ def test_a_consume_without_a_topic_list_is_not_read(self, tmp_path: Path) -> None:+ src = (+ 'import "github.com/IBM/sarama"\n'+ "var g sarama.ConsumerGroup\n"+ 'db.Consume(ctx, "x")\n'+ )+ assert _extract(tmp_path, "main.go", src) == []++ def test_a_segmentio_message_is_not_a_publish(self, tmp_path: Path) -> None:+ src = (+ 'import kafka "github.com/segmentio/kafka-go"\n'+ 'r.CommitMessages(ctx, kafka.Message{Topic: "in", Offset: 4})\n'+ )+ assert _extract(tmp_path, "main.go", src) == []++ def test_go_shapes_need_their_library(self, tmp_path: Path) -> None:+ src = (+ 'w := &kafka.Writer{Topic: "out"}\n'+ 'group.Consume(ctx, []string{"payments"}, h)\n'+ 'r := kgo.Record{Topic: "c"}\n'+ )+ assert _extract(tmp_path, "main.go", src) == []