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): link C# integration events between services by their type name (#4544)

Raghav Chamadiya9eb03006fed6
diff --git a/docs/architecture/language-support.md b/docs/architecture/language-support.md
index 37b79c01b..6b2b763bc 100644
--- a/docs/architecture/language-support.md
+++ b/docs/architecture/language-support.md
@@ -1315,6 +1315,7 @@ mislead the masker.
| **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 |
+| **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>` |
RabbitMQ topics are also read from Go (streadway/amqp, amqp091-go), including
a queue named through its declaration's result (`q.Name`).
diff --git a/docs/scale/WORKSPACES.md b/docs/scale/WORKSPACES.md
index 1bcbd1fbc..7d3567524 100644
--- a/docs/scale/WORKSPACES.md
+++ b/docs/scale/WORKSPACES.md
@@ -169,6 +169,7 @@ Scans source files for HTTP routes, gRPC services, database tables, message topi
| 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`) |
| 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 |
Socket detection is toggled by `detect_socket` in the `contracts:` block below.
A topic, queue or route name is resolved when it is a literal or a constant the
diff --git a/packages/core/src/repowise/core/workspace/extractors/topic/__init__.py b/packages/core/src/repowise/core/workspace/extractors/topic/__init__.py
index 0cbe4e4cf..f0fb37b2d 100644
--- a/packages/core/src/repowise/core/workspace/extractors/topic/__init__.py
+++ b/packages/core/src/repowise/core/workspace/extractors/topic/__init__.py
@@ -11,6 +11,7 @@ from __future__ import annotations
from ..dialect import ContractDialect, DialectExtractor
from .aws import SNS, SQS
from .bullmq import BULLMQ
+from .csharp_events import CSHARP_EVENTS
from .dialect import topic_identity
from .kafka import KAFKA
from .laravel import LARAVEL_QUEUES
@@ -32,6 +33,7 @@ DIALECTS: tuple[ContractDialect, ...] = (
SNS,
NESTJS,
LARAVEL_QUEUES,
+ CSHARP_EVENTS,
)
diff --git a/packages/core/src/repowise/core/workspace/extractors/topic/csharp_events.py b/packages/core/src/repowise/core/workspace/extractors/topic/csharp_events.py
new file mode 100644
index 000000000..cce9ce4b1
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/extractors/topic/csharp_events.py
@@ -0,0 +1,323 @@
+"""C# integration events: an event bus that routes each message by its type's short name.
+
+The eShop event bus, and the many services built from it, publish an
+``IntegrationEvent`` subclass and route it by ``GetType().Name``: the
+RabbitMQ routing key is the short type name, whatever namespace declares it.
+Services share no contract assembly; each re-declares the record it sends or
+receives. So the contract id is ``topic::<short type name>``, which is
+exactly what the transport compares, and two same-named types meet on the
+wire as they meet here.
+
+Three facts have to agree before an end is recorded:
+
+- An event type is a class or record the repo declares deriving from a base in
+ :data:`EVENT_BASES`, directly or through another event type.
+- A publisher is ``new T(...)`` of an event type that reaches a publish call:
+ passed inline (``PublishAsync(new T(..))``) or through the variable it was
+ assigned to, inside the block that declares the variable. A publish call is
+ ``PublishAsync`` / ``Publish``, or a method the repo declares with a
+ parameter of a base type whose name says it publishes, sends or saves (an
+ outbox's ``AddAndSaveEventAsync(IntegrationEvent evt)``); a
+ ``Log(IntegrationEvent e)`` is not one.
+- A subscriber is a subscription row below. A type parameter (``where T :``)
+ is never an event, and a name the repo declares as some other type is not
+ one either.
+
+The facts span files (the base type, the outbox method, the record), so this
+dialect is a repo pass. A ceiling: an event declared only in a shared
+contract repo is read on the subscriber side but has no publisher, since the
+publishing repo does not declare it.
+"""
+
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass, field
+from typing import TYPE_CHECKING
+
+from repowise.core.workspace.contracts import TOPIC_KIND_TOPIC
+from repowise.core.workspace.origins import ContractOrigin
+
+from ..calls import code_matches
+from ..dialect import rows_gate
+from ..langs import CSHARP
+from .dialect import topic_contract
+
+if TYPE_CHECKING:
+ from repowise.core.workspace.contracts import Contract
+
+ from ..base import ScanContext
+
+_BROKER = "integration_event"
+
+#: Base types whose subclasses are integration events.
+EVENT_BASES: tuple[str, ...] = ("IntegrationEvent",)
+
+#: Calls that publish their argument whatever the repo declares.
+_PUBLISH_CALLS = frozenset({"PublishAsync", "Publish"})
+
+
+@dataclass(frozen=True)
+class _Subscription:
+ """One subscription shape; ``event`` is the group naming the event type.
+
+ ``declared`` refuses an event type the repo does not declare (a call name
+ too common to trust alone). ``fallback`` reads the shape only for an event
+ no other row subscribes in the repo: a handler class is how a subscription
+ is wired, but the registration is where it is made.
+ """
+
+ head: re.Pattern[str]
+ label: str
+ origin: ContractOrigin
+ requires: tuple[str, ...]
+ declared: bool = False
+ fallback: bool = False
+
+
+_TYPE = r"(?:global::)?(?P<event>[A-Za-z_][\w.]*)"
+# The handler argument: `XHandler`, or `IIntegrationEventHandler<X>` itself.
+_HANDLER = r"[\w.:]+(?:\s*<[^<>()]*>)?"
+
+SUBSCRIPTIONS: tuple[_Subscription, ...] = (
+ _Subscription(
+ re.compile(rf"\.\s*AddSubscription\s*<\s*{_TYPE}\s*,\s*{_HANDLER}\s*>\s*\("),
+ "AddSubscription",
+ ContractOrigin.CLIENT_CALL,
+ ("AddSubscription",),
+ ),
+ # eShopOnContainers' `eventBus.Subscribe<T, TH>()`.
+ _Subscription(
+ re.compile(rf"\.\s*Subscribe\s*<\s*{_TYPE}\s*,\s*{_HANDLER}\s*>\s*\("),
+ "Subscribe",
+ ContractOrigin.CLIENT_CALL,
+ (".Subscribe",),
+ declared=True,
+ ),
+ _Subscription(
+ re.compile(rf"\bIIntegrationEventHandler\s*<\s*{_TYPE}\s*>"),
+ "IIntegrationEventHandler",
+ ContractOrigin.CLIENT_CALL,
+ ("IIntegrationEventHandler",),
+ fallback=True,
+ ),
+)
+
+# `record X(int A, List<B> C) : IntegrationEvent;`, `class X : Base, IFoo {`.
+_TYPE_DECL_RE = re.compile(
+ r"\b(?:class|record(?:\s+class|\s+struct)?|struct)\s+(?P<name>[A-Za-z_]\w*)"
+ r"\s*(?:<[^<>]*>)?\s*(?:\((?:[^()]|\([^()]*\))*\))?"
+ r"\s*(?::\s*(?P<bases>[^{;]*?))?\s*(?=\{|;|\bwhere\b)"
+)
+_BASE_NAME_RE = re.compile(r"(?:global::)?(?:\w+\.)*(\w+)")
+_TYPE_PARAM_RE = re.compile(r"\bwhere\s+(\w+)\s*:|<\s*(?:in|out)\s+(\w+)")
+# A parameter of an event base type, `AddAndSaveEventAsync(IntegrationEvent evt)`;
+# the method it belongs to is the name before its `(`.
+_BASE_PARAM_RE = re.compile(
+ r"\b(?:" + "|".join(EVENT_BASES) + r")\??\s+@?[A-Za-z_]\w*\s*[,)]"
+)
+_METHOD_NAME_RE = re.compile(r"\b([A-Za-z_]\w*)\s*(?:<[^<>()]*>)?\s*$")
+# A method taking the base type publishes only if its name says so; a logger does not.
+_SINK_VERBS = ("Publish", "Send", "Save", "Enqueue", "Raise", "Dispatch", "Emit")
+_SINK_NAME_RE = re.compile("|".join(_SINK_VERBS))
+# Words that precede a name without declaring it (`return e;`, `await e;`).
+_NOT_A_TYPE = r"(?!(?:return|await|throw|yield|else|new|in|out|ref|is|as|case|goto)\b)"
+_NEW_RE = re.compile(r"\bnew\s+(?:global::)?(?:\w+\.)*(?P<type>[A-Za-z_]\w*)\s*[({]")
+# What precedes `new` in its statement: `var x = `, `x = cond ? (Base)`, `Call(`.
+_ASSIGNED_RE = re.compile(r"(?:^|[\s(])@?(?P<var>[A-Za-z_]\w*)\s*=(?![=>])")
+_INLINE_CALL_RE = re.compile(r"\b(?P<call>[A-Za-z_]\w*)\s*\(\s*(?:\([\w.]+\)\s*)?$")
+_STATEMENT_START = re.compile(r"[;{}]")
+_MAX_STATEMENT = 400
+
+
+@dataclass
+class _Construction:
+ ctx: ScanContext
+ offset: int
+ event: str
+ var: str | None
+ call: str | None
+
+
+@dataclass
+class _Subscribed:
+ ctx: ScanContext
+ offset: int
+ event: str
+ row: _Subscription
+ type_params: frozenset[str]
+
+
+@dataclass
+class _EventPass:
+ bases: dict[str, set[str]] = field(default_factory=dict)
+ sinks: set[str] = field(default_factory=set)
+ constructions: list[_Construction] = field(default_factory=list)
+ subscriptions: list[_Subscribed] = field(default_factory=list)
+
+ def scan(self, ctx: ScanContext) -> None:
+ content = ctx.content
+ for m in code_matches(ctx, _TYPE_DECL_RE):
+ bases = {
+ b.group(1)
+ for part in (m.group("bases") or "").split(",")
+ if (b := _BASE_NAME_RE.match(part.strip()))
+ }
+ self.bases.setdefault(m.group("name"), set()).update(bases)
+ if ctx.has_any(EVENT_BASES):
+ for m in code_matches(ctx, _BASE_PARAM_RE):
+ head = content[max(0, m.start() - _MAX_STATEMENT) : m.start()]
+ open_paren = head.rfind("(")
+ if open_paren < 0 or ")" in head[open_paren:]:
+ continue
+ name = _METHOD_NAME_RE.search(head[:open_paren])
+ if name and _SINK_NAME_RE.search(name.group(1)):
+ self.sinks.add(name.group(1))
+ if "new" in content:
+ for m in code_matches(ctx, _NEW_RE):
+ self.constructions.append(self._construction(ctx, m))
+ type_params: frozenset[str] | None = None
+ for row in SUBSCRIPTIONS:
+ if not ctx.has_any(row.requires):
+ continue
+ for m in code_matches(ctx, row.head):
+ if type_params is None:
+ type_params = frozenset(
+ a or b for a, b in _TYPE_PARAM_RE.findall(content)
+ )
+ event = m.group("event").rpartition(".")[2]
+ self.subscriptions.append(_Subscribed(ctx, m.start(), event, row, type_params))
+
+ @staticmethod
+ def _construction(ctx: ScanContext, m: re.Match[str]) -> _Construction:
+ content = ctx.content
+ start = m.start()
+ window = content[max(0, start - _MAX_STATEMENT) : start]
+ stops = list(_STATEMENT_START.finditer(window))
+ statement = window[stops[-1].end() :] if stops else window
+ inline = _INLINE_CALL_RE.search(statement)
+ assigned = _ASSIGNED_RE.search(statement)
+ return _Construction(
+ ctx,
+ start,
+ m.group("type"),
+ assigned.group("var") if assigned else None,
+ inline.group("call") if inline else None,
+ )
+
+ def _events(self) -> set[str]:
+ events: set[str] = set()
+ known = set(EVENT_BASES)
+ changed = True
+ while changed:
+ changed = False
+ for name, bases in self.bases.items():
+ if name not in events and bases & known:
+ events.add(name)
+ known.add(name)
+ changed = True
+ return events
+
+ def finish(self) -> list[Contract]:
+ events = self._events()
+ sinks = _PUBLISH_CALLS | self.sinks
+ out: list[Contract] = []
+ for c in self.constructions:
+ if c.event not in events:
+ continue
+ if c.call in sinks:
+ origin = ContractOrigin.CLIENT_CALL
+ label = c.call
+ elif c.var and _passes_to_sink(c, sinks):
+ origin = ContractOrigin.DATAFLOW
+ label = "new"
+ else:
+ continue
+ out.append(_contract(c.ctx, c.offset, c.event, "provider", label, origin))
+ subscribed = {
+ s.event for s in self.subscriptions if not s.row.fallback and self._accepts(s, events)
+ }
+ for s in self.subscriptions:
+ if (s.row.fallback and s.event in subscribed) or not self._accepts(s, events):
+ continue
+ out.append(_contract(s.ctx, s.offset, s.event, "consumer", s.row.label, s.row.origin))
+ return out
+
+ def _accepts(self, s: _Subscribed, events: set[str]) -> bool:
+ if s.event in events:
+ return True
+ if s.row.declared or s.event in s.type_params or s.event in EVENT_BASES:
+ return False
+ # Declared here as something other than an event: not this bus's message.
+ return s.event not in self.bases
+
+
+def _passes_to_sink(c: _Construction, sinks: set[str]) -> bool:
+ """Whether *c*'s variable reaches a publish call later in the block declaring it.
+
+ The block is the one around the variable's nearest declaration above the
+ construction, so a same-named variable in another method is another value.
+ """
+ content = c.ctx.content
+ var = re.escape(c.var or "")
+ declared = re.compile(rf"(?<![\w.]){_NOT_A_TYPE}[A-Za-z_][\w.<>,?\[\]]*\s+@?{var}\s*[=;]")
+ scope = c.offset
+ for m in declared.finditer(content, 0, c.offset):
+ scope = m.start()
+ end = _block_end(content, scope)
+ names = "|".join(sorted(map(re.escape, sinks)))
+ call = re.compile(rf"\b(?:{names})\s*\(\s*(?:[^()]*,\s*)?@?{var}\s*[,)]")
+ return any(not c.ctx.in_comment(m.start()) for m in call.finditer(content, c.offset, end))
+
+
+def _block_end(content: str, start: int) -> int:
+ """The offset of the brace closing the block *start* sits in (the end of file if none)."""
+ depth = 0
+ for i in range(start, len(content)):
+ ch = content[i]
+ if ch == "{":
+ depth += 1
+ elif ch == "}":
+ depth -= 1
+ if depth < 0:
+ return i
+ return len(content)
+
+
+def _contract(
+ ctx: ScanContext, offset: int, event: str, role: str, label: str, origin: ContractOrigin
+) -> Contract:
+ return topic_contract(
+ ctx,
+ name=event,
+ broker=_BROKER,
+ kind=TOPIC_KIND_TOPIC,
+ role=role,
+ label=label,
+ origin=origin,
+ offset=offset,
+ )
+
+
+class CSharpEventDialect:
+ """Integration events published and subscribed through a C# event bus."""
+
+ name = _BROKER
+ extensions = CSHARP
+ calls = SUBSCRIPTIONS
+ # A publisher file may name neither the base nor `Publish`, only an outbox method.
+ requires = (*EVENT_BASES, *rows_gate(SUBSCRIPTIONS), *_SINK_VERBS)
+
+ def repo_pass(self) -> _EventPass:
+ return _EventPass()
+
+ def extract(self, ctx: ScanContext) -> list[Contract]:
+ """One file on its own (the extractor uses :meth:`repo_pass` instead)."""
+ repo_pass = self.repo_pass()
+ repo_pass.scan(ctx)
+ return repo_pass.finish()
+
+
+CSHARP_EVENTS = CSharpEventDialect()
+
+__all__ = ["CSHARP_EVENTS", "EVENT_BASES", "SUBSCRIPTIONS"]
diff --git a/tests/unit/workspace/test_csharp_events.py b/tests/unit/workspace/test_csharp_events.py
new file mode 100644
index 000000000..d4fb9345f
--- /dev/null
+++ b/tests/unit/workspace/test_csharp_events.py
@@ -0,0 +1,315 @@
+"""C# integration events: publishers and subscribers joined by the event's short type name."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from repowise.core.workspace.contracts import Contract
+from repowise.core.workspace.extractors.topic import TopicExtractor
+from repowise.core.workspace.matching import match_contracts
+from repowise.core.workspace.origins import ContractOrigin
+
+
+def _repo(tmp_path: Path, alias: str, files: dict[str, str]) -> list[Contract]:
+ root = tmp_path / alias
+ for rel, content in files.items():
+ path = root / rel
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(content, encoding="utf-8")
+ return [
+ c for c in TopicExtractor().extract(root, alias) if c.meta.get("broker") == "integration_event"
+ ]
+
+
+def _rows(contracts: list[Contract]) -> set[tuple[str, str, str, int | None]]:
+ return {(c.role, c.contract_id, c.file_path, c.line) for c in contracts}
+
+
+def _event(ns: str, name: str = "OrderPaidIntegrationEvent", base: str = "IntegrationEvent") -> str:
+ return f"namespace {ns};\n\npublic record {name}(int OrderId) : {base};\n"
+
+
+_PAID = "topic::orderpaidintegrationevent"
+
+_PUBLISHER = """namespace Ordering.Handlers;
+
+public class PaidHandler(IEventBus eventBus)
+{
+ public async Task Handle(int id)
+ {
+ var paid = new OrderPaidIntegrationEvent(id);
+ logger.LogInformation("Publishing {Id}", paid.Id);
+ await eventBus.PublishAsync(paid);
+ }
+}
+"""
+
+_SUBSCRIBER = """namespace Catalog;
+
+public static class Extensions
+{
+ public static void AddServices(this IHostApplicationBuilder builder)
+ {
+ builder.AddRabbitMqEventBus("eventbus")
+ .AddSubscription<OrderPaidIntegrationEvent, OrderPaidIntegrationEventHandler>();
+ }
+}
+"""
+
+_HANDLER = """namespace {ns};
+
+public class OrderPaidIntegrationEventHandler : IIntegrationEventHandler<OrderPaidIntegrationEvent>
+{{
+ public Task Handle(OrderPaidIntegrationEvent @event) => Task.CompletedTask;
+}}
+"""
+
+
+def test_events_redeclared_per_service_link_by_short_type_name(tmp_path: Path) -> None:
+ ordering = _repo(
+ tmp_path,
+ "ordering",
+ {"Events/OrderPaid.cs": _event("Ordering.Events"), "Handlers/PaidHandler.cs": _PUBLISHER},
+ )
+ catalog = _repo(
+ tmp_path,
+ "catalog",
+ {
+ "Events/OrderPaid.cs": _event("Catalog.IntegrationEvents"),
+ "Extensions.cs": _SUBSCRIBER,
+ "Handlers/OrderPaidHandler.cs": _HANDLER.format(ns="Catalog"),
+ },
+ )
+ # Only a handler class subscribes here: the bus wires it by assembly scan.
+ webhooks = _repo(
+ tmp_path,
+ "webhooks",
+ {
+ "OrderPaid.cs": _event("Webhooks.Events"),
+ "OrderPaidHandler.cs": _HANDLER.format(ns="Webhooks"),
+ },
+ )
+ assert _rows(ordering) == {("provider", _PAID, "Handlers/PaidHandler.cs", 7)}
+ # The registration is the subscription; the handler class adds no second row.
+ assert _rows(catalog) == {("consumer", _PAID, "Extensions.cs", 8)}
+ assert _rows(webhooks) == {("consumer", _PAID, "OrderPaidHandler.cs", 3)}
+ links = {
+ (link.provider_repo, link.consumer_repo, link.contract_id)
+ for link in match_contracts(ordering + catalog + webhooks)
+ }
+ assert links == {("ordering", "catalog", _PAID), ("ordering", "webhooks", _PAID)}
+
+
+def test_publish_origin_says_how_the_event_reached_the_call(tmp_path: Path) -> None:
+ rows = _repo(
+ tmp_path,
+ "svc",
+ {
+ "Events.cs": _event("Svc", "AInteg") + _event("Svc.B", "BInteg"),
+ "Pub.cs": (
+ "class P {\n"
+ " async Task Run(IEventBus bus) {\n"
+ " await bus.PublishAsync(new AInteg(1));\n"
+ " var b = new BInteg(2);\n"
+ " await bus.PublishAsync(b);\n"
+ " }\n}\n"
+ ),
+ },
+ )
+ origins = {c.contract_id: c.origin for c in rows}
+ assert origins == {
+ "topic::ainteg": ContractOrigin.CLIENT_CALL,
+ "topic::binteg": ContractOrigin.DATAFLOW,
+ }
+
+
+def test_an_outbox_method_taking_the_base_type_is_a_publish_call(tmp_path: Path) -> None:
+ rows = _repo(
+ tmp_path,
+ "ordering",
+ {
+ "Events.cs": _event("Ordering"),
+ "IOutbox.cs": "public interface IOutbox\n{\n Task AddAndSaveEventAsync(IntegrationEvent evt);\n}\n",
+ # A ternary and an if/else both assign the variable that reaches the call.
+ "Handler.cs": (
+ "class H {\n async Task Run(bool ok) {\n"
+ " IntegrationEvent e;\n"
+ " if (ok) { e = new OrderPaidIntegrationEvent(1); }\n"
+ " else { e = new OrderPaidIntegrationEvent(2); }\n"
+ " await _outbox.AddAndSaveEventAsync(e);\n }\n}\n"
+ ),
+ },
+ )
+ assert _rows(rows) == {("provider", _PAID, "Handler.cs", 4)}
+
+
+def test_a_construction_that_reaches_no_publish_call_is_not_a_publisher(tmp_path: Path) -> None:
+ rows = _repo(
+ tmp_path,
+ "svc",
+ {
+ "Events.cs": _event("Svc"),
+ "Mapper.cs": (
+ "class M {\n object Map(int id) {\n"
+ " var e = new OrderPaidIntegrationEvent(id);\n"
+ " _log.Write(e);\n return e;\n }\n}\n"
+ ),
+ },
+ )
+ assert rows == []
+
+
+def test_a_type_not_derived_from_the_event_base_is_not_published(tmp_path: Path) -> None:
+ rows = _repo(
+ tmp_path,
+ "svc",
+ {
+ "Msg.cs": "namespace Svc;\npublic record OrderSubmitted(int Id);\n",
+ "Pub.cs": "class P {\n Task Run() => _bus.Publish(new OrderSubmitted(1));\n}\n",
+ },
+ )
+ assert rows == []
+
+
+def test_an_event_derived_through_another_event_type_is_read(tmp_path: Path) -> None:
+ rows = _repo(
+ tmp_path,
+ "svc",
+ {
+ "Base.cs": _event("Svc", "OrderEventBase"),
+ "Paid.cs": _event("Svc", base="OrderEventBase"),
+ "Pub.cs": "class P {\n Task Run() => _bus.PublishAsync(new OrderPaidIntegrationEvent(1));\n}\n",
+ },
+ )
+ assert _rows(rows) == {("provider", _PAID, "Pub.cs", 2)}
+
+
+def test_the_event_bus_library_itself_yields_nothing(tmp_path: Path) -> None:
+ # The generic registration and handler interface name type parameters, not events.
+ rows = _repo(
+ tmp_path,
+ "eventbus",
+ {
+ "IIntegrationEventHandler.cs": (
+ "public interface IIntegrationEventHandler<in TIntegrationEvent> : IIntegrationEventHandler\n"
+ " where TIntegrationEvent : IntegrationEvent\n{\n"
+ " Task Handle(TIntegrationEvent @event);\n}\n"
+ ),
+ "EventBusBuilderExtensions.cs": (
+ "public static class EventBusBuilderExtensions\n{\n"
+ " public static IEventBusBuilder AddSubscription<T, TH>(this IEventBusBuilder b)\n"
+ " where T : IntegrationEvent\n"
+ " where TH : class, IIntegrationEventHandler<T>\n"
+ " {\n return b;\n }\n}\n"
+ ),
+ "IEventBus.cs": "public interface IEventBus\n{\n Task PublishAsync(IntegrationEvent @event);\n}\n",
+ "IntegrationEvent.cs": "public record IntegrationEvent\n{\n public Guid Id { get; set; }\n}\n",
+ },
+ )
+ assert rows == []
+
+
+def test_a_subscription_to_a_type_the_repo_declares_as_no_event_is_refused(tmp_path: Path) -> None:
+ rows = _repo(
+ tmp_path,
+ "svc",
+ {
+ "Paid.cs": "namespace Svc;\npublic class OrderPaidIntegrationEvent { }\n",
+ "Extensions.cs": _SUBSCRIBER,
+ },
+ )
+ assert rows == []
+
+
+def test_a_subscription_to_a_type_declared_in_a_shared_contract_repo_is_read(tmp_path: Path) -> None:
+ rows = _repo(tmp_path, "svc", {"Extensions.cs": _SUBSCRIBER})
+ assert _rows(rows) == {("consumer", _PAID, "Extensions.cs", 8)}
+
+
+def test_subscribe_needs_an_event_the_repo_declares(tmp_path: Path) -> None:
+ startup = (
+ "class Startup {\n void Configure() {\n"
+ " eventBus.Subscribe<OrderPaidIntegrationEvent, IIntegrationEventHandler<OrderPaidIntegrationEvent>>();\n"
+ " observable.Subscribe<Tick, TickObserver>();\n }\n}\n"
+ )
+ rows = _repo(tmp_path, "svc", {"Events.cs": _event("Svc"), "Startup.cs": startup})
+ assert _rows(rows) == {("consumer", _PAID, "Startup.cs", 3)}
+
+
+def test_a_commented_out_subscription_is_not_read(tmp_path: Path) -> None:
+ rows = _repo(
+ tmp_path,
+ "svc",
+ {"Extensions.cs": _SUBSCRIBER.replace(" .AddSubscription", " // .AddSubscription")},
+ )
+ assert rows == []
+
+
+def test_a_same_named_variable_in_another_method_is_another_value(tmp_path: Path) -> None:
+ rows = _repo(
+ tmp_path,
+ "svc",
+ {
+ "Events.cs": _event("Svc"),
+ "Svc.cs": (
+ "class S {\n"
+ " void Build(int id) {\n var e = new OrderPaidIntegrationEvent(id);\n Log(e);\n }\n"
+ " Task Send(IntegrationEvent other) {\n var e = other;\n return bus.PublishAsync(e);\n }\n}\n"
+ ),
+ },
+ )
+ assert rows == []
+
+
+def test_only_a_method_named_for_publishing_is_a_publish_call(tmp_path: Path) -> None:
+ rows = _repo(
+ tmp_path,
+ "svc",
+ {
+ "Events.cs": _event("Svc"),
+ "Audit.cs": (
+ "class A {\n void Log(IntegrationEvent e) { }\n"
+ " void Check(object x) { if (x is IntegrationEvent e) { } }\n}\n"
+ ),
+ "Svc.cs": (
+ "class S {\n void Run(int id) {\n"
+ " var e = new OrderPaidIntegrationEvent(id);\n _audit.Log(e);\n"
+ " if (new OrderPaidIntegrationEvent(2) != null) { }\n }\n}\n"
+ ),
+ },
+ )
+ assert rows == []
+
+
+def test_a_file_publishing_only_through_an_outbox_method_is_read(tmp_path: Path) -> None:
+ # The handler names neither the event base nor `Publish`: the outbox method is its only tie.
+ rows = _repo(
+ tmp_path,
+ "ordering",
+ {
+ "Events.cs": _event("Ordering", "OrderPaid"),
+ "IOutbox.cs": "public interface IOutbox\n{\n Task AddAndSaveEventAsync(IntegrationEvent evt);\n}\n",
+ "Handler.cs": (
+ "class H {\n async Task Run(int id) {\n"
+ " var e = new OrderPaid(id);\n"
+ " await _outbox.AddAndSaveEventAsync(e);\n }\n}\n"
+ ),
+ },
+ )
+ assert _rows(rows) == {("provider", "topic::orderpaid", "Handler.cs", 3)}
+
+
+def test_the_event_variable_may_follow_several_arguments(tmp_path: Path) -> None:
+ rows = _repo(
+ tmp_path,
+ "svc",
+ {
+ "Events.cs": _event("Svc"),
+ "Pub.cs": (
+ "class P {\n async Task Run(int id) {\n"
+ " var e = new OrderPaidIntegrationEvent(id);\n"
+ ' await bus.PublishAsync(tenantId, "x", e);\n }\n}\n'
+ ),
+ },
+ )
+ assert _rows(rows) == {("provider", _PAID, "Pub.cs", 3)}