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): MassTransit message contracts for C# and VB.NET (#3070)
Madalin Novac35feebd18443
diff --git a/docs/scale/WORKSPACES.md b/docs/scale/WORKSPACES.mdindex 2a9518fbe..da03b15a4 100644--- a/docs/scale/WORKSPACES.md+++ b/docs/scale/WORKSPACES.md@@ -156,7 +156,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`, 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), plus RabbitMQ queue bindings (`bindQueue`, `queue_bind`) |+| 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`) || 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.@@ -187,6 +187,10 @@ contracts:detect_socket: truedetect_topics: truedetect_data: true+ # Directory-name regex (full match, ignoring case) marking a .NET project whose+ # types are MassTransit messages. The default is shown; widen it to match your+ # own project naming, e.g. '(?:.+\.)?contracts?' to accept singular names too.+ contract_project_pattern: '(?:.+\.)?contracts'# Map a consumer base token or absolute host to the repo it targets, so a# call whose base is unresolved at parse time links as an exact match.service_bases:@@ -206,6 +210,23 @@ Calls to a literalthird-party host (Stripe, Formspree, ...) that is not a workspace service areexcluded from matching and reported under the `external_host` diagnostics reason.+**MassTransit.** A message is routed by its .NET type, so its contract id is+`topic::<namespace>:<type>` (lowercased), not a string. A type counts as a message+only when it is declared at the top level of a non-generic type in a project under a+directory matching `contracts.contract_project_pattern` (configurable; the default+matches `Contracts` and `<Prefix>.Contracts`), in any repo of the workspace. A+`Send` or `Publish` argument that is not one of those types never produces a+contract, which keeps non-bus `Send` calls out unless they pass an indexed message+type. Producers are `Publish`, `Send`, `SchedulePublish`, `ScheduleSend`,+`ScheduleRecurringSend` (generic and argument forms), `Respond`, `IRequestClient<T>`+and saga `Init<T>`, plus extension methods that wrap them; receivers declared as+`IMediator`, `ISender` or `IPublisher` are skipped. Consumers are `IConsumer<T>`+(including `Fault<T>`), closed open-generic consumers and registration helpers, and+saga events. A name that matches two messages is skipped, not guessed, and a bare+name is matched by its short name only when the repo declares no other type with+that name. Adding or removing a message type, or changing the pattern, re-extracts+every repo.+### Package Dependency ScanningReads package manifests (`package.json`, `composer.json`, `pyproject.toml`,diff --git a/packages/core/src/repowise/core/workspace/config.py b/packages/core/src/repowise/core/workspace/config.pyindex 20332ea4e..4437f7df2 100644--- a/packages/core/src/repowise/core/workspace/config.py+++ b/packages/core/src/repowise/core/workspace/config.py@@ -8,6 +8,7 @@ from __future__ import annotationsimport loggingimport os+import refrom dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Any@@ -28,6 +29,8 @@ WORKSPACE_CONFIG_FILENAME = ".repowise-workspace.yaml"WORKSPACE_CEILING_ENV_VAR = "REPOWISE_WORKSPACE_CEILING"WORKSPACE_DATA_DIR = ".repowise-workspace"CURRENT_VERSION = 1+# A ``Contracts`` directory name, with or without a dotted prefix (``Sample.Contracts``).+DEFAULT_CONTRACT_PROJECT_PATTERN = r"(?:.+\.)?contracts"# ---------------------------------------------------------------------------@@ -105,6 +108,18 @@ class ManualContractLink:)+def _valid_pattern(value: Any) -> str:+ """*value* as a contract project pattern, or the default when it is not a regex."""+ if value is None:+ return DEFAULT_CONTRACT_PROJECT_PATTERN+ try:+ re.compile(str(value))+ except re.error:+ _log.warning("Invalid contracts.contract_project_pattern %r; using the default", value)+ return DEFAULT_CONTRACT_PROJECT_PATTERN+ return str(value)++@dataclassclass ContractConfig:"""Configuration for contract detection (Phase 4)."""@@ -125,6 +140,9 @@ class ContractConfig:# Extra glob patterns (added to the built-in test/spec defaults) whose files# are skipped during contract extraction.exclude_globs: list[str] = field(default_factory=list)+ # A directory name matching this regex (in full, ignoring case) marks a .NET+ # project whose types are MassTransit message contracts.+ contract_project_pattern: str = DEFAULT_CONTRACT_PROJECT_PATTERNdef to_dict(self) -> dict[str, Any]:d: dict[str, Any] = {@@ -141,6 +159,8 @@ class ContractConfig:d["service_bases"] = dict(self.service_bases)if self.exclude_globs:d["exclude_globs"] = list(self.exclude_globs)+ if self.contract_project_pattern != DEFAULT_CONTRACT_PROJECT_PATTERN:+ d["contract_project_pattern"] = self.contract_project_patternreturn d@classmethod@@ -156,6 +176,7 @@ class ContractConfig:manual_links=manual,service_bases={str(k): str(v) for k, v in data.get("service_bases", {}).items()},exclude_globs=[str(g) for g in data.get("exclude_globs", [])],+ contract_project_pattern=_valid_pattern(data.get("contract_project_pattern")),)diff --git a/packages/core/src/repowise/core/workspace/contracts.py b/packages/core/src/repowise/core/workspace/contracts.pyindex 1a0d0862a..2d5b64b27 100644--- a/packages/core/src/repowise/core/workspace/contracts.py+++ b/packages/core/src/repowise/core/workspace/contracts.py@@ -62,7 +62,8 @@ CONTRACTS_FILENAME = "contracts.json"# base, and Prisma, TypeORM, Sequelize, Drizzle and Knex tables.# Version 13 adds Angular HttpClient calls, with bases folded from environment# files and class fields.-CONTRACTS_VERSION = 13+# Version 14 adds MassTransit message-type topic contracts (C# and VB.NET).+CONTRACTS_VERSION = 14#: ``meta["kind"]`` of a topic contract: the destination a broker call names.#: A queue is read by one consumer group; a topic, subject or channel fans@@ -548,15 +549,18 @@ async def run_contract_extraction(DataExtractor,GrpcExtractor,HttpExtractor,+ MassTransitExtractor,OpenApiExtractor,SocketExtractor,TopicExtractor,assign_service,+ build_message_type_index,detect_service_boundaries,merge_openapi_providers,)from .extractors.base import iter_source_files, make_exclude_predicatefrom .extractors.from_index import EXTRACTION_LAYER_KEY, LAYER_REGEX+ from .extractors.masstransit import MessageTypeIndexfrom .matching import annotate_consumer_targets, match_contractscontract_config = ws_config.contracts@@ -583,6 +587,16 @@ async def run_contract_extraction(else CodeSurface())+ # A MassTransit consumer resolves its message type against every repo's+ # contract projects, so the type index is workspace-wide too.+ message_types = (+ await asyncio.to_thread(+ build_message_type_index, repo_paths, exclude, contract_config.contract_project_pattern+ )+ if contract_config.detect_topics+ else MessageTypeIndex()+ )+# Which repos can be carried forward, and which must be re-extracted.# Probing a repo's state costs a `git rev-parse` and a dirty check; the# alternative is trusting changed_repos, which is exactly the trust a stale@@ -599,10 +613,13 @@ async def run_contract_extraction(# and its HEAD is unchanged, so nothing else here would notice.# The published-package set joins it because a code consumer depends on# *another* repo's manifests: adding the repo that publishes what this one- # imports moves no HEAD here, so nothing else would notice.+ # imports moves no HEAD here, so nothing else would notice. The message-type+ # set joins it for the same reason: a new contract type in one repo changes+ # which calls in an unchanged repo resolve.config_fp = hashlib.sha256(json.dumps(- [contract_config.to_dict(), sorted(code_surface.members)], sort_keys=True+ [contract_config.to_dict(), sorted(code_surface.members), sorted(message_types.fqns)],+ sort_keys=True,).encode()).hexdigest()[:16]@@ -671,6 +688,7 @@ async def run_contract_extraction(extractors.append(SocketExtractor())if contract_config.detect_topics:extractors.append(TopicExtractor())+ extractors.append(MassTransitExtractor(contract_config.contract_project_pattern))if contract_config.detect_data:extractors.append(DataExtractor())code_rows = code_surface.for_repo(alias)@@ -708,6 +726,8 @@ async def run_contract_extraction(kwargs = {"repo_index": repo_index, "stats": stats}elif isinstance(extractor, OpenApiExtractor):kwargs = {"stats": stats}+ elif isinstance(extractor, MassTransitExtractor):+ kwargs = {"message_types": message_types, "stats": stats}else:kwargs = {}found = await asyncio.to_thread(diff --git a/packages/core/src/repowise/core/workspace/extractors/__init__.py b/packages/core/src/repowise/core/workspace/extractors/__init__.pyindex 8fe913ebd..0c09da3cc 100644--- a/packages/core/src/repowise/core/workspace/extractors/__init__.py+++ b/packages/core/src/repowise/core/workspace/extractors/__init__.py@@ -1,11 +1,12 @@"""Contract extractors: HTTP routes, gRPC services, sockets, message topics,-database tables, service boundaries."""+MassTransit message types, database tables, service boundaries."""from __future__ import annotationsfrom .data import DataExtractor, normalize_table_namefrom .grpc import GrpcExtractorfrom .http import HttpExtractor, normalize_http_path+from .masstransit import MassTransitExtractor, build_message_type_indexfrom .openapi import OpenApiExtractor, merge_openapi_providersfrom .service_boundary import (ServiceBoundary,@@ -19,11 +20,13 @@ __all__ = ["DataExtractor","GrpcExtractor","HttpExtractor",+ "MassTransitExtractor","OpenApiExtractor","ServiceBoundary","SocketExtractor","TopicExtractor","assign_service",+ "build_message_type_index","detect_service_boundaries","merge_openapi_providers","normalize_http_path",diff --git a/packages/core/src/repowise/core/workspace/extractors/langs.py b/packages/core/src/repowise/core/workspace/extractors/langs.pyindex 78cb94aa1..95482b132 100644--- a/packages/core/src/repowise/core/workspace/extractors/langs.py+++ b/packages/core/src/repowise/core/workspace/extractors/langs.py@@ -19,6 +19,7 @@ RUBY = _REGISTRY.extensions_for(["ruby"])PHP = _REGISTRY.extensions_for(["php"])GO = _REGISTRY.extensions_for(["go"])CSHARP = _REGISTRY.extensions_for(["csharp"])+VBNET = _REGISTRY.extensions_for(["vbnet"])RUST = _REGISTRY.extensions_for(["rust"])PROTO = _REGISTRY.extensions_for(["proto"])diff --git a/packages/core/src/repowise/core/workspace/extractors/masstransit.py b/packages/core/src/repowise/core/workspace/extractors/masstransit.pynew file mode 100644index 000000000..67a0c06ea--- /dev/null+++ b/packages/core/src/repowise/core/workspace/extractors/masstransit.py@@ -0,0 +1,1209 @@+"""MassTransit message contracts for C# and VB.NET.++A MassTransit message is routed by its .NET type, so the contract id is the+message type's ``namespace:name`` (MassTransit's default entity name), not a+string topic. A type is only a message when it is declared in a contract+project (``contracts.contract_project_pattern``): that index is the gate that+keeps ``.Send(x)`` on a socket or a mail client out of the results.+"""++from __future__ import annotations++import re+from dataclasses import dataclass, field+from pathlib import Path+from typing import TYPE_CHECKING++from repowise.core.fs_walk import iter_glob+from repowise.core.ingestion.resolvers.dotnet.msbuild import (+ find_csproj_files,+ path_has_dotnet_scan_skip_dir,+)+from repowise.core.ingestion.resolvers.dotnet.namespace_map import (+ declared_namespaces,+ scan_type_declarations,+)++from ..config import DEFAULT_CONTRACT_PROJECT_PATTERN+from .base import line_at, select_files+from .langs import CSHARP, VBNET++if TYPE_CHECKING:+ from collections.abc import Callable, Iterator, Mapping, Sequence++ from repowise.core.workspace.contracts import Contract++ from .base import SourceFile++_TEST_DIR_RE = re.compile(+ r"^.+\.(?:tests?|unittests?|integrationtests?|specs?|testing|testhelpers?)$", re.IGNORECASE+)++_TIER_DECLARED = 0.8+_TIER_UNIQUE_NAME = 0.6+_TIER_DATAFLOW = 0.7+++# ---------------------------------------------------------------------------+# Message type index+# ---------------------------------------------------------------------------+++@dataclass+class MessageTypeIndex:+ """Every top-level type declared in a contract project, workspace-wide."""++ fqns: set[str] = field(default_factory=set)+ by_short: dict[str, set[str]] = field(default_factory=dict)++ def add(self, fqn: str) -> None:+ self.fqns.add(fqn)+ self.by_short.setdefault(fqn.rsplit(".", 1)[-1], set()).add(fqn)+++def _in_test_project(rel_path: str) -> bool:+ return any(_TEST_DIR_RE.match(part) for part in rel_path.split("/")[:-1])+++def build_message_type_index(+ repo_paths: Mapping[str, Path],+ exclude: Callable[[str], bool] | None = None,+ contract_project_pattern: str = DEFAULT_CONTRACT_PROJECT_PATTERN,+) -> MessageTypeIndex:+ """Collect the declared types of every contract project in *repo_paths*.++ A project is a contract project when one directory name on its path matches+ *contract_project_pattern* in full, ignoring case.+ """+ index = MessageTypeIndex()+ dir_re = re.compile(contract_project_pattern, re.IGNORECASE)+ for repo in repo_paths.values():+ seen: set[Path] = set()+ for csproj in find_csproj_files(repo):+ try:+ rel_dir = csproj.parent.relative_to(repo).parts+ except ValueError:+ continue+ if not any(dir_re.fullmatch(part) for part in rel_dir):+ continue+ for cs in iter_glob(csproj.parent, "*.cs"):+ if cs in seen or path_has_dotnet_scan_skip_dir(cs, repo):+ continue+ seen.add(cs)+ rel = cs.relative_to(repo).as_posix()+ if _in_test_project(rel) or (exclude is not None and exclude(rel)):+ continue+ try:+ text = cs.read_bytes().decode("utf-8-sig", errors="replace")+ except OSError:+ continue+ for decl in scan_type_declarations(text):+ if decl.namespace and decl.qualified == decl.name and not decl.arity:+ index.add(decl.fqn)+ return index+++# ---------------------------------------------------------------------------+# Comment masking+# ---------------------------------------------------------------------------++_CS_TOKEN = re.compile(+ r"//[^\n]*|/\*.*?\*/"+ r'|\$?@\$?"(?:[^"]|"")*"|\$?"(?:\\.|[^"\\\n])*"'+ r"|\x27(?:\\.[^\x27\n]*?|[^\\\x27\n])\x27",+ re.DOTALL,+)+_VB_TOKEN = re.compile(+ r'"(?:[^"\n]|"")*"|\x27[^\n]*|^[ \t]*REM\b[^\n]*',+ re.IGNORECASE | re.MULTILINE,+)+_NOT_NEWLINE = re.compile(r"[^\n]")+++def _mask_non_code(text: str, vb: bool) -> str:+ """Blank out comments and string literals, keeping every offset and newline."""+ return (_VB_TOKEN if vb else _CS_TOKEN).sub(lambda m: _NOT_NEWLINE.sub(" ", m.group()), text)+++# ---------------------------------------------------------------------------+# Per-file context and name resolution+# ---------------------------------------------------------------------------++_CS_USING = re.compile(r"^[ \t]*(?:global\s+)?using\s+(?:(\w+)\s*=\s*)?([\w.]+)\s*;", re.MULTILINE)+_VB_IMPORTS = re.compile(+ r"^[ \t]*Imports\s+(?:(\w+)\s*=\s*)?([\w.]+)", re.IGNORECASE | re.MULTILINE+)+_VB_NAMESPACE = re.compile(r"^[ \t]*Namespace\s+([\w.]+)", re.IGNORECASE | re.MULTILINE)+_GLOBAL_PREFIX = re.compile(r"^global(?:::|\.)", re.IGNORECASE)+_DOTTED = re.compile(r"[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*")+++@dataclass+class _FileContext:+ namespaces: list[str]+ usings: list[str]+ aliases: dict[str, str]+++def _file_context(masked: str, vb: bool) -> _FileContext:+ usings: list[str] = []+ aliases: dict[str, str] = {}+ for m in (_VB_IMPORTS if vb else _CS_USING).finditer(masked):+ alias, target = m.groups()+ if alias is None:+ usings.append(target)+ elif not vb:+ aliases[alias] = target+ if vb:+ namespaces = [m.group(1) for m in _VB_NAMESPACE.finditer(masked)]+ else:+ namespaces = declared_namespaces(masked)+ return _FileContext(namespaces, usings, aliases)+++@dataclass(frozen=True)+class _Resolved:+ fqn: str+ confidence: float+ resolution: str+++class _Resolver:+ def __init__(self, index: MessageTypeIndex) -> None:+ self._fqns = {f.lower(): f for f in index.fqns}+ self._by_short = {+ short.lower(): {f.lower() for f in fqns} for short, fqns in index.by_short.items()+ }++ def resolve(+ self, written: str, ctx: _FileContext, local_names: Callable[[], set[str]]+ ) -> _Resolved | str:+ """A resolved type, or ``"ambiguous"`` / ``"unresolved"``.++ A bare name that no using reaches resolves by its short name only when+ the repo declares no type of that name outside the contract projects.+ """+ name = _GLOBAL_PREFIX.sub("", written)+ candidates = [name]+ for ns in ctx.namespaces:+ parts = ns.split(".")+ candidates += [".".join(parts[:i]) + "." + name for i in range(len(parts), 0, -1)]+ candidates += [f"{u}.{name}" for u in ctx.usings]+ head, _, rest = name.partition(".")+ if head in ctx.aliases:+ candidates.append(ctx.aliases[head] + (f".{rest}" if rest else ""))++ hits = {c.lower() for c in candidates} & self._fqns.keys()+ if len(hits) == 1:+ label = "qualified" if "." in name else "using"+ return _Resolved(self._fqns[next(iter(hits))], _TIER_DECLARED, label)+ if len(hits) > 1:+ return "ambiguous"+ if "." in name:+ return "unresolved"+ short = name.rsplit(".", 1)[-1].lower()+ shorts = self._by_short.get(short, set())+ if shorts and short in local_names():+ return "unresolved"+ if len(shorts) == 1:+ return _Resolved(self._fqns[next(iter(shorts))], _TIER_UNIQUE_NAME, "unique_name")+ return "ambiguous" if shorts else "unresolved"+++# ---------------------------------------------------------------------------+# Consumers+# ---------------------------------------------------------------------------++_CS_CONSUMER = re.compile(+ r"\bIConsumer\s*<\s*((?:global::)?[\w.]+(?:\s*<\s*(?:global::)?[\w.]+\s*>)?)\s*>"+)+_VB_CONSUMER = re.compile(+ r"\bIConsumer\s*\(\s*Of\s+((?:Global\.)?[\w.]+(?:\s*\(\s*Of\s+(?:Global\.)?[\w.]+\s*\))?)\s*\)",+ re.IGNORECASE,+)+_CS_CONSUME_METHOD = re.compile(r"\bConsume\s*\(\s*ConsumeContext\s*<\s*(.+?)\s*>\s+\w+")+_VB_CONSUME_METHOD = re.compile(+ r"\bConsume\s*\(\s*(?:ByVal\s+)?\w+\s+As\s+ConsumeContext\s*\(\s*Of\s+(.+?)\s*\)\s*\)",+ re.IGNORECASE,+)+_CS_STATE_MACHINE = re.compile(r"\bMassTransitStateMachine\s*<")+_VB_STATE_MACHINE = re.compile(r"\bMassTransitStateMachine\s*\(\s*Of\b", re.IGNORECASE)+_CS_SAGA_EVENT = re.compile(r"\bEvent\s*<\s*((?:global::)?[\w.]+)\s*>\s+\w+")+_VB_SAGA_EVENT = re.compile(+ r"\bAs\s+\[?Event\]?\s*\(\s*Of\s+((?:Global\.)?[\w.]+)\s*\)", re.IGNORECASE+)+_FAULT = re.compile(r"Fault\s*(?:<|\(\s*Of\s+)\s*(.+?)\s*[>)]$", re.IGNORECASE)+++def _norm_generic(text: str) -> str:+ text = re.sub(r"\(\s*Of\s+", "<", text, flags=re.IGNORECASE)+ text = text.replace(")", ">")+ return re.sub(r"\s+|global(?:::|\.)", "", text, flags=re.IGNORECASE).lower()+++# ---------------------------------------------------------------------------+# Producers+# ---------------------------------------------------------------------------++_BASE_CALLS = (+ "Publish",+ "Send",+ "SchedulePublish",+ "ScheduleSend",+ "ScheduleRecurringSend",+ "Respond",+ "RespondAsync",+ "CreateRequestClient",+)+_ARG_CALLS = frozenset(+ {"Publish", "Send", "SchedulePublish", "ScheduleSend", "ScheduleRecurringSend"}+ | {"Respond", "RespondAsync"}+)+# Arguments before the message in the non-generic form: (when), (uri, when), (uri, schedule).+_LEADING_ARGS = {"SchedulePublish": 1, "ScheduleSend": 2, "ScheduleRecurringSend": 2}+_CALL_KIND = {+ "Publish": "publish",+ "Send": "send",+ "Respond": "respond",+ "RespondAsync": "respond",+ "CreateRequestClient": "request",+}+_RECEIVER = re.compile(+ r"(?<![\w.])((?:[A-Za-z_]\w*(?:\([^()]*\))?\s*\??\.\s*)*[A-Za-z_]\w*(?:\([^()]*\))?)\s*$"+)+_NOT_AN_ARG = frozenset(+ {"new", "nothing", "null", "me", "this", "default", "typeof", "function", "sub"}+)+_NOT_A_TYPE = frozenset(+ {"return", "await", "new", "throw", "else", "in", "is", "as", "using", "case", "yield", "ref"}+)+_VB_GENERIC_OPEN = re.compile(r"\(\s*Of\s+", re.IGNORECASE)+_VB_SCOPE_END = re.compile(r"^[ \t]*End\s+(?:Sub|Function|Property|Operator)\b", re.I | re.M)+++def _call_pattern(wrappers: Mapping[str, list[_Wrapper]]) -> re.Pattern[str]:+ names = _BASE_CALLS + tuple(sorted(wrappers))+ return re.compile(r"\.\s*(" + "|".join(map(re.escape, names)) + r")\b")+++def _skip_ws(text: str, i: int, vb: bool) -> int:+ while i < len(text):+ continuation = vb and text[i] == "_" and text[i + 1 : i + 2].isspace()+ if not (text[i].isspace() or continuation):+ break+ i += 1+ return i+++def _balanced(text: str, i: int, open_ch: str, close_ch: str) -> int:+ """Index just past the bracket closing the one at *i*, or -1."""+ depth = 0+ for j in range(i, min(len(text), i + 300)):+ ch = text[j]+ if ch == open_ch:+ depth += 1+ elif ch == close_ch:+ depth -= 1+ if depth == 0:+ return j + 1+ elif ch in ";{}":+ return -1+ return -1+++def _split_args(args: str) -> list[str]:+ """Split a generic or parameter list at its top-level commas."""+ depth = 0+ start = 0+ parts: list[str] = []+ for j, ch in enumerate(args):+ if ch in "<(":+ depth += 1+ elif ch in ">)":+ depth -= 1+ elif ch == "," and depth == 0:+ parts.append(args[start:j].strip())+ start = j + 1+ parts.append(args[start:].strip())+ return parts+++def _last_type_arg(args: str) -> str | None:+ last = _split_args(args)[-1]+ return last if _DOTTED.fullmatch(_GLOBAL_PREFIX.sub("", last)) else None+++def _generic_at(text: str, i: int, vb: bool) -> tuple[list[str], int] | None:+ """Type arguments of the generic list opening at *i*, and the index past it."""+ if vb:+ g = _VB_GENERIC_OPEN.match(text, i)+ end = _balanced(text, i, "(", ")") if g else -1+ return (_split_args(text[g.end() : end - 1]), end) if g and end >= 0 else None+ if text[i : i + 1] != "<":+ return None+ end = _balanced(text, i, "<", ">")+ return (_split_args(text[i + 1 : end - 1]), end) if end >= 0 else None+++def _declared_type(masked: str, call_start: int, ident: str, vb: bool) -> str | None:+ """Type of *ident* from its nearest declaration above *call_start*."""+ name = re.escape(ident)+ if vb:+ scope_end = 0+ for m in _VB_SCOPE_END.finditer(masked, 0, call_start):+ scope_end = m.end()+ window_start = scope_end+ patterns = (+ rf"(?<![\w.]){name}\s+As\s+(?:New\s+)?([A-Za-z_][\w.]*)",+ rf"\bDim\s+{name}\s*=\s*New\s+([A-Za-z_][\w.]*)",+ )+ flags = re.IGNORECASE+ else:+ window_start = 0+ patterns = (rf"(?<![\w.])(var|[A-Za-z_][\w.]*)\??\s+{name}\s*(?=[=;,)])",)+ flags = 0+ best: tuple[int, str | None] = (-1, None)+ for pat in patterns:+ for m in re.finditer(pat, masked[window_start:call_start], flags):+ typ = m.group(1)+ if typ.lower() in _NOT_A_TYPE:+ continue+ if typ == "var":+ init = re.match(r"\s*=\s*new\s+([A-Za-z_][\w.]*)", masked[window_start + m.end() :])+ typ = init.group(1) if init else None+ if typ is not None and m.start() >= best[0]:+ best = (m.start(), typ)+ return best[1]+++@dataclass(frozen=True)+class _ProducerCall:+ start: int+ method: str+ receiver: str+ written: str+ dataflow: bool+ base: str+++def _after_first_arg(text: str, i: int) -> int:+ """Index just past the first top-level argument starting at *i*, or -1."""+ depth = 0+ for j in range(i, min(len(text), i + 200)):+ ch = text[j]+ if ch in "([<":+ depth += 1+ elif ch in ")]>":+ depth -= 1+ if depth < 0:+ return -1+ elif ch == "," and depth == 0:+ return j + 1+ elif ch in ";{}":+ return -1+ return -1+++def _wrapper_call_ok(masked: str, start: int, vb: bool, w: _Wrapper) -> bool | None:+ """Whether the receiver can be a bus; None for a static-form call, True/False otherwise."""+ r = _RECEIVER.search(masked[max(0, start - 120) : start])+ recv = r.group(1) if r else ""+ if not re.fullmatch(r"[A-Za-z_]\w*", recv):+ return True+ if recv.lower() == w.owner:+ return None+ typ = _declared_type(masked, start, recv, vb)+ # A derived bus type is still named like one; a logger or container is not.+ return typ is None or bool(_BUS_LIKE.search(typ.rsplit(".", 1)[-1]))+++def _find_producers(+ masked: str, vb: bool, call_re: re.Pattern[str], wrappers: Mapping[str, list[_Wrapper]]+) -> list[_ProducerCall]:+ calls: list[_ProducerCall] = []+ new_re = re.compile(r"new\s+([A-Za-z_][\w.]*)", re.IGNORECASE if vb else 0)+ for m in call_re.finditer(masked):+ overloads = wrappers.get(m.group(1), [])+ w = overloads[0] if overloads else None+ base = w.base if w else m.group(1)+ static = False+ if w:+ ok = _wrapper_call_ok(masked, m.start(), vb, w)+ if ok is False:+ continue+ static = ok is None+ i = _skip_ws(masked, m.end(), vb)+ written: str | None = None+ dataflow = False+ if w:+ g = _generic_at(masked, i, vb)+ if g:+ picks = {+ o.tindex for o in overloads if o.arity == len(g[0]) and o.tindex is not None+ }+ if len(picks) != 1:+ continue+ written = _written_type(g[0][picks.pop()])+ i = _skip_ws(masked, g[1], vb)+ elif vb:+ g = _VB_GENERIC_OPEN.match(masked, i)+ if g:+ end = _balanced(masked, i, "(", ")")+ if end < 0:+ continue+ written = _last_type_arg(masked[g.end() : end - 1])+ i = _skip_ws(masked, end, vb)+ elif masked[i : i + 1] == "<":+ end = _balanced(masked, i, "<", ">")+ if end < 0:+ continue+ written = _last_type_arg(masked[i + 1 : end - 1])+ i = _skip_ws(masked, end, vb)+ if masked[i : i + 1] != "(":+ continue+ i = _skip_ws(masked, i + 1, vb)+ if static:+ i = _after_first_arg(masked, i)+ if i < 0:+ continue+ i = _skip_ws(masked, i, vb)+ if written is None and base in _ARG_CALLS:+ for _ in range(_LEADING_ARGS.get(base, 0)):+ i = _after_first_arg(masked, i)+ if i < 0:+ break+ i = _skip_ws(masked, i, vb)+ if i < 0:+ continue+ n = new_re.match(masked, i)+ if n and n.group(1).lower() != "with":+ written = n.group(1)+ elif not n:+ a = re.match(r"([A-Za-z_]\w*)\s*(?=[,)])", masked[i : i + 80])+ if a and a.group(1).lower() not in _NOT_AN_ARG:+ written = _declared_type(masked, m.start(), a.group(1), vb)+ dataflow = True+ if not written:+ continue+ window = masked[max(0, m.start() - 120) : m.start()]+ r = _RECEIVER.search(window)+ calls.append(+ _ProducerCall(m.start(), m.group(1), r.group(1) if r else "", written, dataflow, base)+ )+ return calls+++# ---------------------------------------------------------------------------+# Generic consumers, generic registration helpers and bus wrapper methods+# ---------------------------------------------------------------------------++_CS_CLASS_HEAD = re.compile(r"\b(?:class|record)\s+(\w+)")+_VB_CLASS_HEAD = re.compile(+ r"^[ \t]*(?:(?:Public|Private|Friend|Protected|Partial|MustInherit|NotInheritable|Shadows)"+ r"[ \t]+)*Class[ \t]+(\w+)",+ re.IGNORECASE | re.MULTILINE,+)+_CS_BASE_END = re.compile(r"\{|;|\bwhere\s+\w+\s*:")+_VB_BASE_LINE = re.compile(+ r"(?:[ \t]*\r?\n)*[ \t]*(?:Inherits|Implements)[ \t]+([^\n]*)(?:\n|$)", re.IGNORECASE+)+_TYPE_PARAM = re.compile(r"(?:(?:in|out)\s+)?(\w+)", re.IGNORECASE)+_BASE_REF = re.compile(r"(?:global(?:::|\.))?(?:\w+\.)*(\w+)\s*", re.IGNORECASE)+_REGISTER_CS = re.compile(r"\b(?:AddConsumer|Consumer)\s*(?=<)")+_REGISTER_VB = re.compile(r"\b(?:AddConsumer|Consumer)\s*(?=\(\s*Of\b)", re.IGNORECASE)+_CS_GENERIC_METHOD = re.compile(r"\b(\w+)\s*(?=<\s*\w+(?:\s*,\s*\w+)*\s*>\s*\()")+_VB_GENERIC_METHOD = re.compile(r"\b(?:Sub|Function)\s+(\w+)\s*(?=\(\s*Of\b)", re.IGNORECASE)+_CS_WHERE = re.compile(r"\s*\bwhere\s+\w+\s*:[^{=;]*")+_VB_METHOD_END = re.compile(r"^[ \t]*End\s+(?:Sub|Function)\b", re.IGNORECASE | re.MULTILINE)+_CS_EXTENSION = re.compile(r"\b(\w+)\s*(?:<([^<>()]*)>)?\s*\(\s*this\s+")+_VB_EXTENSION = re.compile(+ r"<\s*(?:[\w.]+\.)?Extension\s*(?:\(\s*\))?\s*>\s*(?:_\s*)?"+ r"(?:\w+\s+)*?(?:Sub|Function)\s+(\w+)",+ re.IGNORECASE,+)+_VB_PARAM_NAME = re.compile(r"(?:(?:ByVal|ByRef|Optional|ParamArray)\s+)*(\w+)", re.IGNORECASE)+_CS_PARAM_NAME = re.compile(r"(\w+)\s*(?:=.*)?$", re.DOTALL)+_MAX_BODY = 4000+_BUS_TYPES = frozenset(+ {+ "ibus",+ "ibuscontrol",+ "ipublishendpoint",+ "isendendpoint",+ "isendendpointprovider",+ "consumecontext",+ "sagaconsumecontext",+ "behaviorcontext",+ }+)+_BUS_LIKE = re.compile(r"bus|endpoint|context|outbox", re.IGNORECASE)+_CONFIGURATOR_TYPE = re.compile(r"I\w*(?:Registration|Bus|Endpoint)\w*Configurator", re.IGNORECASE)+_CS_PARAM_TYPE = re.compile(+ r"(?:(?:ref|in|out|params)\s+)?(?:global::)?([\w.]+)\s*(?:<.*>)?\??\s+\w+", re.DOTALL+)+_VB_PARAM_TYPE = re.compile(r"\bAs\s+(?:Global\.)?([\w.]+)", re.IGNORECASE)+_CS_OWNER = re.compile(r"\b(?:class|struct)\s+(\w+)")+_VB_OWNER = re.compile(+ r"^[ \t]*(?:\w+[ \t]+)*?(?:Module|Class)[ \t]+(\w+)", re.IGNORECASE | re.MULTILINE+)+_CS_BUS_CALL = re.compile(+ r"\b(\w+)\s*\.\s*(Publish|Send)\s*(?:<\s*[\w.]+\s*>\s*)?\(\s*(\w+)\s*(?=[,)])"+)+_VB_BUS_CALL = re.compile(+ r"\b(\w+)\s*\.\s*(Publish|Send)\s*(?:\(\s*Of\s+[\w.]+\s*\)\s*)?\(\s*(\w+)\s*(?=[,)])",+ re.IGNORECASE,+)+++@dataclass(frozen=True)+class _Wrapper:+ """An extension method that publishes or sends its message parameter."""++ base: str+ owner: str+ arity: int+ tindex: int | None+++@dataclass(frozen=True)+class _OpenConsumer:+ """Which type parameter of an open-generic class its ``IConsumer`` consumes."""++ param: int+ fault: bool+++@dataclass(frozen=True)+class _ClassDecl:+ name: str+ tparams: tuple[str, ...]+ bases: tuple[tuple[str, tuple[str, ...]], ...]+ offset: int+++@dataclass+class _RepoScan:+ """Per-repo facts that a call site alone cannot show."""++ wrappers: dict[str, list[_Wrapper]] = field(default_factory=dict)+ open_names: set[str] = field(default_factory=set)+ helper_names: set[str] = field(default_factory=set)+ open_consumers: dict[tuple[str, int], _OpenConsumer] = field(default_factory=dict)+ # (name, arity) -> [(type parameter index, fault)] registered by the helper body+ helpers: dict[tuple[str, int], list[tuple[int, bool]]] = field(default_factory=dict)+ helper_spans: dict[str, list[tuple[int, int]]] = field(default_factory=dict)+++def _base_ref(base: str, vb: bool) -> tuple[str, tuple[str, ...]] | None:+ m = _BASE_REF.match(base)+ if not m:+ return None+ g = _generic_at(base, m.end(), vb)+ return m.group(1), tuple(g[0]) if g else ()+++def _tparam_names(args: list[str]) -> tuple[str, ...]:+ return tuple(m.group(1) for a in args if (m := _TYPE_PARAM.match(a)))+++def _vb_bases(masked: str, pos: int) -> list[str]:+ nl = masked.find("\n", pos)+ j = nl + 1 if nl >= 0 else len(masked)+ out: list[str] = []+ while (m := _VB_BASE_LINE.match(masked, j)) and m.end() > j:+ out += _split_args(m.group(1))+ j = m.end()+ return out+++def _class_decls(masked: str, vb: bool, generic_only: bool) -> Iterator[_ClassDecl]:+ for m in (_VB_CLASS_HEAD if vb else _CS_CLASS_HEAD).finditer(masked):+ i = _skip_ws(masked, m.end(), vb)+ g = _generic_at(masked, i, vb)+ tparams = _tparam_names(g[0]) if g else ()+ if generic_only and not tparams:+ continue+ if g:+ i = _skip_ws(masked, g[1], vb)+ if vb:+ raw = _vb_bases(masked, g[1] if g else m.end())+ else:+ if masked[i : i + 1] == "(":+ end = _balanced(masked, i, "(", ")")+ if end < 0:+ continue+ i = _skip_ws(masked, end, vb)+ if masked[i : i + 1] != ":":+ continue+ seg = masked[i + 1 : i + 501]+ stop = _CS_BASE_END.search(seg)+ if not stop:+ continue+ raw = _split_args(seg[: stop.start()])+ bases = tuple(r for b in raw if (r := _base_ref(b, vb)) is not None)+ if bases:+ yield _ClassDecl(m.group(1), tparams, bases, m.start())+++def _consumed_arg(+ name: str, args: tuple[str, ...], known: Mapping[tuple[str, int], _OpenConsumer]+) -> tuple[str, bool] | None:+ """The message type written for a consumer base or interface, and whether it is a fault."""+ if name.lower() == "iconsumer":+ entry = _OpenConsumer(0, False) if len(args) == 1 else None+ else:+ entry = known.get((name.lower(), len(args)))+ if entry is None:+ return None+ arg = args[entry.param]+ fault = _FAULT.match(arg)+ return (fault.group(1), True) if fault else (arg, entry.fault)+++def _open_consumers(decls: list[_ClassDecl]) -> dict[tuple[str, int], _OpenConsumer]:+ """Generic classes that implement ``IConsumer`` of one of their type parameters."""+ known: dict[tuple[str, int], _OpenConsumer | None] = {}+ for _ in range(3):+ changed = False+ usable = {k: v for k, v in known.items() if v is not None}+ for d in decls:+ lowered = [t.lower() for t in d.tparams]+ hit = None+ for name, args in d.bases:+ got = _consumed_arg(name, args, usable)+ if got and got[0].lower() in lowered:+ hit = _OpenConsumer(lowered.index(got[0].lower()), got[1])+ break+ key = (d.name.lower(), len(d.tparams))+ if hit is None or (key in known and known[key] in (hit, None)):+ continue+ # Two classes sharing a name and arity that disagree are not trusted.+ known[key] = None if key in known else hit+ changed = True+ if not changed:+ break+ return {k: v for k, v in known.items() if v is not None}+++def _brace_end(masked: str, i: int) -> int:+ depth = 0+ for j in range(i, min(len(masked), i + _MAX_BODY)):+ if masked[j] == "{":+ depth += 1+ elif masked[j] == "}":+ depth -= 1+ if depth == 0:+ return j + 1+ return -1+++def _param_type(param: str, vb: bool) -> str:+ """Last segment of a parameter's declared type, lower-cased ("" when unknown)."""+ m = _VB_PARAM_TYPE.search(param) if vb else _CS_PARAM_TYPE.match(param.strip())+ return m.group(1).rsplit(".", 1)[-1].lower() if m else ""+++def _is_extension(masked: str, m: re.Match[str], params: list[str], vb: bool) -> bool:+ if vb:+ return "extension" in masked[max(0, m.start() - 80) : m.start()].lower()+ return bool(params) and params[0].startswith("this ")+++def _generic_method_bodies(+ masked: str, vb: bool+) -> Iterator[tuple[str, tuple[str, ...], int, int, list[str]]]:+ """``(name, type parameters, body start, body end, extension parameters)`` per generic method.++ The parameters are empty unless the method is an extension method.+ """+ for m in (_VB_GENERIC_METHOD if vb else _CS_GENERIC_METHOD).finditer(masked):+ if not vb and masked[: m.start()].rstrip().endswith("new"):+ continue+ g = _generic_at(masked, m.end(), vb)+ if not g:+ continue+ p = _skip_ws(masked, g[1], vb)+ end = _balanced(masked, p, "(", ")") if masked[p : p + 1] == "(" else -1+ if end < 0:+ continue+ tparams = _tparam_names(g[0])+ params = _split_args(masked[p + 1 : end - 1])+ if not _is_extension(masked, m, params, vb):+ continue+ if vb:+ stop = _VB_METHOD_END.search(masked, end, end + _MAX_BODY)+ if stop:+ yield m.group(1), tparams, end, stop.start(), params+ continue+ j = end+ while where := _CS_WHERE.match(masked, j):+ j = where.end()+ j = _skip_ws(masked, j, vb)+ if masked[j : j + 1] == "{":+ stop_at = _brace_end(masked, j)+ elif masked[j : j + 2] == "=>":+ semi = masked.find(";", j, j + _MAX_BODY)+ stop_at = semi+ else:+ continue+ if stop_at >= 0:+ yield m.group(1), tparams, j, stop_at, params+++def _registrations(+ masked: str, vb: bool, start: int, end: int, known: Mapping[tuple[str, int], _OpenConsumer]+) -> Iterator[tuple[str, bool]]:+ """``(message type, fault)`` of each ``AddConsumer`` of an open generic in a span."""+ for m in (_REGISTER_VB if vb else _REGISTER_CS).finditer(masked, start, end):+ g = _generic_at(masked, m.end(), vb)+ ref = _base_ref(g[0][0], vb) if g else None+ got = _consumed_arg(*ref, known) if ref and ref[0].lower() != "iconsumer" else None+ if got:+ yield got+++def _generic_helpers(+ masked: str, vb: bool, known: Mapping[tuple[str, int], _OpenConsumer]+) -> Iterator[tuple[str, int, list[tuple[int, bool]], tuple[int, int]]]:+ for name, tparams, start, end, params in _generic_method_bodies(masked, vb):+ first = _param_type(params[0].removeprefix("this "), vb) if params else ""+ if not _CONFIGURATOR_TYPE.fullmatch(first):+ continue+ lowered = [t.lower() for t in tparams]+ regs = [+ (lowered.index(arg.lower()), fault)+ for arg, fault in _registrations(masked, vb, start, end, known)+ if arg.lower() in lowered+ ]+ if regs:+ yield name, len(tparams), regs, (start, end)+++def _param_name(param: str, vb: bool) -> str | None:+ text = param.strip()+ m = _VB_PARAM_NAME.match(text) if vb else _CS_PARAM_NAME.search(text)+ return m.group(1).lower() if m else None+++def _owner_at(masked: str, offset: int, vb: bool) -> str:+ owners = list((_VB_OWNER if vb else _CS_OWNER).finditer(masked, 0, offset))+ return owners[-1].group(1).lower() if owners else ""+++def _extension_wrappers(masked: str, vb: bool) -> Iterator[tuple[str, _Wrapper]]:+ """Extension methods on a bus type that publish or send their message parameter."""+ for m in (_VB_EXTENSION if vb else _CS_EXTENSION).finditer(masked):+ name = m.group(1)+ if name in _BASE_CALLS:+ continue+ if vb:+ g = _generic_at(masked, _skip_ws(masked, m.end(), vb), vb)+ tparams = _tparam_names(g[0]) if g else ()+ p = _skip_ws(masked, g[1] if g else m.end(), vb)+ else:+ tparams = _tparam_names(_split_args(m.group(2))) if m.group(2) else ()+ p = masked.find("(", m.end(1))+ end = _balanced(masked, p, "(", ")") if masked[p : p + 1] == "(" else -1+ params = _split_args(masked[p + 1 : end - 1]) if end >= 0 else []+ if len(params) < 2 or _param_type(params[0].removeprefix("this "), vb) not in _BUS_TYPES:+ continue+ receiver = _param_name(params[0].removeprefix("this "), vb)+ message = _param_name(params[1], vb)+ lowered = [t.lower() for t in tparams]+ mtype = _param_type(params[1], vb)+ if mtype in lowered:+ tindex: int | None = lowered.index(mtype)+ elif mtype == "object":+ tindex = None+ else:+ continue+ if vb:+ stop = _VB_METHOD_END.search(masked, end, end + _MAX_BODY)+ body = masked[end : stop.start()] if stop else ""+ else:+ j = end+ while where := _CS_WHERE.match(masked, j):+ j = where.end()+ j = _skip_ws(masked, j, vb)+ stop_at = _brace_end(masked, j) if masked[j : j + 1] == "{" else masked.find(";", j)+ body = masked[j:stop_at] if stop_at >= 0 else ""+ for call in (_VB_BUS_CALL if vb else _CS_BUS_CALL).finditer(body):+ if call.group(1).lower() == receiver and call.group(3).lower() == message:+ owner = _owner_at(masked, m.start(), vb)+ yield name, _Wrapper(call.group(2).capitalize(), owner, len(tparams), tindex)+ break+++def _prescan(+ sources: Sequence[tuple[str, bool, str]], mask: Callable[[str, bool, str], str]+) -> _RepoScan:+ scan = _RepoScan()+ conflicts: set[str] = set()+ decls: list[_ClassDecl] = []+ scanned: set[str] = set()+ for rel, vb, content in sources:+ if (".Publish" in content or ".Send" in content) and (+ "this " in content or "Extension" in content+ ):+ for name, wrapper in _extension_wrappers(mask(rel, vb, content), vb):+ seen = scan.wrappers.setdefault(name, [wrapper])+ if wrapper not in seen:+ seen.append(wrapper)+ if (seen[0].base, seen[0].owner) != (wrapper.base, wrapper.owner):+ conflicts.add(name)+ for name in conflicts:+ del scan.wrappers[name]+ for _ in range(3):+ for rel, vb, content in sources:+ if rel not in scanned and (+ "Consumer" in content or any(n in content for n in scan.open_names)+ ):+ scanned.add(rel)+ decls += _class_decls(mask(rel, vb, content), vb, generic_only=True)+ scan.open_consumers = _open_consumers(decls)+ names = {d.name for d in decls if (d.name.lower(), len(d.tparams)) in scan.open_consumers}+ if names == scan.open_names:+ break+ scan.open_names = names+ if not scan.open_consumers:+ return scan+ clashes: set[tuple[str, int]] = set()+ for rel, vb, content in sources:+ if "Consumer" not in content:+ continue+ masked = mask(rel, vb, content)+ for name, arity, regs, span in _generic_helpers(masked, vb, scan.open_consumers):+ key = (name.lower(), arity)+ if scan.helpers.setdefault(key, regs) != regs:+ clashes.add(key)+ scan.helper_names.add(name)+ scan.helper_spans.setdefault(rel, []).append(span)+ for key in clashes:+ del scan.helpers[key]+ return scan+++def _written_type(arg: str) -> str | None:+ return arg if _DOTTED.fullmatch(_GLOBAL_PREFIX.sub("", arg)) else None+++def _configurator_receiver(masked: str, start: int, vb: bool) -> bool:+ """Whether the receiver before a helper call can be a registration configurator."""+ r = _RECEIVER.search(masked[max(0, start - 120) : start].rstrip().removesuffix("."))+ recv = r.group(1) if r else ""+ if not masked[:start].rstrip().endswith(".") or not recv:+ return False+ if not re.fullmatch(r"[A-Za-z_]\w*", recv):+ return True+ typ = _declared_type(masked, start, recv, vb)+ return typ is None or bool(_CONFIGURATOR_TYPE.fullmatch(typ.rsplit(".", 1)[-1]))+++def _open_generic_findings(masked: str, vb: bool, rel: str, scan: _RepoScan) -> list[_Finding]:+ """Consumers formed by closing an open-generic consumer class or helper."""+ known = scan.open_consumers+ out: list[_Finding] = []++ def emit(arg: str, fault: bool, offset: int, label: str, optional: bool) -> None:+ written = _written_type(arg)+ if written is None:+ return+ short = written.rsplit(".", 1)[-1]+ symbol = f"{label}<Fault<{short}>>" if fault else f"{label}<{short}>"+ out.append(+ _Finding(written, "consumer", offset, "consumer", symbol, fault, optional=optional)+ )++ for d in _class_decls(masked, vb, generic_only=False):+ lowered = {t.lower() for t in d.tparams}+ for name, args in d.bases:+ got = _consumed_arg(name, args, known) if name.lower() != "iconsumer" else None+ if got and got[0].lower() not in lowered:+ emit(got[0], got[1], d.offset, name, optional=False)++ spans = scan.helper_spans.get(rel, [])+ for m in (_REGISTER_VB if vb else _REGISTER_CS).finditer(masked):+ if any(a <= m.start() < b for a, b in spans):+ continue+ g = _generic_at(masked, m.end(), vb)+ ref = _base_ref(g[0][0], vb) if g else None+ got = _consumed_arg(*ref, known) if ref and ref[0].lower() != "iconsumer" else None+ if got:+ emit(got[0], got[1], m.start(), "AddConsumer", optional=True)++ if scan.helpers:+ names = "|".join(sorted({re.escape(n) for n, _ in scan.helpers}))+ call = re.compile(rf"\b({names})\s*(?=<|\(\s*Of\b)", re.IGNORECASE)+ for m in call.finditer(masked):+ g = _generic_at(masked, m.end(), vb)+ if not g or masked[_skip_ws(masked, g[1], vb) :][:1] != "(":+ continue+ if not _configurator_receiver(masked, m.start(), vb):+ continue+ for idx, fault in scan.helpers.get((m.group(1).lower(), len(g[0])), ()):+ emit(g[0][idx], fault, m.start(), m.group(1), optional=True)+ return out+++# ---------------------------------------------------------------------------+# Request clients and saga initialisers+# ---------------------------------------------------------------------------++_CS_REQUEST_CLIENT = re.compile(r"\bIRequestClient\s*(?=<)")+_VB_REQUEST_CLIENT = re.compile(r"\bIRequestClient\s*(?=\(\s*Of\b)", re.IGNORECASE)+_CS_INIT = re.compile(+ r"\.\s*(Publish|Send|Respond)(?:Async)?\s*\(\s*"+ r"(?:[\w.]+\s*,\s*|new\s+\w+\s*\([^()]*\)\s*,\s*)?"+ r"\(?\s*\w+\s*\)?\s*=>\s*\w+\s*\.\s*Init\s*"+ r"<\s*((?:global::)?[\w.]+)\s*>"+)+_VB_INIT = re.compile(+ r"\.\s*(Publish|Send|Respond)(?:Async)?\s*\(\s*Function\s*\(\s*\w+\s*\)\s*\w+\s*\.\s*Init\s*"+ r"\(\s*Of\s+((?:Global\.)?[\w.]+)\s*\)",+ re.IGNORECASE,+)+++def _request_findings(masked: str, vb: bool) -> list[_Finding]:+ out: list[_Finding] = []+ for m in (_VB_REQUEST_CLIENT if vb else _CS_REQUEST_CLIENT).finditer(masked):+ g = _generic_at(masked, m.end(), vb)+ written = _written_type(g[0][0]) if g and len(g[0]) == 1 else None+ if written:+ short = written.rsplit(".", 1)[-1]+ out.append(+ _Finding(written, "provider", m.start(), "request", f"IRequestClient({short})")+ )+ for m in (_VB_INIT if vb else _CS_INIT).finditer(masked):+ kind = _CALL_KIND[m.group(1).capitalize()]+ short = m.group(2).rsplit(".", 1)[-1]+ out.append(_Finding(m.group(2), "provider", m.start(), kind, f"Init({short})"))+ return out+++# ---------------------------------------------------------------------------+# Extractor+# ---------------------------------------------------------------------------++_HINTS = (+ ".Publish",+ ".Send",+ ".Schedule",+ ".Respond",+ "CreateRequestClient",+ "IRequestClient",+ "IConsumer",+ "MassTransitStateMachine",+)+++@dataclass(frozen=True)+class _Finding:+ written: str+ role: str+ offset: int+ kind: str+ symbol: str+ fault: bool = False+ dataflow: bool = False+ receiver: str | None = None+ line: int | None = None+ optional: bool = False+++_MEDIATOR_TYPES = frozenset({"imediator", "isender", "ipublisher", "mediator"})+++def _is_mediator(masked: str, vb: bool, call: _ProducerCall) -> bool:+ """Whether the call's receiver variable is declared as a mediator type."""+ if not re.fullmatch(r"[A-Za-z_]\w*", call.receiver):+ return False+ typ = _declared_type(masked, call.start, call.receiver, vb)+ return typ is not None and typ.rsplit(".", 1)[-1].lower() in _MEDIATOR_TYPES+++def _producer_findings(+ masked: str, vb: bool, scan: _RepoScan, call_re: re.Pattern[str]+) -> list[_Finding]:+ out: list[_Finding] = []+ for call in _find_producers(masked, vb, call_re, scan.wrappers):+ if "mediat" in call.receiver.lower() or _is_mediator(masked, vb, call):+ continue+ out.append(+ _Finding(+ call.written,+ "provider",+ call.start,+ _CALL_KIND.get(call.base, "schedule"),+ f"{call.method}({call.written.rsplit('.', 1)[-1]})",+ dataflow=call.dataflow,+ receiver=call.receiver,+ )+ )+ return out+++def _consumer_findings(masked: str, vb: bool) -> list[_Finding]:+ out: list[_Finding] = []+ consume_lines: dict[str, int] = {}+ for m in (_VB_CONSUME_METHOD if vb else _CS_CONSUME_METHOD).finditer(masked):+ consume_lines.setdefault(_norm_generic(m.group(1)), line_at(masked, m.start()))++ for m in (_VB_CONSUMER if vb else _CS_CONSUMER).finditer(masked):+ inner = m.group(1)+ fault = _FAULT.match(inner)+ written = fault.group(1) if fault else inner+ if not _DOTTED.fullmatch(_GLOBAL_PREFIX.sub("", written)):+ continue+ short = written.rsplit(".", 1)[-1]+ out.append(+ _Finding(+ written,+ "consumer",+ m.start(),+ "consumer",+ f"IConsumer<Fault<{short}>>" if fault else f"IConsumer<{short}>",+ fault=fault is not None,+ line=consume_lines.get(_norm_generic(inner)),+ )+ )++ if (_VB_STATE_MACHINE if vb else _CS_STATE_MACHINE).search(masked):+ for m in (_VB_SAGA_EVENT if vb else _CS_SAGA_EVENT).finditer(masked):+ short = m.group(1).rsplit(".", 1)[-1]+ out.append(_Finding(m.group(1), "consumer", m.start(), "saga", f"Event<{short}>"))+ return out+++_VB_TYPE_DECL = re.compile(+ r"^[ \t]*(?:\w+[ \t]+)*?(?:Class|Structure|Interface|Enum|Module)[ \t]+(\w+)",+ re.IGNORECASE | re.MULTILINE,+)+++def _local_type_names(+ sources: Sequence[tuple[str, bool, str]], index: MessageTypeIndex+) -> set[str]:+ """Lower-cased names of the types the repo declares that are not indexed messages."""+ names: set[str] = set()+ for _, vb, content in sources:+ if vb:+ names.update(m.group(1).lower() for m in _VB_TYPE_DECL.finditer(content))+ continue+ for decl in scan_type_declarations(content):+ if decl.fqn not in index.fqns:+ names.add(decl.name.lower())+ return names+++class MassTransitExtractor:+ """Extract MassTransit producer and consumer contracts from C# and VB.NET."""++ def __init__(self, contract_project_pattern: str = DEFAULT_CONTRACT_PROJECT_PATTERN) -> None:+ self._contract_project_pattern = contract_project_pattern++ @classmethod+ def source_extensions(cls) -> frozenset[str]:+ return CSHARP | VBNET++ def extract(+ self,+ repo_path: Path,+ repo_alias: str = "",+ exclude: Callable[[str], bool] | None = None,+ files: Sequence[SourceFile] | None = None,+ message_types: MessageTypeIndex | None = None,+ stats: dict[str, int] | None = None,+ ) -> list[Contract]:+ from repowise.core.workspace.contracts import Contract++ if message_types is None:+ message_types = build_message_type_index(+ {repo_alias: repo_path}, exclude, self._contract_project_pattern+ )+ if not message_types.fqns:+ return []+ resolver = _Resolver(message_types)+ counters = stats if stats is not None else {}+ contracts: list[Contract] = []+ seen: set[tuple[str, str, str, bool]] = set()++ sources = [+ (rel_path, suffix in VBNET, content.removeprefix("\ufeff"))+ for rel_path, suffix, content in select_files(+ repo_path, self.source_extensions(), exclude, files+ )+ if not _in_test_project(rel_path)+ ]+ masks: dict[str, str] = {}++ def mask(rel_path: str, vb: bool, content: str) -> str:+ if rel_path not in masks:+ masks[rel_path] = _mask_non_code(content, vb)+ return masks[rel_path]++ local_cache: list[set[str]] = []++ def local_names() -> set[str]:+ if not local_cache:+ local_cache.append(_local_type_names(sources, message_types))+ return local_cache[0]++ scan = _prescan(sources, mask)+ call_re = _call_pattern(scan.wrappers)+ hints = _HINTS + tuple(scan.wrappers) + tuple(scan.helper_names) + tuple(scan.open_names)++ for rel_path, vb, content in sources:+ if not any(h in content for h in hints):+ continue+ masked = mask(rel_path, vb, content)+ ctx = _file_context(masked, vb)+ findings = (+ _producer_findings(masked, vb, scan, call_re)+ + _request_findings(masked, vb)+ + _consumer_findings(masked, vb)+ )+ if scan.open_consumers:+ findings += _open_generic_findings(masked, vb, rel_path, scan)++ for f in findings:+ res = resolver.resolve(f.written, ctx, local_names)+ if isinstance(res, str):+ if f.optional:+ continue+ name = "masstransit_ambiguous" if res == "ambiguous" else (+ f"masstransit_{f.role.replace('provider', 'producer')}_unresolved"+ )+ counters[name] = counters.get(name, 0) + 1+ continue+ ns, _, short = res.fqn.rpartition(".")+ contract_id = f"topic::{ns}:{short}".lower()+ if (rel_path, contract_id, f.role, f.fault) in seen:+ continue+ seen.add((rel_path, contract_id, f.role, f.fault))+ meta: dict = {+ "topic": f"{ns}:{short}",+ "broker": "masstransit",+ "message_type": res.fqn,+ "kind": f.kind,+ "fault": f.fault,+ "resolution": "dataflow" if f.dataflow else res.resolution,+ }+ if f.receiver is not None:+ meta["receiver"] = f.receiver+ confidence = min(res.confidence, _TIER_DATAFLOW) if f.dataflow else res.confidence+ contracts.append(+ Contract(+ repo=repo_alias,+ contract_id=contract_id,+ contract_type="topic",+ role=f.role,+ file_path=rel_path,+ symbol_name=f.symbol,+ confidence=confidence,+ service=None,+ line=f.line if f.line is not None else line_at(content, f.offset),+ meta=meta,+ )+ )+ return contractsdiff --git a/tests/unit/workspace/test_contract_config.py b/tests/unit/workspace/test_contract_config.pyindex 8bef1bbbd..6674e85e3 100644--- a/tests/unit/workspace/test_contract_config.py+++ b/tests/unit/workspace/test_contract_config.py@@ -136,3 +136,21 @@ class TestWorkspaceConfigWithContracts:assert loaded.contracts.detect_topics is Falseassert len(loaded.contracts.manual_links) == 1assert loaded.contracts.manual_links[0].contract_id == "http::GET::/jobs"+++class TestContractProjectPattern:+ def test_default_is_omitted_from_the_dict(self) -> None:+ assert "contract_project_pattern" not in ContractConfig().to_dict()++ def test_round_trip(self) -> None:+ cfg = ContractConfig(contract_project_pattern=r".+\.messages")+ loaded = ContractConfig.from_dict(cfg.to_dict())+ assert loaded.contract_project_pattern == r".+\.messages"++ def test_pattern_changes_the_fingerprinted_dict(self) -> None:+ changed = ContractConfig(contract_project_pattern="messages")+ assert ContractConfig().to_dict() != changed.to_dict()++ def test_invalid_regex_falls_back_to_the_default(self) -> None:+ cfg = ContractConfig.from_dict({"contract_project_pattern": "(unclosed"})+ assert cfg.contract_project_pattern == ContractConfig().contract_project_patterndiff --git a/tests/unit/workspace/test_incremental_extraction.py b/tests/unit/workspace/test_incremental_extraction.pyindex ff1d31d12..39d5ed5f4 100644--- a/tests/unit/workspace/test_incremental_extraction.py+++ b/tests/unit/workspace/test_incremental_extraction.py@@ -495,3 +495,127 @@ async def test_walk_count_scales_with_changed_repos_not_workspace_size(full_total = sum(s.get("files_walked", 0) for s in first.extraction_stats.values())assert 0 < walked_this_run < full_totalassert second.extraction_stats["alpha"]["walks"] == 1 # still one walk per repo+++# ---------------------------------------------------------------------------+# MassTransit: the message-type index is part of the extraction fingerprint+# ---------------------------------------------------------------------------+++def _message_repos(tmp_path: Path, contract_dir: str = "Sample.Contracts") -> tuple[Path, Path]:+ """Alpha declares the message ``Ping``; beta consumes ``Ping`` and ``Pong``."""+ alpha, beta = tmp_path / "alpha", tmp_path / "beta"+ contract = alpha / contract_dir+ contract.mkdir()+ (contract / f"{contract_dir}.csproj").write_text("<Project />", encoding="utf-8")+ _message(contract, "Ping")+ (beta / "Consumers.cs").write_text(+ "using Sample.Contracts;\n"+ "public class PingConsumer : IConsumer<Ping> { }\n"+ "public class PongConsumer : IConsumer<Pong> { }\n",+ encoding="utf-8",+ )+ _commit_all(alpha, beta, message="contract")+ return alpha, contract+++def _message(directory: Path, name: str) -> None:+ (directory / f"{name}.cs").write_text(+ f"namespace Sample.Contracts\n{{\n public class {name} {{ }}\n}}\n", encoding="utf-8"+ )+++def _commit_all(*repos: Path, message: str) -> None:+ for repo in repos:+ _git(repo, "add", "-A")+ _git(repo, "commit", "-q", "-m", message)+++def _topic_ids(store: ContractStore, alias: str) -> list[str]:+ return sorted(c.contract_id for c in store.rows_for_repo(alias) if c.contract_type == "topic")+++async def test_new_contract_type_in_one_repo_re_extracts_its_consumers_elsewhere(+ workspace: WorkspaceConfig, tmp_path: Path, no_save: None, extracted: list[str]+) -> None:+ """A MassTransit consumer resolves against another repo's contract project.++ Beta's source and HEAD never move, so only the message-type fingerprint can+ tell it that the message it consumes now exists.+ """+ alpha, contract = _message_repos(tmp_path)+ first = await _first_run(workspace, tmp_path)+ assert _topic_ids(first, "beta") == ["topic::sample.contracts:ping"]+ extracted.clear()++ _message(contract, "Pong")+ _commit_all(alpha, message="add Pong")+ second = await run_contract_extraction(workspace, tmp_path, ["alpha"], None, first)++ assert sorted(extracted) == ["alpha", "beta"]+ assert _topic_ids(second, "beta") == [+ "topic::sample.contracts:ping",+ "topic::sample.contracts:pong",+ ]+++async def test_removed_contract_type_re_extracts_its_consumers_elsewhere(+ workspace: WorkspaceConfig, tmp_path: Path, no_save: None, extracted: list[str]+) -> None:+ alpha, contract = _message_repos(tmp_path)+ first = await _first_run(workspace, tmp_path)+ extracted.clear()++ (contract / "Ping.cs").unlink()+ _commit_all(alpha, message="remove Ping")+ second = await run_contract_extraction(workspace, tmp_path, ["alpha"], None, first)++ assert sorted(extracted) == ["alpha", "beta"]+ assert _topic_ids(second, "beta") == []+++async def test_renamed_contract_type_re_extracts_its_consumers_elsewhere(+ workspace: WorkspaceConfig, tmp_path: Path, no_save: None, extracted: list[str]+) -> None:+ alpha, contract = _message_repos(tmp_path)+ first = await _first_run(workspace, tmp_path)+ extracted.clear()++ (contract / "Ping.cs").unlink()+ _message(contract, "Pong")+ _commit_all(alpha, message="rename Ping to Pong")+ second = await run_contract_extraction(workspace, tmp_path, ["alpha"], None, first)++ assert sorted(extracted) == ["alpha", "beta"]+ assert _topic_ids(second, "beta") == ["topic::sample.contracts:pong"]+++async def test_unchanged_contract_types_still_reuse(+ workspace: WorkspaceConfig, tmp_path: Path, no_save: None, extracted: list[str]+) -> None:+ _message_repos(tmp_path)+ first = await _first_run(workspace, tmp_path)+ extracted.clear()++ await run_contract_extraction(workspace, tmp_path, [], None, first)++ assert extracted == []+++async def test_changed_contract_project_pattern_re_extracts_every_repo(+ workspace: WorkspaceConfig, tmp_path: Path, no_save: None, extracted: list[str]+) -> None:+ """The pattern decides which projects hold messages, and moves no commit."""+ _message_repos(tmp_path, contract_dir="Sample.Messages")+ first = await _first_run(workspace, tmp_path)+ assert _topic_ids(first, "beta") == []+ extracted.clear()++ configured = WorkspaceConfig(+ repos=list(workspace.repos),+ contracts=ContractConfig(contract_project_pattern=r".+\.messages"),+ )+ second = await run_contract_extraction(configured, tmp_path, [], None, first)++ assert sorted(extracted) == ["alpha", "beta"]+ assert _topic_ids(second, "beta") == ["topic::sample.contracts:ping"]diff --git a/tests/unit/workspace/test_masstransit_extractor.py b/tests/unit/workspace/test_masstransit_extractor.pynew file mode 100644index 000000000..3e492d54e--- /dev/null+++ b/tests/unit/workspace/test_masstransit_extractor.py@@ -0,0 +1,833 @@+"""MassTransit producer/consumer contracts for C# and VB.NET.++Fixtures are small hand-written examples.+"""++from __future__ import annotations++from pathlib import Path++import pytest++from repowise.core.workspace.contracts import Contract, ContractLink+from repowise.core.workspace.extractors import MassTransitExtractor, build_message_type_index+from repowise.core.workspace.matching import match_contracts++NS = "Sample.Contracts"+++def _write(root: Path, rel: str, text: str) -> None:+ path = root / rel+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(text, encoding="utf-8")+++def _contract_project(root: Path, project: str, namespace: str, types: list[str]) -> None:+ """A ``<project>/<project>.csproj`` holding one C# file per message type."""+ name = project.rsplit("/", 1)[-1]+ _write(root, f"{project}/{name}.csproj", '<Project Sdk="Microsoft.NET.Sdk" />')+ for name in types:+ _write(+ root,+ f"{project}/{name}.cs",+ f"namespace {namespace}\n{{\n public class {name}\n {{\n }}\n}}\n",+ )+++def _extract(repos: dict[str, Path]) -> tuple[list[Contract], dict[str, dict[str, int]]]:+ index = build_message_type_index(repos)+ rows: list[Contract] = []+ stats: dict[str, dict[str, int]] = {}+ for alias, path in repos.items():+ stats[alias] = {}+ rows += MassTransitExtractor().extract(+ path, alias, message_types=index, stats=stats[alias]+ )+ return rows, stats+++def _rows(rows: list[Contract], role: str, file_suffix: str = "") -> list[Contract]:+ return [r for r in rows if r.role == role and r.file_path.endswith(file_suffix)]+++def _links(rows: list[Contract]) -> list[ContractLink]:+ return [link for link in match_contracts(rows) if link.contract_type == "topic"]+++def _id(name: str, namespace: str = NS) -> str:+ return f"topic::{namespace}:{name}".lower()+++def contracts(tmp_path: Path) -> Path:+ root = tmp_path / "contracts"+ _contract_project(+ root, "Sample.Contracts", NS, ["OrderSubmitted", "OrderCancelled", "Ping", "Pong"]+ )+ return root+++def _app(tmp_path: Path, name: str, files: dict[str, str]) -> Path:+ root = tmp_path / name+ for rel, text in files.items():+ _write(root, rel, text)+ return root+++def _cs_usings() -> str:+ return f"using MassTransit;\nusing {NS};\n"+++class TestContractIndex:+ def test_only_contract_projects_contribute_types(self, tmp_path: Path) -> None:+ root = tmp_path / "repo"+ _contract_project(root, "Acme.Contracts", "Acme.Messages", ["InContracts"])+ _contract_project(root, "src/Contracts", "Acme.Folder", ["InFolder"])+ _contract_project(root, "Acme.ContractNotes", "Acme.Notes", ["NotAMessage"])+ _contract_project(root, "Acme.Contracts.Tests", "Acme.Tests", ["TestOnly"])+ _write(+ root,+ "Acme.Contracts/obj/Generated.cs",+ "namespace Acme.Gen { public class Generated {} }",+ )++ index = build_message_type_index({"repo": root})++ assert index.fqns == {"Acme.Messages.InContracts", "Acme.Folder.InFolder"}+ assert index.by_short["InFolder"] == {"Acme.Folder.InFolder"}++ def test_nested_types_are_not_messages(self, tmp_path: Path) -> None:+ root = tmp_path / "repo"+ _write(root, "Sample.Contracts/Sample.Contracts.csproj", "<Project />")+ _write(+ root,+ "Sample.Contracts/Outer.cs",+ "namespace Sample.Contracts\n{\n public class Outer\n {\n"+ " public class Inner { }\n }\n}\n",+ )++ assert build_message_type_index({"repo": root}).fqns == {"Sample.Contracts.Outer"}++ def test_generic_types_are_not_messages(self, tmp_path: Path) -> None:+ root = tmp_path / "repo"+ _write(root, "Sample.Contracts/Sample.Contracts.csproj", "<Project />")+ _write(+ root,+ "Sample.Contracts/Envelope.cs",+ "namespace Sample.Contracts\n{\n public class Envelope<T> { }\n"+ " public class Plain { }\n}\n",+ )++ assert build_message_type_index({"repo": root}).fqns == {"Sample.Contracts.Plain"}+++class TestContractProjectPattern:+ def test_configured_pattern_replaces_the_default(self, tmp_path: Path) -> None:+ root = tmp_path / "repo"+ _contract_project(root, "Acme.Messages", "Acme.Messages", ["Configured"])+ _contract_project(root, "Acme.Contracts", "Acme.Contracts", ["Default"])++ index = build_message_type_index({"repo": root}, contract_project_pattern=r".+\.messages")++ assert index.fqns == {"Acme.Messages.Configured"}++ def test_singular_names_need_a_widened_pattern(self, tmp_path: Path) -> None:+ root = tmp_path / "repo"+ _contract_project(root, "Acme.Contract", "Acme.Contract", ["Singular"])++ assert build_message_type_index({"repo": root}).fqns == set()+ widened = build_message_type_index({"repo": root}, None, r"(?:.+\.)?contracts?")+ assert widened.fqns == {"Acme.Contract.Singular"}++ def test_pattern_must_match_the_whole_directory_name(self, tmp_path: Path) -> None:+ root = tmp_path / "repo"+ _contract_project(root, "Acme.Messages.Extras", "Acme.Extras", ["Partial"])++ index = build_message_type_index({"repo": root}, contract_project_pattern="messages")++ assert index.fqns == set()++ def test_extractor_uses_its_own_pattern_without_a_prebuilt_index(self, tmp_path: Path) -> None:+ root = tmp_path / "repo"+ _contract_project(root, "Acme.Messages", "Acme.Messages", ["Ping"])+ _write(root, "Worker.cs", "using Acme.Messages;\npublic class W : IConsumer<Ping> { }\n")++ rows = MassTransitExtractor(r".+\.messages").extract(root, "repo")++ assert [r.contract_id for r in rows] == ["topic::acme.messages:ping"]+++class TestConsumers:+ def test_each_message_binds_to_its_own_consume_method(+ self, contracts: Path, tmp_path: Path+ ) -> None:+ worker = _app(+ tmp_path,+ "warehouse",+ {+ "OrderConsumer.cs": (+ "using System.Threading.Tasks;\n"+ "using MassTransit;\n"+ f"using {NS};\n\n"+ "public class Handler : IConsumer<OrderCancelled>, IConsumer<OrderSubmitted>\n"+ "{\n"+ " public Task Consume(ConsumeContext<OrderCancelled> context) =>\n"+ " Task.CompletedTask;\n\n"+ " public Task Consume(ConsumeContext<OrderSubmitted> context) =>\n"+ " Task.CompletedTask;\n"+ "}\n"+ )+ },+ )++ rows, _ = _extract({"contracts": contracts, "warehouse": worker})++ by_id = {r.contract_id: r for r in _rows(rows, "consumer")}+ assert set(by_id) == {_id("OrderCancelled"), _id("OrderSubmitted")}+ submitted = by_id[_id("OrderSubmitted")]+ assert submitted.line == 10+ assert by_id[_id("OrderCancelled")].line == 7+ assert submitted.meta["message_type"] == f"{NS}.OrderSubmitted"+ assert submitted.meta["kind"] == "consumer"+ assert submitted.meta["broker"] == "masstransit"+ assert submitted.meta["fault"] is False+ assert submitted.meta["resolution"] == "using"+ assert submitted.confidence == 0.8++ def test_fault_consumer_is_keyed_on_the_inner_message(+ self, contracts: Path, tmp_path: Path+ ) -> None:+ worker = _app(+ tmp_path,+ "worker",+ {"Faults.cs": f"using {NS};\npublic class Faults : IConsumer<Fault<Ping>>\n{{\n}}\n"},+ )++ rows, _ = _extract({"contracts": contracts, "worker": worker})++ (row,) = _rows(rows, "consumer")+ assert row.contract_id == _id("Ping")+ assert row.meta["fault"] is True++ def test_fault_and_plain_consumer_of_one_message_are_two_rows(+ self, contracts: Path, tmp_path: Path+ ) -> None:+ worker = _app(+ tmp_path,+ "worker",+ {+ "Both.cs": (+ f"using {NS};\n"+ "public class Both : IConsumer<Ping>, IConsumer<Fault<Ping>>\n"+ "{\n"+ " public Task Consume(ConsumeContext<Ping> context) => null;\n"+ " public Task Consume(ConsumeContext<Fault<Ping>> context) => null;\n"+ "}\n"+ )+ },+ )++ rows, _ = _extract({"contracts": contracts, "worker": worker})++ by_fault = {r.meta["fault"]: r for r in _rows(rows, "consumer")}+ assert set(by_fault) == {True, False}+ assert by_fault[False].line == 4+ assert by_fault[True].line == 5++ def test_open_generic_consumer_yields_nothing(self, contracts: Path, tmp_path: Path) -> None:+ worker = _app(+ tmp_path,+ "worker",+ {+ "Base.cs": (+ f"using {NS};\n"+ "public abstract class Base<TMessage> : IConsumer<TMessage>\n"+ " where TMessage : class\n{\n}\n"+ )+ },+ )++ rows, stats = _extract({"contracts": contracts, "worker": worker})++ assert _rows(rows, "consumer") == []+ assert stats["worker"]["masstransit_consumer_unresolved"] == 1++ def test_byte_order_mark_does_not_hide_the_namespace_or_usings(self, tmp_path: Path) -> None:+ root = tmp_path / "repo"+ _write(root, "Sample.Contracts/Sample.Contracts.csproj", "<Project />")+ (root / "Sample.Contracts" / "Ping.cs").write_bytes(+ b"\xef\xbb\xbfnamespace Sample.Contracts\n{\n public class Ping { }\n}\n"+ )+ (root / "C.cs").write_bytes(+ b"\xef\xbb\xbfusing Sample.Contracts;\npublic class C : IConsumer<Ping>\n{\n}\n"+ )++ rows, _ = _extract({"repo": root})++ (row,) = _rows(rows, "consumer")+ assert row.contract_id == _id("Ping")+ assert row.meta["resolution"] == "using"++ def test_vb_implements_with_several_interfaces(+ self, contracts: Path, tmp_path: Path+ ) -> None:+ worker = _app(+ tmp_path,+ "worker",+ {+ "Handler.vb": (+ f"Imports {NS}\n\n"+ "Public Class Handler\n"+ " Implements IConsumer(Of Ping)\n"+ " Implements IConsumer(Of Pong)\n\n"+ " Public Async Function Consume(context As ConsumeContext(Of Pong)) "+ "As Task Implements IConsumer(Of Pong).Consume\n"+ " End Function\n"+ "End Class\n"+ )+ },+ )++ rows, _ = _extract({"contracts": contracts, "worker": worker})++ assert {r.contract_id for r in _rows(rows, "consumer")} == {_id("Ping"), _id("Pong")}++ def test_saga_events_are_consumers_only_in_a_state_machine_file(+ self, contracts: Path, tmp_path: Path+ ) -> None:+ sagas = _app(+ tmp_path,+ "sagas",+ {+ "OrderStateMachine.cs": (+ "public class OrderStateMachine : MassTransitStateMachine<OrderState>\n"+ "{\n"+ f" public Event<{NS}.OrderSubmitted> Submitted {{ get; }}\n"+ "}\n"+ ),+ "Other.cs": (+ "public class Other\n{\n"+ f" public Event<{NS}.OrderCancelled> Cancelled {{ get; }}\n"+ "}\n"+ ),+ },+ )++ rows, _ = _extract({"contracts": contracts, "sagas": sagas})++ (row,) = _rows(rows, "consumer", "OrderStateMachine.cs")+ assert row.contract_id == _id("OrderSubmitted")+ assert row.meta["kind"] == "saga"+ assert _rows(rows, "consumer", "Other.cs") == []++ @pytest.mark.parametrize(+ ("vb", "text"),+ [+ (False, "// class C : IConsumer<Ping>\n/* IConsumer<Ping> */"),+ (True, "' Implements IConsumer(Of Ping)\nREM Implements IConsumer(Of Pong)"),+ ],+ )+ def test_commented_out_consumers_are_ignored(+ self, contracts: Path, tmp_path: Path, vb: bool, text: str+ ) -> None:+ imports = f"Imports {NS}\n" if vb else f"using {NS};\n"+ worker = _app(tmp_path, "worker", {"Old.vb" if vb else "Old.cs": imports + text + "\n"})++ rows, _ = _extract({"contracts": contracts, "worker": worker})++ assert _rows(rows, "consumer") == []+++class TestProducers:+ @pytest.mark.parametrize(+ ("call", "kind"),+ [+ ("Task.Run(() => bus.Publish<Ping>(new { Id = 1 }));", "publish"),+ ("await bus.Publish<Ping>(\n new\n {\n Id = 1,\n });", "publish"),+ ("await context.Publish<Ping>(new { Id = 1 }, ct);", "publish"),+ ("x => x.Then(s => s.Publish<OrderState, Ping>(new { Id = 1 }))", "publish"),+ ("await endpoint.Send<Ping>(new { Id = 1 });", "send"),+ (+ "await scheduler.ScheduleRecurringSend<Ping>(uri, schedule, new { Id = 1 });",+ "schedule",+ ),+ ("await bus.Publish(new Ping { Id = 1 });", "publish"),+ ("await scheduler.SchedulePublish(DateTime.UtcNow, new Ping());", "schedule"),+ ("await scheduler.ScheduleSend(uri, DateTime.UtcNow, new Ping());", "schedule"),+ ("await scheduler.ScheduleRecurringSend(uri, schedule, new Ping());", "schedule"),+ ],+ )+ def test_csharp_call_shapes(+ self, contracts: Path, tmp_path: Path, call: str, kind: str+ ) -> None:+ app = _app(+ tmp_path,+ "app",+ {+ "Publisher.cs": (+ f"using {NS};\n\npublic class Publisher\n{{\n void Run()\n {{\n"+ f"{call}\n }}\n}}\n"+ )+ },+ )++ rows, _ = _extract({"contracts": contracts, "app": app})++ (row,) = _rows(rows, "provider")+ assert row.contract_id == _id("Ping")+ assert row.meta["kind"] == kind+ assert row.file_path == "Publisher.cs"++ def test_schedule_argument_form_reads_the_message_not_the_time(+ self, contracts: Path, tmp_path: Path+ ) -> None:+ app = _app(+ tmp_path,+ "app",+ {+ "Timers.cs": (+ f"using {NS};\n\npublic class Timers\n{{\n"+ " void Run(DateTime when)\n {\n"+ " scheduler.SchedulePublish(when, new OrderSubmitted());\n"+ " scheduler.ScheduleSend(new Uri(\"queue:x\"), when, new Pong());\n"+ " scheduler.SchedulePublish(when, other);\n"+ " }\n}\n"+ )+ },+ )++ rows, _ = _extract({"contracts": contracts, "app": app})++ assert {r.contract_id for r in _rows(rows, "provider")} == {+ _id("OrderSubmitted"),+ _id("Pong"),+ }++ def test_producer_row_line_is_the_call_line(self, contracts: Path, tmp_path: Path) -> None:+ app = _app(+ tmp_path,+ "app",+ {+ "P.cs": (+ f"using {NS};\n\nclass P\n{{\n void M()\n {{\n"+ " var x = 1;\n bus.Publish<Ping>(new { });\n }\n}\n"+ )+ },+ )++ rows, _ = _extract({"contracts": contracts, "app": app})++ (row,) = _rows(rows, "provider")+ assert row.line == 8+ assert row.meta["receiver"] == "bus"++ def test_vb_dataflow_with_dim_as_new_and_dim_equals_new(+ self, contracts: Path, tmp_path: Path+ ) -> None:+ imports = f"Imports {NS}\n\n"+ app = _app(+ tmp_path,+ "app",+ {+ "AsNew.vb": (+ imports + "Public Class A\n Sub Go()\n"+ " Dim message As New OrderSubmitted()\n"+ " bus.Send(message)\n"+ " End Sub\nEnd Class\n"+ ),+ "EqualsNew.vb": (+ imports + "Public Class B\n Sub Go()\n"+ " Dim message = New OrderSubmitted() With\n"+ " {\n .Id = 1\n }\n"+ " bus.Send(message)\n"+ " End Sub\nEnd Class\n"+ ),+ },+ )++ rows, _ = _extract({"contracts": contracts, "app": app})++ providers = _rows(rows, "provider")+ assert {r.file_path for r in providers} == {"AsNew.vb", "EqualsNew.vb"}+ for row in providers:+ assert row.contract_id == _id("OrderSubmitted")+ assert row.meta["resolution"] == "dataflow"+ assert row.confidence == 0.7++ def test_vb_publish_with_a_generic_argument(self, contracts: Path, tmp_path: Path) -> None:+ app = _app(+ tmp_path,+ "app",+ {+ "Publisher.vb": (+ f"Imports {NS}\n\nPublic Class Publisher\n"+ " Public Async Sub Run()\n"+ " Await bus.Publish(Of Pong)(New With {.Id = 1})\n"+ " End Sub\nEnd Class\n"+ )+ },+ )++ rows, _ = _extract({"contracts": contracts, "app": app})++ (row,) = _rows(rows, "provider")+ assert row.contract_id == _id("Pong")++ def test_csharp_dataflow_from_var_declared_and_parameter(+ self, contracts: Path, tmp_path: Path+ ) -> None:+ app = _app(+ tmp_path,+ "app",+ {+ "Flow.cs": (+ f"using {NS};\n\nclass Flow\n{{\n"+ " void A()\n {\n var msg = new Ping();\n"+ " bus.Send(msg);\n }\n\n"+ " void B(Pong other)\n {\n bus.Publish(other);\n }\n}\n"+ )+ },+ )++ rows, _ = _extract({"contracts": contracts, "app": app})++ assert {r.meta["message_type"].rsplit(".", 1)[-1] for r in _rows(rows, "provider")} == {+ "Ping",+ "Pong",+ }++ def test_vb_variable_declared_in_another_method_is_not_used(+ self, contracts: Path, tmp_path: Path+ ) -> None:+ app = _app(+ tmp_path,+ "app",+ {+ "Scope.vb": (+ f"Imports {NS}\n\nPublic Class S\n"+ " Sub First()\n Dim message As New Ping()\n End Sub\n\n"+ " Sub Second()\n bus.Send(message)\n End Sub\nEnd Class\n"+ )+ },+ )++ rows, _ = _extract({"contracts": contracts, "app": app})++ assert _rows(rows, "provider") == []++ def test_mediator_anonymous_and_commented_calls_yield_nothing(+ self, contracts: Path, tmp_path: Path+ ) -> None:+ app = _app(+ tmp_path,+ "app",+ {+ "Noise.cs": (+ f"using {NS};\n\nclass N\n{{\n"+ " private readonly IPublisher _events;\n\n"+ " void M(IMediator m, ISender sender)\n {\n"+ " mediator.Publish(new Ping());\n"+ " m.Send(new Ping());\n"+ " sender.Send<Ping>(x);\n"+ " _events.Publish(new Pong());\n"+ " bus.Send(new { A = 1 });\n"+ " // bus.Publish<Ping>(new { });\n"+ " /* bus.Publish(new Ping()); */\n"+ ' log("bus.Publish<Ping>(x)");\n'+ " }\n}\n"+ ),+ "Noise.vb": (+ f"Imports {NS}\n\nPublic Class V\n Sub M()\n"+ " ' bus.Publish(New Ping())\n"+ " REM bus.Publish(New Ping())\n"+ " bus.Send(New With {.A = 1})\n"+ " End Sub\nEnd Class\n"+ ),+ },+ )++ rows, _ = _extract({"contracts": contracts, "app": app})++ assert [r for r in rows if r.repo == "app"] == []++ def test_a_bus_receiver_next_to_a_mediator_still_counts(+ self, contracts: Path, tmp_path: Path+ ) -> None:+ app = _app(+ tmp_path,+ "app",+ {+ "Both.cs": (+ f"using {NS};\n\nclass B\n{{\n"+ " void M(IMediator m, IBus bus)\n {\n"+ " m.Send(new Ping());\n"+ " bus.Publish(new Pong());\n"+ " }\n}\n"+ )+ },+ )++ rows, _ = _extract({"contracts": contracts, "app": app})++ assert {r.contract_id for r in _rows(rows, "provider")} == {_id("Pong")}++ def test_test_projects_yield_no_producers_and_no_indexed_types(+ self, contracts: Path, tmp_path: Path+ ) -> None:+ app = _app(+ tmp_path,+ "app",+ {+ "Sample.Orders.Tests/PublishTests.cs": (+ f"using {NS};\nclass T\n{{\n void M() => bus.Publish<Ping>(new {{ }});\n}}\n"+ )+ },+ )+ _contract_project(app, "Sample.Contracts.Tests", "Sample.Tests", ["TestOnlyMessage"])++ rows, _ = _extract({"contracts": contracts, "app": app})++ assert [r for r in rows if r.repo == "app"] == []+ assert "Sample.Tests.TestOnlyMessage" not in build_message_type_index({"app": app}).fqns++ def test_type_outside_any_contract_project_is_counted_not_linked(+ self, contracts: Path, tmp_path: Path+ ) -> None:+ app = _app(+ tmp_path,+ "app",+ {+ "Mail.cs": (+ "class M\n{\n void Go()\n {\n"+ " smtp.Send<Envelope>(new Envelope());\n"+ " bus.Publish(new Envelope());\n }\n}\n"+ )+ },+ )++ rows, stats = _extract({"contracts": contracts, "app": app})++ assert [r for r in rows if r.repo == "app"] == []+ assert stats["app"]["masstransit_producer_unresolved"] == 2+++class TestResolution:+ @pytest.fixture+ def twin_contracts(self, tmp_path: Path) -> dict[str, Path]:+ a, b = tmp_path / "a", tmp_path / "b"+ _contract_project(a, "Alpha.Contracts", "Alpha.Contracts", ["Ping"])+ _contract_project(b, "Beta.Contracts", "Beta.Contracts", ["Ping"])+ return {"a": a, "b": b}++ def test_same_short_name_in_two_namespaces_is_ambiguous(+ self, twin_contracts: dict[str, Path], tmp_path: Path+ ) -> None:+ worker = _app(tmp_path, "worker", {"C.cs": "public class C : IConsumer<Ping>\n{\n}\n"})++ rows, stats = _extract({**twin_contracts, "worker": worker})++ assert _rows(rows, "consumer") == []+ assert stats["worker"]["masstransit_ambiguous"] == 1++ def test_a_using_picks_the_namespace(+ self, twin_contracts: dict[str, Path], tmp_path: Path+ ) -> None:+ worker = _app(+ tmp_path,+ "worker",+ {"C.cs": "using Beta.Contracts;\npublic class C : IConsumer<Ping>\n{\n}\n"},+ )++ rows, _ = _extract({**twin_contracts, "worker": worker})++ (row,) = _rows(rows, "consumer")+ assert row.contract_id == "topic::beta.contracts:ping"++ def test_qualified_name_resolves_relative_to_a_parent_namespace(+ self, contracts: Path, tmp_path: Path+ ) -> None:+ app = _app(+ tmp_path,+ "app",+ {+ "S.cs": (+ "namespace Sample.Orders\n{\n public class S\n {\n"+ " void M() => bus.Publish<Contracts.Ping>(new { });\n"+ " }\n}\n"+ )+ },+ )++ rows, _ = _extract({"contracts": contracts, "app": app})++ (row,) = _rows(rows, "provider")+ assert row.meta["resolution"] == "qualified"+ assert row.confidence == 0.8++ def test_unknown_qualified_name_does_not_fall_back_to_the_short_name(+ self, contracts: Path, tmp_path: Path+ ) -> None:+ app = _app(+ tmp_path,+ "app",+ {+ "Mail.cs": (+ "class M\n{\n void Go()\n {\n"+ " mailer.Send(new Other.Mail.Ping());\n"+ " mailer.Send(new Ping());\n }\n}\n"+ )+ },+ )++ rows, stats = _extract({"contracts": contracts, "app": app})++ (row,) = _rows(rows, "provider", "Mail.cs")+ assert row.meta["resolution"] == "unique_name"+ assert stats["app"]["masstransit_producer_unresolved"] == 1++ def test_using_alias_and_unique_name_fallback(self, contracts: Path, tmp_path: Path) -> None:+ app = _app(+ tmp_path,+ "app",+ {+ "Aliased.cs": (+ "using Msg = Sample.Contracts;\nclass A\n{\n"+ " void M() => bus.Publish<Msg.Ping>(new { });\n}\n"+ ),+ "Global.cs": "class G\n{\n void M() => bus.Publish<Pong>(new { });\n}\n",+ },+ )++ rows, _ = _extract({"contracts": contracts, "app": app})++ by_file = {r.file_path: r for r in _rows(rows, "provider")}+ assert by_file["Aliased.cs"].meta["resolution"] == "qualified"+ assert by_file["Global.cs"].meta["resolution"] == "unique_name"+ assert by_file["Global.cs"].confidence == 0.6++ def test_short_name_is_not_used_when_the_repo_declares_that_type_itself(+ self, contracts: Path, tmp_path: Path+ ) -> None:+ app = _app(+ tmp_path,+ "app",+ {+ "Ping.cs": "namespace Local\n{\n public class Ping { }\n}\n",+ "Use.cs": "class U\n{\n void M() => bus.Publish(new Ping());\n}\n",+ "Other.cs": "class O\n{\n void M() => bus.Publish(new Pong());\n}\n",+ },+ )++ rows, stats = _extract({"contracts": contracts, "app": app})++ assert [r.contract_id for r in _rows(rows, "provider")] == [_id("Pong")]+ assert stats["app"]["masstransit_producer_unresolved"] == 1++ def test_a_using_still_reaches_the_contract_when_a_local_type_shares_the_name(+ self, contracts: Path, tmp_path: Path+ ) -> None:+ app = _app(+ tmp_path,+ "app",+ {+ "Ping.vb": "Public Class Ping\nEnd Class\n",+ "Use.cs": (+ f"using {NS};\nclass U\n{{\n void M() => bus.Publish(new Ping());\n}}\n"+ ),+ },+ )++ rows, _ = _extract({"contracts": contracts, "app": app})++ (row,) = _rows(rows, "provider")+ assert row.meta["resolution"] == "using"+++class TestLinks:+ @pytest.fixture+ def orders(self, tmp_path: Path) -> Path:+ return _app(+ tmp_path,+ "orders",+ {+ "Sample.Orders/Publisher.vb": (+ f"Imports {NS}\n\n"+ "Public Class Publisher\n"+ " Public Async Sub Submit()\n"+ " Await bus.Publish(New OrderSubmitted() With {.Id = 1})\n"+ " End Sub\n"+ "End Class\n"+ )+ },+ )++ def _consumer_repo(self, tmp_path: Path, name: str) -> Path:+ return _app(+ tmp_path,+ name,+ {+ "Consumers.cs": (+ f"using {NS};\npublic class OrderConsumer : IConsumer<OrderSubmitted>\n"+ "{\n}\n"+ )+ },+ )++ def test_one_producer_links_each_consumer_repo(+ self, contracts: Path, orders: Path, tmp_path: Path+ ) -> None:+ repos = {"contracts": contracts, "orders": orders}+ for name in ("x", "y", "z"):+ repos[name] = self._consumer_repo(tmp_path, name)++ rows, _ = _extract(repos)++ links = [link for link in _links(rows) if link.contract_id == _id("OrderSubmitted")]+ assert sorted(link.consumer_repo for link in links) == ["x", "y", "z"]+ assert {link.provider_repo for link in links} == {"orders"}+ assert {link.provider_file for link in links} == {"Sample.Orders/Publisher.vb"}++ def test_dataflow_producer_links_a_consumer(+ self, contracts: Path, tmp_path: Path+ ) -> None:+ orders = _app(+ tmp_path,+ "orders",+ {+ "Ship.vb": (+ f"Imports {NS}\n\nPublic Class Ship\n Sub Go()\n"+ " Dim message = New Pong() With {.Id = 1}\n"+ " bus.Send(message)\n"+ " End Sub\nEnd Class\n"+ )+ },+ )+ warehouse = _app(+ tmp_path,+ "warehouse",+ {"Consumer.cs": f"using {NS};\npublic class PongConsumer : IConsumer<Pong> {{ }}\n"},+ )++ rows, _ = _extract({"contracts": contracts, "orders": orders, "warehouse": warehouse})++ (link,) = [link for link in _links(rows) if link.contract_id == _id("Pong")]+ assert (link.provider_repo, link.consumer_repo) == ("orders", "warehouse")+ (provider,) = _rows(rows, "provider", "Ship.vb")+ assert provider.meta["resolution"] == "dataflow"++ def test_same_repo_producer_and_consumer_do_not_self_link(+ self, contracts: Path, orders: Path, tmp_path: Path+ ) -> None:+ _write(+ orders,+ "Sample.Orders/SelfConsumer.cs",+ f"using {NS};\npublic class SelfConsumer : IConsumer<OrderSubmitted>\n{{\n}}\n",+ )+ other = self._consumer_repo(tmp_path, "other")++ rows, _ = _extract({"contracts": contracts, "orders": orders, "other": other})++ links = [link for link in _links(rows) if link.contract_id == _id("OrderSubmitted")]+ assert [(link.provider_repo, link.consumer_repo) for link in links] == [+ ("orders", "other")+ ]diff --git a/tests/unit/workspace/test_masstransit_generic_links.py b/tests/unit/workspace/test_masstransit_generic_links.pynew file mode 100644index 000000000..ddeccefd1--- /dev/null+++ b/tests/unit/workspace/test_masstransit_generic_links.py@@ -0,0 +1,750 @@+"""MassTransit links formed through generics, wrappers, requests and saga initialisers.++Fixtures are small hand-written examples: a ``Sample.Contracts`` project declaring+the messages, and app repos that publish or consume them.+"""++from __future__ import annotations++from pathlib import Path++import pytest++from repowise.core.workspace.contracts import Contract+from repowise.core.workspace.extractors import MassTransitExtractor, build_message_type_index+from repowise.core.workspace.matching import match_contracts++NS = "Sample.Contracts"+MESSAGES = ["Ping", "Pong", "OrderSubmitted", "OrderCancelled", "OrderStatusRequest", "OrderStatus"]+++def _write(root: Path, rel: str, text: str) -> None:+ path = root / rel+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(text, encoding="utf-8")+++def _extract(repos: dict[str, Path]) -> list[Contract]:+ index = build_message_type_index(repos)+ rows: list[Contract] = []+ for alias, path in repos.items():+ rows += MassTransitExtractor().extract(path, alias, message_types=index)+ fqns = {f.lower() for f in index.fqns}+ for row in rows:+ # Every emitted id resolves to a declared contract type, never a guess.+ assert row.meta["message_type"].lower() in fqns+ return rows+++def _ids(rows: list[Contract], role: str, *, fault: bool = False, kind: str | None = None) -> set:+ return {+ r.contract_id.rsplit(":", 1)[-1]+ for r in rows+ if r.role == role and r.meta["fault"] is fault and (kind is None or r.meta["kind"] == kind)+ }+++def contracts(tmp_path: Path) -> Path:+ root = tmp_path / "contracts"+ _write(root, "Sample.Contracts/Sample.Contracts.csproj", '<Project Sdk="Microsoft.NET.Sdk" />')+ for name in MESSAGES:+ _write(+ root,+ f"Sample.Contracts/{name}.cs",+ f"namespace {NS}\n{{\n public class {name}\n {{\n }}\n}}\n",+ )+ return root+++def _app(tmp_path: Path, name: str, files: dict[str, str]) -> Path:+ root = tmp_path / name+ for rel, text in files.items():+ _write(root, rel, text)+ return root+++ECHO_CONSUMER = """public class EchoConsumer<T> : IConsumer<T> where T : class+{+ public Task Consume(ConsumeContext<T> context) => Task.CompletedTask;+}+"""++AUDIT_FAULTS = """public class AuditFaults<T> : IConsumer<Fault<T>> where T : class+{+ public Task Consume(ConsumeContext<Fault<T>> context) => Task.CompletedTask;+}+"""++ADD_HANDLER = """public static class Extensions+{+ public static void AddHandler<T>(this IBusRegistrationConfigurator cfg) where T : class+ {+ cfg.AddConsumer<EchoConsumer<T>>();+ }+}+"""+++def _configure(*statements: str) -> str:+ body = "".join(f" {s}\n" for s in statements)+ return (+ f"using {NS};\npublic class Setup\n{{\n"+ f" public void Configure(IBusRegistrationConfigurator cfg)\n {{\n{body} }}\n}}\n"+ )+++class TestOpenGenericConsumers:+ def test_open_generic_alone_yields_nothing(self, contracts: Path, tmp_path: Path) -> None:+ worker = _app(tmp_path, "worker", {"Echo.cs": ECHO_CONSUMER + ADD_HANDLER})++ rows = _extract({"contracts": contracts, "worker": worker})++ assert [r for r in rows if r.role == "consumer"] == []++ def test_helper_call_sites_register_each_message(+ self, contracts: Path, tmp_path: Path+ ) -> None:+ worker = _app(+ tmp_path,+ "worker",+ {+ "Echo.cs": ECHO_CONSUMER + ADD_HANDLER,+ "Setup.cs": _configure("cfg.AddHandler<Ping>();", "cfg.AddHandler<Pong>();"),+ },+ )++ rows = _extract({"contracts": contracts, "worker": worker})++ assert _ids(rows, "consumer") == {"ping", "pong"}+ assert _ids(rows, "consumer", fault=True) == set()++ def test_closed_generic_consumer_registered_directly(+ self, contracts: Path, tmp_path: Path+ ) -> None:+ worker = _app(+ tmp_path,+ "worker",+ {+ "Echo.cs": ECHO_CONSUMER,+ "Setup.cs": _configure("cfg.AddConsumer<EchoConsumer<OrderSubmitted>>();"),+ },+ )++ rows = _extract({"contracts": contracts, "worker": worker})++ assert _ids(rows, "consumer") == {"ordersubmitted"}++ def test_fault_consumer_closes_as_a_fault_of_the_argument(+ self, contracts: Path, tmp_path: Path+ ) -> None:+ worker = _app(+ tmp_path,+ "worker",+ {+ "Faults.cs": AUDIT_FAULTS,+ "Setup.cs": _configure("cfg.AddConsumer<AuditFaults<Ping>>();"),+ },+ )++ rows = _extract({"contracts": contracts, "worker": worker})++ assert _ids(rows, "consumer") == set()+ assert _ids(rows, "consumer", fault=True) == {"ping"}++ def test_vb_helper_and_generic_class(self, contracts: Path, tmp_path: Path) -> None:+ worker = _app(+ tmp_path,+ "worker",+ {+ "Echo.vb": (+ "Public Class EchoConsumer(Of T As Class)\n"+ " Implements IConsumer(Of T)\n"+ "End Class\n"+ "Public Module Extensions\n"+ " <Extension()>\n"+ " Public Sub AddHandler(Of T As Class)"+ "(ByVal cfg As IBusRegistrationConfigurator)\n"+ " cfg.AddConsumer(Of EchoConsumer(Of T))()\n"+ " End Sub\n"+ "End Module\n"+ ),+ "Setup.vb": (+ f"Imports {NS}\n"+ "Public Class Setup\n"+ " Public Sub Configure(cfg As IBusRegistrationConfigurator)\n"+ " cfg.AddHandler(Of Ping)()\n"+ " End Sub\n"+ "End Class\n"+ ),+ },+ )++ rows = _extract({"contracts": contracts, "worker": worker})++ assert _ids(rows, "consumer") == {"ping"}+++LOGGING_BASE = """public abstract class LoggingConsumer<TMessage> : IConsumer<TMessage>+ where TMessage : class+{+}+"""++FAULT_BASE = """public abstract class FaultHandler<T> : IConsumer<Fault<T>> where T : class+{+}+"""+++class TestGenericConsumerBases:+ def test_subclass_is_keyed_on_the_message_argument(+ self, contracts: Path, tmp_path: Path+ ) -> None:+ worker = _app(+ tmp_path,+ "worker",+ {+ "Base.cs": LOGGING_BASE,+ "Handlers.cs": (+ f"using {NS};\npublic class PingHandler : LoggingConsumer<Ping>\n{{\n}}\n"+ ),+ },+ )++ rows = _extract({"contracts": contracts, "worker": worker})++ assert _ids(rows, "consumer") == {"ping"}++ def test_other_type_arguments_are_not_consumed(self, contracts: Path, tmp_path: Path) -> None:+ worker = _app(+ tmp_path,+ "worker",+ {+ "Handler.cs": (+ "public class RetrySettings { }\n"+ "public abstract class Handler<TMessage, TOptions> : IConsumer<TMessage>\n"+ " where TMessage : class\n{\n}\n"+ ),+ "Handlers.cs": (+ f"using {NS};\n"+ "public class PongHandler : Handler<Pong, RetrySettings>\n{\n}\n"+ "public class SwappedHandler : Handler<OrderCancelled, Ping>\n{\n}\n"+ ),+ },+ )++ rows = _extract({"contracts": contracts, "worker": worker})++ # Ping is only a second type argument there, so it is never consumed.+ assert _ids(rows, "consumer") == {"pong", "ordercancelled"}++ def test_a_three_level_chain_reaches_the_concrete_class(+ self, contracts: Path, tmp_path: Path+ ) -> None:+ worker = _app(+ tmp_path,+ "worker",+ {+ "Chain.cs": (+ "public abstract class BaseConsumer<T> : IConsumer<T> where T : class\n{\n}\n"+ "public abstract class MiddleConsumer<T> : BaseConsumer<T> where T : class\n"+ "{\n}\n"+ ),+ "Concrete.cs": (+ f"using {NS};\n"+ "public class SubmittedConsumer : MiddleConsumer<OrderSubmitted>\n{\n}\n"+ ),+ },+ )++ rows = _extract({"contracts": contracts, "worker": worker})++ assert _ids(rows, "consumer") == {"ordersubmitted"}++ def test_fault_consumer_base_is_a_fault_of_the_argument(+ self, contracts: Path, tmp_path: Path+ ) -> None:+ worker = _app(+ tmp_path,+ "worker",+ {+ "Base.cs": FAULT_BASE,+ "Handlers.cs": (+ f"using {NS};\npublic class CancelFaults : FaultHandler<OrderCancelled>\n"+ "{\n}\n"+ ),+ },+ )++ rows = _extract({"contracts": contracts, "worker": worker})++ assert _ids(rows, "consumer") == set()+ assert _ids(rows, "consumer", fault=True) == {"ordercancelled"}++ def test_open_generic_base_alone_yields_nothing(self, contracts: Path, tmp_path: Path) -> None:+ worker = _app(tmp_path, "worker", {"Base.cs": LOGGING_BASE})++ rows = _extract({"contracts": contracts, "worker": worker})++ assert [r for r in rows if r.role == "consumer"] == []++ def test_vb_inherits_a_generic_base(self, contracts: Path, tmp_path: Path) -> None:+ worker = _app(+ tmp_path,+ "worker",+ {+ "Base.vb": (+ "Public MustInherit Class LoggingConsumer(Of TMessage As Class)\n"+ " Implements IConsumer(Of TMessage)\n"+ "End Class\n"+ ),+ "Handlers.vb": (+ f"Imports {NS}\n"+ "Public Class PingHandler\n"+ " Inherits LoggingConsumer(Of Ping)\n"+ "End Class\n"+ ),+ },+ )++ rows = _extract({"contracts": contracts, "worker": worker})++ assert _ids(rows, "consumer") == {"ping"}+++WRAPPER = """using Sample.Contracts;+public static class BusExtensions+{+ public static Task PublishMessage<T>(this IPublishEndpoint e, T m) where T : class+ {+ return e.Publish(m);+ }++ public static Task SendMessage(this ISendEndpoint endpoint, object message)+ => endpoint.Send(message);++ public static Task Describe(this IBus bus, string text)+ {+ return Console.Out.Send(prefix + text);+ }+}+"""+++class TestWrapperMethods:+ def test_extension_that_publishes_its_message_makes_callers_producers(+ self, contracts: Path, tmp_path: Path+ ) -> None:+ orders = _app(+ tmp_path,+ "orders",+ {+ "Bus.cs": WRAPPER,+ "Submit.cs": (+ f"using {NS};\n"+ "public class Submit\n{\n"+ " public Task Run(IPublishEndpoint bus)\n {\n"+ " return bus.PublishMessage(new OrderSubmitted());\n"+ " }\n"+ " public Task Cancel(IPublishEndpoint bus)\n {\n"+ " return bus.PublishMessage<OrderCancelled>(null);\n"+ " }\n"+ " public Task Text(IBus bus)\n {\n"+ " return bus.Describe(new OrderStatus().ToString());\n"+ " }\n}\n"+ ),+ },+ )+ worker = _app(+ tmp_path,+ "worker",+ {+ "Handler.cs": (+ f"using {NS};\npublic class H : IConsumer<OrderSubmitted>\n{{\n"+ " public Task Consume(ConsumeContext<OrderSubmitted> context) => null;\n}\n"+ )+ },+ )++ rows = _extract({"contracts": contracts, "orders": orders, "worker": worker})++ assert _ids(rows, "provider", kind="publish") == {"ordersubmitted", "ordercancelled"}+ # Describe sends text, not its message parameter, so it is not a wrapper.+ assert "orderstatus" not in _ids(rows, "provider")+ links = [link for link in match_contracts(rows) if link.contract_type == "topic"]+ assert len(links) == 1++ def test_vb_extension_wrapper(self, contracts: Path, tmp_path: Path) -> None:+ orders = _app(+ tmp_path,+ "orders",+ {+ "Bus.vb": (+ "Public Module BusExtensions\n"+ " <Extension()>\n"+ " Public Function SendMessage(Of T As Class)"+ "(ByVal endpoint As ISendEndpoint, ByVal message As T) As Task\n"+ " Return endpoint.Send(message)\n"+ " End Function\n"+ "End Module\n"+ ),+ "Submit.vb": (+ f"Imports {NS}\n"+ "Public Class Submit\n"+ " Public Sub Run(endpoint As ISendEndpoint)\n"+ " endpoint.SendMessage(New OrderSubmitted())\n"+ " End Sub\n"+ "End Class\n"+ ),+ },+ )++ rows = _extract({"contracts": contracts, "orders": orders})++ assert _ids(rows, "provider", kind="send") == {"ordersubmitted"}++ def test_non_extension_method_is_not_a_wrapper(self, contracts: Path, tmp_path: Path) -> None:+ orders = _app(+ tmp_path,+ "orders",+ {+ "Util.cs": (+ "public static class Util\n{\n"+ " public static Task PublishMessage<T>(IPublishEndpoint bus, T message)\n"+ " where T : class => bus.Publish(message);\n}\n"+ ),+ "Submit.cs": (+ f"using {NS};\n"+ "public class Submit\n{\n"+ " public Task Run(IPublishEndpoint bus) =>\n"+ " Util.PublishMessage(bus, null);\n}\n"+ ),+ },+ )++ rows = _extract({"contracts": contracts, "orders": orders})++ assert _ids(rows, "provider") == set()+++class TestRequestResponse:+ def test_request_clients_produce_the_request_and_responses_produce_the_response(+ self, contracts: Path, tmp_path: Path+ ) -> None:+ client = _app(+ tmp_path,+ "client",+ {+ "Lookup.cs": (+ f"using {NS};\n"+ "public class Lookup\n{\n"+ " public Lookup(IRequestClient<OrderStatusRequest> client) { }\n}\n"+ ),+ "Other.cs": (+ f"using {NS};\n"+ "public class Other\n{\n"+ " public void Run(IBus bus)\n {\n"+ " var client = bus.CreateRequestClient<OrderSubmitted>();\n"+ " }\n}\n"+ ),+ },+ )+ server = _app(+ tmp_path,+ "server",+ {+ "Handler.cs": (+ f"using {NS};\n"+ "public class StatusHandler : IConsumer<OrderStatusRequest>\n{\n"+ " public async Task Consume(ConsumeContext<OrderStatusRequest> context)\n"+ " {\n"+ " await context.RespondAsync<OrderStatus>(new { });\n"+ " context.Respond(new OrderCancelled());\n"+ " }\n}\n"+ )+ },+ )++ rows = _extract({"contracts": contracts, "client": client, "server": server})++ assert _ids(rows, "provider", kind="request") == {"orderstatusrequest", "ordersubmitted"}+ assert _ids(rows, "provider", kind="respond") == {"orderstatus", "ordercancelled"}+ links = {+ (link.provider_repo, link.consumer_repo, link.contract_id.rsplit(":", 1)[-1])+ for link in match_contracts(rows)+ if link.contract_type == "topic"+ }+ assert ("client", "server", "orderstatusrequest") in links++ def test_mediator_request_client_is_not_a_producer(+ self, contracts: Path, tmp_path: Path+ ) -> None:+ client = _app(+ tmp_path,+ "client",+ {+ "Lookup.cs": (+ f"using {NS};\n"+ "public class Lookup\n{\n"+ " public void Run(IMediator mediator)\n {\n"+ " var c = mediator.CreateRequestClient<OrderStatusRequest>();\n"+ " }\n}\n"+ )+ },+ )++ rows = _extract({"contracts": contracts, "client": client})++ assert _ids(rows, "provider") == set()+++class TestSagaInitialisers:+ def test_init_inside_publish_and_send_async_is_a_producer(+ self, contracts: Path, tmp_path: Path+ ) -> None:+ saga = _app(+ tmp_path,+ "saga",+ {+ "Machine.cs": (+ f"using {NS};\n"+ "public class OrderStateMachine : MassTransitStateMachine<OrderState>\n{\n"+ " public OrderStateMachine()\n {\n"+ " During(Submitted, When(Timeout)\n"+ " .PublishAsync(ctx => ctx.Init<OrderSubmitted>(new { }))\n"+ ' .SendAsync(new Uri("queue:x"), '+ "(ctx) => ctx.Init<OrderCancelled>(new { })));\n"+ " }\n}\n"+ )+ },+ )++ rows = _extract({"contracts": contracts, "saga": saga})++ assert _ids(rows, "provider") == {"ordersubmitted", "ordercancelled"}++ def test_init_outside_a_publish_or_send_is_not_a_producer(+ self, contracts: Path, tmp_path: Path+ ) -> None:+ saga = _app(+ tmp_path,+ "saga",+ {+ "Machine.cs": (+ f"using {NS};\n"+ "public class Helper\n{\n"+ " public object Build(Ctx ctx) => ctx.Init<OrderSubmitted>(new { });\n}\n"+ "// .Publish(ctx => ctx.Init<OrderCancelled>(new { }))\n"+ )+ },+ )++ rows = _extract({"contracts": contracts, "saga": saga})++ assert rows == []+++class TestEndpointConventions:+ def test_convention_markers_are_never_producers(self, contracts: Path, tmp_path: Path) -> None:+ worker = _app(+ tmp_path,+ "worker",+ {+ "Setup.cs": (+ f"using {NS};\n"+ "public class Setup\n{\n"+ " public void Configure()\n {\n"+ ' EndpointConvention.Map<OrderSubmitted>(new Uri("queue:orders"));\n'+ " EndpointConventions.Map.TypesFromNamespaceToQueue<OrderCancelled>"+ '("orders");\n'+ " }\n}\n"+ )+ },+ )++ rows = _extract({"contracts": contracts, "worker": worker})++ assert _ids(rows, "provider") == set()+++class TestGateAndPrecision:+ def test_names_without_consumer_still_close_bases_and_helpers(+ self, contracts: Path, tmp_path: Path+ ) -> None:+ worker = _app(+ tmp_path,+ "worker",+ {+ "Bases.cs": (+ "public abstract class Handler<TMsg, TOpts> : IConsumer<TMsg>\n"+ " where TMsg : class\n{\n}\n"+ "public class Listener<T> : IConsumer<T> where T : class\n{\n}\n"+ "public static class Wiring\n{\n"+ " public static void AddPair<TA, TB>(this IBusRegistrationConfigurator c)\n"+ " where TA : class\n {\n"+ " c.AddConsumer<Listener<TA>>();\n }\n}\n"+ ),+ "Receiver.cs": (+ f"using {NS};\npublic class PingReceiver : Handler<Ping, Pong>\n{{\n}}\n"+ ),+ "Setup.cs": (+ f"using {NS};\n"+ "public class Setup\n{\n"+ " public void Run(IBusRegistrationConfigurator cfg)\n {\n"+ " cfg.AddPair<OrderCancelled, OrderStatus>();\n }\n}\n"+ ),+ },+ )++ rows = _extract({"contracts": contracts, "worker": worker})++ assert _ids(rows, "consumer") == {"ping", "ordercancelled"}++ def test_wrapper_precision(self, contracts: Path, tmp_path: Path) -> None:+ orders = _app(+ tmp_path,+ "orders",+ {+ "Bus.cs": (+ "public static class Utils\n{\n"+ " public static Task PubWith<TBus, TMsg>(this IBus bus, TMsg m)\n"+ " where TMsg : class\n {\n return bus.Publish(m);\n }\n"+ " public static Task PubInner<T>(this IBus bus, T m)\n"+ " where T : class\n {\n"+ " return bus.Publish(m.Inner);\n }\n"+ " public static Task PubLog<T>(this ILogger log, T m)\n"+ " where T : class\n {\n"+ " return log.Publish(m);\n }\n"+ " public static Task PubOther<T>(this IBus bus, T m)\n"+ " where T : class\n {\n"+ " return other.Publish(m);\n }\n}\n"+ ),+ "Use.cs": (+ f"using {NS};\n"+ "public class Use\n{\n"+ " public Task Run(IBus bus, ILogger logger)\n {\n"+ " bus.PubWith<OrderStatus, OrderSubmitted>(null);\n"+ " bus.PubInner(new OrderCancelled());\n"+ " logger.PubLog(new OrderCancelled());\n"+ " bus.PubOther(new OrderCancelled());\n"+ " return Task.CompletedTask;\n }\n}\n"+ ),+ },+ )++ rows = _extract({"contracts": contracts, "orders": orders})++ assert _ids(rows, "provider") == {"ordersubmitted"}++ def test_static_form_skips_the_receiver_argument(+ self, contracts: Path, tmp_path: Path+ ) -> None:+ orders = _app(+ tmp_path,+ "orders",+ {+ "Bus.cs": (+ "public static class Utils\n{\n"+ " public static Task PubWith<T>(this IBus bus, T m) where T : class\n {\n"+ " return bus.Publish(m);\n }\n}\n"+ ),+ "Use.cs": (+ f"using {NS};\n"+ "public class Use\n{\n"+ " public Task Run(IBus bus2)\n {\n"+ " return Utils.PubWith(bus2, new OrderSubmitted());\n }\n}\n"+ ),+ },+ )++ rows = _extract({"contracts": contracts, "orders": orders})++ assert _ids(rows, "provider") == {"ordersubmitted"}++ def test_vb_body_send_on_another_receiver_is_not_a_wrapper(+ self, contracts: Path, tmp_path: Path+ ) -> None:+ orders = _app(+ tmp_path,+ "orders",+ {+ "Bus.vb": (+ "Public Module Utils\n"+ " <Extension()>\n"+ " Public Sub Log(Of T As Class)(ByVal bus As IBus, ByVal msg As T)\n"+ " Console.Send(msg)\n"+ " End Sub\n"+ "End Module\n"+ ),+ "Use.vb": (+ f"Imports {NS}\n"+ "Public Class Use\n"+ " Public Sub Run(bus As IBus)\n"+ " bus.Log(New OrderSubmitted())\n"+ " End Sub\n"+ "End Class\n"+ ),+ },+ )++ rows = _extract({"contracts": contracts, "orders": orders})++ assert _ids(rows, "provider") == set()++ def test_helper_name_collision_on_a_container_is_not_a_registration(+ self, contracts: Path, tmp_path: Path+ ) -> None:+ worker = _app(+ tmp_path,+ "worker",+ {+ "Echo.cs": ECHO_CONSUMER + ADD_HANDLER.replace("AddHandler", "Register"),+ "Other.cs": (+ "public static class Di\n{\n"+ " public static void Register<T>(this IServiceProvider sp)\n"+ " where T : class\n {\n"+ " sp.AddConsumer<EchoConsumer<T>>();\n }\n}\n"+ ),+ "Setup.cs": (+ f"using {NS};\n"+ "public class Setup\n{\n"+ " public void Run(IContainer container)\n {\n"+ " container.Register<OrderSubmitted>();\n }\n}\n"+ ),+ },+ )++ rows = _extract({"contracts": contracts, "worker": worker})++ assert [r for r in rows if r.role == "consumer"] == []++ def test_overloads_with_different_arity_pick_the_matching_type_argument(+ self, contracts: Path, tmp_path: Path+ ) -> None:+ orders = _app(+ tmp_path,+ "orders",+ {+ "Bus.cs": (+ "public static class Utils\n{\n"+ " public static Task PubWith<T>(this IPublishEndpoint bus, T m)\n"+ " where T : class\n"+ " {\n return bus.Publish(m);\n }\n"+ " public static Task PubWith<TCtx, T>(this ConsumeContext<TCtx> ctx, T m)\n"+ " where T : class\n {\n return ctx.Publish(m);\n }\n}\n"+ ),+ "Use.cs": (+ f"using {NS};\n"+ "public class Use\n{\n"+ " public Task Run(IPublishEndpoint bus, ConsumeContext<OrderStatus> ctx)\n"+ " {\n"+ " bus.PubWith<OrderSubmitted>(null);\n"+ " return ctx.PubWith<OrderStatus, OrderCancelled>(null);\n }\n}\n"+ ),+ },+ )++ rows = _extract({"contracts": contracts, "orders": orders})++ assert _ids(rows, "provider") == {"ordersubmitted", "ordercancelled"}