Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(workspace): Go AMQP topics, queues named through their declaration, and Python class constants (#4542)

Raghav Chamadiyab92d94c82a57
diff --git a/docs/architecture/language-support.md b/docs/architecture/language-support.md
index 7bc425cb7..37b79c01b 100644
--- a/docs/architecture/language-support.md
+++ b/docs/architecture/language-support.md
@@ -1316,6 +1316,9 @@ mislead the masker.
| **Socket** | SignalR `MapHub`, FastAPI `@app.websocket`, `ws`, NestJS gateways; socket.io `emit`, Laravel broadcast events, Pusher `trigger` | ClientWebSocket, SignalR client, NativeWebSocket, WebSocketSharp, `new WebSocket(url)`; socket.io `on`, Laravel Echo, pusher-js |
| **Data** | DDL `CREATE`/`ALTER`, Alembic `op.create_table`, Laravel `Schema::create`/`Schema::table`, Knex migrations, ORM models (SQLAlchemy, SQLModel, Django, JPA, EF Core, ActiveRecord, Eloquent, Prisma, TypeORM, Sequelize, Drizzle) | SQL string literals in app code (sqlglot-parsed, verb-anchored-regex fallback), Laravel `DB::table`, Knex queries |
+RabbitMQ topics are also read from Go (streadway/amqp, amqp091-go), including
+a queue named through its declaration's result (`q.Name`).
+
See [docs/scale/WORKSPACES.md](../scale/WORKSPACES.md) for the user-facing
workspace guide, and [workspace.md](workspace.md) for the layer's pipeline,
registries and contributor recipes.
diff --git a/docs/scale/WORKSPACES.md b/docs/scale/WORKSPACES.md
index 1c0c4cdc8..1bcbd1fbc 100644
--- a/docs/scale/WORKSPACES.md
+++ b/docs/scale/WORKSPACES.md
@@ -172,7 +172,10 @@ Scans source files for HTTP routes, gRPC services, database tables, message topi
Socket detection is toggled by `detect_socket` in the `contracts:` block below.
A topic, queue or route name is resolved when it is a literal or a constant the
-same file assigns once; a name built at runtime is skipped, not guessed. HTTP
+same file assigns once; a name built at runtime is skipped, not guessed. RabbitMQ
+is also read from Go (streadway/amqp, amqp091-go), and a queue named through its
+declaration's result (`q.Name` after Go `QueueDeclare`, amqplib `assertQueue`, pika
+`queue_declare`) resolves when that file declares it with a settled name. HTTP
routes match on their full path, with router mount prefixes stitched on first.
An ambiguous target becomes a lower-confidence **candidate** link, and a unique
one an **exact** link. The exact naming and matching rules for each transport
diff --git a/packages/core/src/repowise/core/workspace/extractors/strings.py b/packages/core/src/repowise/core/workspace/extractors/strings.py
index 957327466..8fdfcf16a 100644
--- a/packages/core/src/repowise/core/workspace/extractors/strings.py
+++ b/packages/core/src/repowise/core/workspace/extractors/strings.py
@@ -51,7 +51,9 @@ class StringSyntax:
trailing decoration from the right-hand side (Ruby's ``.freeze``).
``members`` locates a constant object or enum (``const Q = {``,
``enum Q {``), ending at its opening brace; each ``key: value`` or
- ``key = value`` entry folds as ``Q.key``.
+ ``key = value`` entry folds as ``Q.key``. ``self_prefixes`` read a
+ class's own member (PHP ``self::X``, Python ``self.X``), looked up as the
+ bare name the class body assigns.
"""
quotes: str = "\"'"
@@ -68,6 +70,7 @@ class StringSyntax:
assignment: re.Pattern[str] | None = None
assignment_strip: re.Pattern[str] | None = None
members: re.Pattern[str] | None = None
+ self_prefixes: tuple[str, ...] = ()
# ---------------------------------------------------------------------------
@@ -245,12 +248,22 @@ def _interpolates(prefix: str, quote: str, syntax: StringSyntax) -> bool:
)
-def _lookup(name: str, constants: dict[str, str]) -> str | None:
+# The value recorded for a `self.X` the file assigns but does not settle: it
+# resolves to nothing, so `self.X` is refused rather than read as a bare `X`.
+_UNSETTLED = ""
+
+
+def _lookup(name: str, constants: dict[str, str], syntax: StringSyntax) -> str | None:
const = constants.get(name)
if const is None and name.startswith("$"):
const = constants.get(name[1:]) # a PHP variable, keyed without its sigil
- if const is None and name.startswith(("self::", "static::")):
- const = constants.get(name.partition("::")[2]) # a PHP class constant
+ if const is None:
+ for prefix in syntax.self_prefixes:
+ if name.startswith(prefix):
+ # A class's own member: its `self.X` binding first, else the bare `X`.
+ bare = name[len(prefix) :]
+ own = constants.get(syntax.self_prefixes[0] + bare)
+ return own if own is not None else constants.get(bare)
return const
@@ -261,7 +274,7 @@ def _fold(expr: str, syntax: StringSyntax, constants: dict[str, str]) -> str:
the corpus needs a second level, and a half-folded template would be wrong.
"""
expr = expr.strip()
- const = _lookup(expr, constants)
+ const = _lookup(expr, constants, syntax)
if const is not None:
lit = _parse_literal(const, syntax)
text = _literal_text(lit, syntax, {}) if lit is not None else None
@@ -382,7 +395,7 @@ def resolve_string(
if NAME_RE.fullmatch(text):
# A bare name. Its value resolved without constants when it was
# recorded, so this step cannot reach another bare name.
- const = _lookup(text, constants)
+ const = _lookup(text, constants, syntax)
if const is not None:
return resolve_string(const, syntax, constants)
return None
@@ -416,6 +429,8 @@ def string_constants(
return {}
text = content if code is None else code
seen: dict[str, str | None] = {}
+ # `self.X = ...` (group `own`): kept apart, so it never folds a bare `X`.
+ owned: dict[str, str | None] = {}
for m in syntax.assignment.finditer(text):
if code is None and on_comment_line(content, m.start()):
continue # an example in a doc comment is not a binding
@@ -423,9 +438,15 @@ def string_constants(
rhs = content[m.start("rhs") : m.end("rhs")].strip()
if syntax.assignment_strip is not None:
rhs = syntax.assignment_strip.sub("", rhs).strip()
+ into = owned if m.groupdict().get("own") else seen
# A second assignment retires the name whatever it assigns: the reader
# cannot tell which one reaches the use site.
- seen[name] = None if name in seen or resolve_string(rhs, syntax) is None else rhs
+ into[name] = None if name in into or resolve_string(rhs, syntax) is None else rhs
+ for name, rhs in owned.items():
+ # A `self.X` that does not settle, or that a class or module `X` also
+ # assigns, blocks the `self.X` lookup alone: the bare `X` keeps folding.
+ unsettled = rhs is None or name in seen
+ seen[syntax.self_prefixes[0] + name] = _UNSETTLED if unsettled else rhs
if syntax.members is not None:
for m in syntax.members.finditer(text):
if code is None and on_comment_line(content, m.start()):
@@ -817,10 +838,16 @@ JS_SYNTAX = StringSyntax(
),
)
-# ``NAME = <expr>`` at any indentation, RHS to end of line. The whitespace
-# around ``=`` is required, which excludes the usual unspaced keyword argument
-# on its own line (``url=str(resp.url),``) that otherwise reads as a second
-# assignment and retires the very name being folded.
+# ``NAME = <expr>`` at any indentation, RHS to end of line. A name with a
+# lower-case letter needs whitespace around ``=``, which excludes the usual
+# unspaced keyword argument on its own line (``url=str(resp.url),``) that
+# otherwise reads as a second assignment and retires the very name being
+# folded. An upper-case name is a constant by convention and may be unspaced
+# (``EXCHANGE='robot-shop'``). A line after one ending in an open bracket or a
+# comma continues a call or literal, so it assigns nothing. ``self.X = <expr>``
+# folds ``self.X`` alone; one that does not settle, or whose ``X`` is also
+# assigned bare, refuses ``self.X`` and leaves the bare ``X`` as it was.
+# ``self.X`` and ``cls.X`` otherwise read the class attribute ``X``.
PYTHON_SYNTAX = StringSyntax(
prefixes="fFrRbBuU",
template_prefixes="f",
@@ -828,9 +855,12 @@ PYTHON_SYNTAX = StringSyntax(
refuse=_ESCAPED_BRACE_RE,
refuse_prefixes="b",
assignment=re.compile(
- r"^[ \t]*(?P<name>[A-Za-z_]\w*)(?:[ \t]*:[^=\n]+)?[ \t]+=[ \t]+(?P<rhs>.*)$",
+ r"^(?<![(\[{,]\n)[ \t]*(?P<own>(?:self|cls)\.)?"
+ r"(?P<name>[A-Z_][A-Z0-9_]*(?=[ \t]*=(?!=))|[A-Za-z_]\w*(?=(?:[ \t]*:[^=\n]+)?[ \t]+=[ \t]))"
+ r"(?:[ \t]*:[^=\n]+)?[ \t]*=[ \t]*(?P<rhs>.*)$",
re.MULTILINE,
),
+ self_prefixes=("self.", "cls."),
)
RUST_SYNTAX = StringSyntax(
@@ -911,6 +941,7 @@ PHP_SYNTAX = StringSyntax(
assignment=re.compile(
r"(?:\bconst[ \t]+|\$)(?P<name>[A-Za-z_]\w*)[ \t]*=(?!=)[ \t]*(?P<rhs>[^;\n]+);"
),
+ self_prefixes=("self::", "static::"),
)
_SYNTAX_BY_LANGUAGE: tuple[tuple[frozenset[str], StringSyntax], ...] = (
diff --git a/packages/core/src/repowise/core/workspace/extractors/topic/declared.py b/packages/core/src/repowise/core/workspace/extractors/topic/declared.py
new file mode 100644
index 000000000..10fc6807a
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/extractors/topic/declared.py
@@ -0,0 +1,116 @@
+"""A queue named through the result of the call that declared it.
+
+Go code binds and consumes ``q.Name`` after ``q, err := ch.QueueDeclare("orders",
+...)``; amqplib ``q.queue`` after ``const q = await ch.assertQueue('orders')``;
+pika ``result.method.queue`` after ``result = ch.queue_declare(queue='orders')``.
+The queue is read from the file's declarations of that receiver when every one
+names the same queue and the file settles it. A server-named queue (``""``),
+a receiver declared with two names, or one the file also binds to anything
+else (an assignment, a parameter, a loop variable), stays unread.
+"""
+
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass
+from functools import lru_cache
+from typing import TYPE_CHECKING
+
+from ..strings import Arg, call_arguments, select_argument
+
+if TYPE_CHECKING:
+ from ..base import ScanContext
+ from ..calls import FileStrings
+
+_RECEIVER_RE = re.compile(r"[A-Za-z_$][\w$]*")
+# Where every supported declaring call names its queue: `QueueDeclare("q")`,
+# `assertQueue('q')`, `queue_declare(queue='q')`.
+_DECLARED_NAME = Arg(keys=("queue",), pos=0)
+
+
+@lru_cache(maxsize=256)
+def _assignment_re(receiver: str, call: str) -> re.Pattern[str]:
+ # Every assignment of *receiver*; ``decl`` is set when it is the declaring
+ # call (`q, err := ch.QueueDeclare(`, `result = channel.queue_declare(`,
+ # `const q = await ch.assertQueue(`).
+ return re.compile(
+ rf"(?<![\w$.]){re.escape(receiver)}\s*(?:,\s*[A-Za-z_]\w*)?\s*:?=(?![=>])\s*"
+ rf"(?P<decl>(?:await\s+)?(?:[\w$]+\s*\.\s*)+{re.escape(call)}\s*\()?"
+ )
+
+
+# A function's parameter list: `func f(`, `func (r *T) f(`, `def f(`,
+# `function f(`, or an arrow's `(a, b) =>` (group `arrow`).
+_SIGNATURE_RE = re.compile(
+ r"\b(?:func\s*(?:\([^()]*\)\s*)?[A-Za-z_]\w*|def\s+[A-Za-z_]\w*|function\s*[\w$]*)\s*\("
+ r"|\((?P<arrow>[^()]*)\)\s*=>"
+)
+# A parameter's name: its first identifier (`q amqp.Queue`, `*args`, `result: R = None`).
+_PARAM_NAME_RE = re.compile(r"\s*(?:\*{1,2}|\.\.\.)?([A-Za-z_$][\w$]*)")
+
+
+@lru_cache(maxsize=256)
+def _other_binding_re(receiver: str) -> re.Pattern[str]:
+ # A loop, `as` or single-parameter arrow binding (`for q in`, `as q`, `q =>`).
+ r = re.escape(receiver)
+ return re.compile(
+ rf"\b(?:as|for)\s+(?:[\w$]+\s*,\s*)?{r}\b|\b(?:const|let|var)\s+{r}\s+(?:of|in)\b"
+ rf"|(?<![\w$.]){r}\s*=>"
+ )
+
+
+def _bound_otherwise(ctx: ScanContext, receiver: str) -> bool:
+ """Whether the file binds *receiver* as a parameter or loop variable anywhere.
+
+ Ceiling: a JS class method's parameters (``consume(q) {``) are not read.
+ """
+ content = ctx.content
+ if _other_binding_re(receiver).search(content):
+ return True
+ for m in _SIGNATURE_RE.finditer(content):
+ if m.group("arrow") is not None:
+ params = m.group("arrow").split(",")
+ else:
+ params = call_arguments(content, m.end() - 1) or []
+ for p in params:
+ name = _PARAM_NAME_RE.match(p)
+ if name is not None and name.group(1) == receiver:
+ return True
+ return False
+
+
+@dataclass(frozen=True)
+class QueueDeclaration:
+ """*call* declares a queue, named at *name*; its result's *member* names it after."""
+
+ call: str
+ member: str
+ name: Arg = _DECLARED_NAME
+
+ def queues(
+ self, ctx: ScanContext, args: list[str], arg: Arg, strings: FileStrings
+ ) -> list[str]:
+ """The queue the value *arg* selects (``q.Name``) names, or ``[]``."""
+ raw = select_argument(args, arg)
+ if len(raw) != 1:
+ return []
+ receiver, dot, member = raw[0].partition(".")
+ if not dot or member != self.member or not _RECEIVER_RE.fullmatch(receiver):
+ return []
+ if _bound_otherwise(ctx, receiver):
+ return [] # a parameter of that name may hold another queue (file scope)
+ found: set[str] = set()
+ for m in _assignment_re(receiver, self.call).finditer(ctx.content):
+ if ctx.in_comment(m.start()):
+ continue
+ if m.group("decl") is None:
+ return [] # the name is bound to something else too (file scope)
+ declared = call_arguments(ctx.content, m.end() - 1) or []
+ names, refused = strings.resolve(declared, self.name)
+ if refused or not names or not all(names):
+ return [] # unread, or server-named (`""`)
+ found.update(names)
+ return list(found) if len(found) == 1 else []
+
+
+__all__ = ["QueueDeclaration"]
diff --git a/packages/core/src/repowise/core/workspace/extractors/topic/dialect.py b/packages/core/src/repowise/core/workspace/extractors/topic/dialect.py
index 21c9645a4..813728d74 100644
--- a/packages/core/src/repowise/core/workspace/extractors/topic/dialect.py
+++ b/packages/core/src/repowise/core/workspace/extractors/topic/dialect.py
@@ -39,6 +39,7 @@ if TYPE_CHECKING:
from ..base import ScanContext
from ..calls import FileStrings
from ..strings import Arg
+ from .declared import QueueDeclaration
#: Wildcard characters of each subscription-pattern syntax, which a name must
#: contain to be read as a pattern (``regex`` names are patterns outright).
@@ -55,7 +56,9 @@ class TopicCall:
substrings (the library's import) one of which the file must contain.
``normalize`` maps a resolved name to the broker's own (a queue URL to its
last segment). ``pattern`` is the subscription-pattern syntax of a
- consumer whose name may carry wildcards.
+ consumer whose name may carry wildcards. ``declared`` reads a queue
+ named through its declaration's result (``q.Name``): the ``queue`` of a
+ binding, else the ``name``.
"""
head: re.Pattern[str]
@@ -67,6 +70,7 @@ class TopicCall:
origin: ContractOrigin = ContractOrigin.CLIENT_CALL
routing_key: Arg | None = None
queue: Arg | None = None
+ declared: QueueDeclaration | None = None
default_exchange: bool = False
requires: tuple[str, ...] = ()
normalize: Callable[[str], str | None] | None = None
@@ -153,9 +157,13 @@ def call_contracts(
queues: list[str] = []
if call.queue is not None:
queues, _ = strings.resolve(args, call.queue)
+ if not queues and call.declared is not None:
+ queues = call.declared.queues(ctx, args, call.queue, strings)
if not queues:
return [] # a binding with no readable queue binds nothing we can name
names, _ = strings.resolve(args, call.name, call.normalize)
+ if not names and call.declared is not None and call.queue is None:
+ names = call.declared.queues(ctx, args, call.name, strings)
out: list[Contract] = []
for name in names:
kind, key, unresolved = call.kind, routing_key, key_refused
diff --git a/packages/core/src/repowise/core/workspace/extractors/topic/rabbitmq.py b/packages/core/src/repowise/core/workspace/extractors/topic/rabbitmq.py
index 3c8428a69..6fc4c6272 100644
--- a/packages/core/src/repowise/core/workspace/extractors/topic/rabbitmq.py
+++ b/packages/core/src/repowise/core/workspace/extractors/topic/rabbitmq.py
@@ -1,4 +1,4 @@
-"""RabbitMQ publishers, consumers and queue bindings: Spring AMQP, amqplib, pika, php-amqplib.
+"""RabbitMQ publishers, consumers and queue bindings: Spring AMQP, amqplib, pika, php-amqplib, Go amqp.
A publish names an exchange and a routing key, a consume names a queue, and a
binding connects the two; see :mod:`repowise.core.workspace.matching.topic`.
@@ -8,6 +8,11 @@ share, so they are read only in a file that imports amqplib, whatever the
channel variable is called. ``sendToQueue`` and ``bindQueue`` are amqplib's
alone and are read anywhere, including on a channel handed in from another
module.
+
+Go (streadway/amqp, rabbitmq/amqp091-go) names a declared queue through the
+declaration's result (``q.Name``), read back from ``QueueDeclare``
+(:class:`.declared.QueueDeclaration`), as are amqplib's ``assertQueue`` and
+pika's ``queue_declare`` results.
"""
from __future__ import annotations
@@ -21,12 +26,17 @@ from repowise.core.workspace.contracts import (
)
from repowise.core.workspace.origins import ContractOrigin
-from ..langs import JAVA, JS_TS, PHP, PYTHON
+from ..langs import GO, JAVA, JS_TS, PHP, PYTHON
from ..strings import Arg
+from .declared import QueueDeclaration
from .dialect import TopicCall, TopicDialect
_AMQPLIB = ("amqplib", "amqp-connection-manager")
+_AMQPLIB_QUEUE = QueueDeclaration(call="assertQueue", member="queue")
+_PIKA_QUEUE = QueueDeclaration(call="queue_declare", member="method.queue")
_PHP_AMQPLIB = ("PhpAmqpLib",)
+_GO_AMQP = ("streadway/amqp", "rabbitmq/amqp091-go")
+_GO_QUEUE = QueueDeclaration(call="QueueDeclare", member="Name")
RABBITMQ = TopicDialect(
name="rabbitmq",
@@ -59,6 +69,7 @@ RABBITMQ = TopicDialect(
extensions=JS_TS,
name=Arg(pos=0),
kind=TOPIC_KIND_QUEUE,
+ declared=_AMQPLIB_QUEUE,
requires=_AMQPLIB,
),
TopicCall(
@@ -90,6 +101,7 @@ RABBITMQ = TopicDialect(
kind=TOPIC_KIND_BINDING,
routing_key=Arg(pos=2),
queue=Arg(pos=0),
+ declared=_AMQPLIB_QUEUE,
requires=("bindQueue",),
),
TopicCall(
@@ -99,6 +111,7 @@ RABBITMQ = TopicDialect(
extensions=PYTHON,
name=Arg(keys=("queue",), pos=0),
kind=TOPIC_KIND_QUEUE,
+ declared=_PIKA_QUEUE,
origin=ContractOrigin.NAME_HEURISTIC, # a variable named `channel`
requires=("basic_consume",),
),
@@ -124,6 +137,7 @@ RABBITMQ = TopicDialect(
origin=ContractOrigin.NAME_HEURISTIC, # a variable named `channel`
routing_key=Arg(keys=("routing_key",), pos=2),
queue=Arg(keys=("queue",), pos=0),
+ declared=_PIKA_QUEUE,
requires=("queue_bind",),
),
# php-amqplib: `basic_publish($msg, $exchange = '', $routing_key = '')`.
@@ -158,6 +172,62 @@ RABBITMQ = TopicDialect(
queue=Arg(keys=("queue",), pos=0),
requires=_PHP_AMQPLIB,
),
+ # Go: `Publish(exchange, key, mandatory, immediate, msg)`, the context
+ # first in `PublishWithContext` and `ConsumeWithContext`; `QueueBind(queue, key, exchange, ...)`.
+ TopicCall(
+ head=re.compile(r"\.\s*Consume\s*\("),
+ role="consumer",
+ label="Channel.Consume",
+ extensions=GO,
+ name=Arg(pos=0),
+ kind=TOPIC_KIND_QUEUE,
+ declared=_GO_QUEUE,
+ requires=_GO_AMQP,
+ ),
+ TopicCall(
+ head=re.compile(r"\.\s*ConsumeWithContext\s*\("),
+ role="consumer",
+ label="Channel.ConsumeWithContext",
+ extensions=GO,
+ name=Arg(pos=1),
+ kind=TOPIC_KIND_QUEUE,
+ declared=_GO_QUEUE,
+ requires=_GO_AMQP,
+ ),
+ TopicCall(
+ head=re.compile(r"\.\s*Publish\s*\("),
+ role="provider",
+ label="Channel.Publish",
+ extensions=GO,
+ name=Arg(pos=0),
+ kind=TOPIC_KIND_EXCHANGE,
+ routing_key=Arg(pos=1),
+ default_exchange=True,
+ requires=_GO_AMQP,
+ ),
+ TopicCall(
+ head=re.compile(r"\.\s*Publish(?:WithContext|WithDeferredConfirmWithContext)\s*\("),
+ role="provider",
+ label="Channel.PublishWithContext",
+ extensions=GO,
+ name=Arg(pos=1),
+ kind=TOPIC_KIND_EXCHANGE,
+ routing_key=Arg(pos=2),
+ default_exchange=True,
+ requires=_GO_AMQP,
+ ),
+ TopicCall(
+ head=re.compile(r"\.\s*QueueBind\s*\("),
+ role="consumer",
+ label="Channel.QueueBind",
+ extensions=GO,
+ name=Arg(pos=2),
+ kind=TOPIC_KIND_BINDING,
+ routing_key=Arg(pos=1),
+ queue=Arg(pos=0),
+ declared=_GO_QUEUE,
+ requires=_GO_AMQP,
+ ),
),
)
diff --git a/tests/unit/workspace/test_strings.py b/tests/unit/workspace/test_strings.py
index 0207d58ac..824c7599a 100644
--- a/tests/unit/workspace/test_strings.py
+++ b/tests/unit/workspace/test_strings.py
@@ -143,6 +143,47 @@ class TestPhpConstants:
assert resolve_string("static::QUEUE", PHP_SYNTAX, constants) == "jobs"
+class TestPythonConstants:
+ def test_an_upper_case_constant_may_be_unspaced(self) -> None:
+ constants = string_constants("class P:\n EXCHANGE='orders'\n", PYTHON_SYNTAX)
+ assert constants == {"EXCHANGE": "'orders'"}
+
+ def test_an_unspaced_keyword_argument_is_not_an_assignment(self) -> None:
+ src = "url = '/a'\nclient.get(\n url=str(x),\n TIMEOUT==1,\n)\n"
+ assert string_constants(src, PYTHON_SYNTAX) == {"url": "'/a'"}
+
+ def test_an_upper_case_keyword_argument_on_a_continuation_line_is_not_one(self) -> None:
+ src = "c.f(\n EXCHANGE='a',\n ROUTING='k'\n)\n"
+ assert string_constants(src, PYTHON_SYNTAX) == {}
+
+ def test_an_instance_attribute_does_not_fold_a_bare_name(self) -> None:
+ src = "def f(queue):\n pass\nclass C:\n def __init__(self):\n self.queue = 'jobs'\n"
+ constants = string_constants(src, PYTHON_SYNTAX)
+ assert resolve_string("queue", PYTHON_SYNTAX, constants) is None
+ assert resolve_string("self.queue", PYTHON_SYNTAX, constants) == "jobs"
+
+ def test_self_and_cls_read_a_class_attribute(self) -> None:
+ constants = string_constants("class P:\n QUEUE = 'jobs'\n", PYTHON_SYNTAX)
+ assert resolve_string("self.QUEUE", PYTHON_SYNTAX, constants) == "jobs"
+ assert resolve_string("cls.QUEUE", PYTHON_SYNTAX, constants) == "jobs"
+ assert resolve_string("f'{self.QUEUE}.dlq'", PYTHON_SYNTAX, constants) == "jobs.dlq"
+
+ def test_an_attribute_a_method_rebinds_is_not_folded(self) -> None:
+ src = "class P:\n QUEUE = 'jobs'\n def __init__(self, q):\n self.QUEUE = q\n"
+ constants = string_constants(src, PYTHON_SYNTAX)
+ assert resolve_string("self.QUEUE", PYTHON_SYNTAX, constants) is None
+ assert resolve_string("cls.QUEUE", PYTHON_SYNTAX, constants) is None
+
+ def test_an_instance_attribute_keeps_the_module_constant_it_copies(self) -> None:
+ src = "EXCHANGE = 'orders'\nclass P:\n def __init__(self):\n self.EXCHANGE = EXCHANGE\n"
+ constants = string_constants(src, PYTHON_SYNTAX)
+ assert resolve_string("EXCHANGE", PYTHON_SYNTAX, constants) == "orders"
+ assert resolve_string("self.EXCHANGE", PYTHON_SYNTAX, constants) is None
+
+ def test_self_is_not_a_member_prefix_in_js(self) -> None:
+ assert resolve_string("self.QUEUE", JS_SYNTAX, {"QUEUE": "'jobs'"}) is None
+
+
@pytest.mark.parametrize(
("suffix", "expected"),
[(".ts", JS_SYNTAX), (".py", PYTHON_SYNTAX), (".php", PHP_SYNTAX), (".sql", None)],
diff --git a/tests/unit/workspace/test_topic_dialects.py b/tests/unit/workspace/test_topic_dialects.py
index 0f5d615fe..13b057d91 100644
--- a/tests/unit/workspace/test_topic_dialects.py
+++ b/tests/unit/workspace/test_topic_dialects.py
@@ -268,6 +268,104 @@ class TestPhpAmqplib:
assert _extract(tmp_path, "X.php", "<?php\n$x->basic_publish($m, 'orders');\n") == []
+class TestGoAmqp:
+ _IMPORT = 'package main\n\nimport "github.com/streadway/amqp"\n\n'
+
+ def test_publish_consume_and_a_bind_on_the_declared_queue(self, tmp_path: Path) -> None:
+ src = self._IMPORT + (
+ 'q, err := ch.QueueDeclare("orders", true, false, false, false, nil)\n'
+ 'err = ch.QueueBind(q.Name, "orders", "robot-shop", false, nil)\n'
+ 'msgs, err := ch.Consume(q.Name, "", true, false, false, false, nil)\n'
+ 'ch.Publish("robot-shop", "order.created", false, false, msg)\n'
+ )
+ rows = {
+ (c.role, c.contract_id, c.meta["kind"]): c for c in _extract(tmp_path, "main.go", src)
+ }
+ assert set(rows) == {
+ ("consumer", "topic::robot-shop", "binding"),
+ ("consumer", "topic::orders", "queue"),
+ ("provider", "topic::robot-shop", "exchange"),
+ }
+ assert rows["consumer", "topic::robot-shop", "binding"].meta["queue"] == "orders"
+ provider = rows["provider", "topic::robot-shop", "exchange"]
+ assert provider.meta["routing_key"] == "order.created"
+
+ def test_with_context_calls_skip_the_context(self, tmp_path: Path) -> None:
+ src = 'import amqp "github.com/rabbitmq/amqp091-go"\n' + (
+ 'ch.PublishWithContext(ctx, "", "jobs", false, false, msg)\n'
+ 'ch.ConsumeWithContext(ctx, "jobs", "", true, false, false, false, nil)\n'
+ )
+ rows = {(c.role, c.contract_id, c.meta["kind"]) for c in _extract(tmp_path, "w.go", src)}
+ assert rows == {("provider", "topic::jobs", "queue"), ("consumer", "topic::jobs", "queue")}
+
+ @pytest.mark.parametrize(
+ "declare",
+ [
+ 'q, err := ch.QueueDeclare("", false, false, true, false, nil)\n', # server-named
+ 'q, err := ch.QueueDeclare("a", true, false, false, false, nil)\n'
+ 'q, err = ch.QueueDeclare("b", true, false, false, false, nil)\n',
+ "", # declared in another file
+ 'q, err := ch.QueueDeclare("a", true, false, false, false, nil)\n'
+ "q := other()\n", # bound to something else too
+ 'q, err := ch.QueueDeclare("a", true, false, false, false, nil)\n'
+ "func bind(ch *amqp.Channel, q amqp.Queue) {\n", # a parameter of that name
+ 'q, err := ch.QueueDeclare("a", true, false, false, false, nil)\n'
+ "for _, q := range queues {\n", # a loop variable of that name
+ ],
+ )
+ def test_an_unsettled_declared_queue_binds_nothing(self, tmp_path: Path, declare: str) -> None:
+ src = self._IMPORT + declare + 'ch.QueueBind(q.Name, "", "logs", false, nil)\n'
+ assert _extract(tmp_path, "main.go", src) == []
+
+ def test_nothing_without_the_library(self, tmp_path: Path) -> None:
+ src = 'package main\n\nch.Publish("orders", "k", false, false, msg)\nch.Consume("jobs")\n'
+ assert _extract(tmp_path, "main.go", src) == []
+
+
+class TestDeclaredQueues:
+ def test_amqplib_assert_queue_names_the_bound_and_consumed_queue(
+ self, tmp_path: Path
+ ) -> None:
+ src = _AMQP + (
+ "const q = await ch.assertQueue('audit');\n"
+ "await ch.bindQueue(q.queue, 'orders', 'order.*');\n"
+ "await ch.consume(q.queue, h);\n"
+ )
+ rows = {
+ (c.contract_id, c.meta["kind"], c.meta.get("queue"))
+ for c in _extract(tmp_path, "w.ts", src)
+ }
+ assert rows == {("topic::orders", "binding", "audit"), ("topic::audit", "queue", None)}
+
+ def test_pika_queue_declare_result_names_the_queue(self, tmp_path: Path) -> None:
+ src = (
+ "result = channel.queue_declare(queue='audit', durable=True)\n"
+ "channel.queue_bind(exchange='orders', queue=result.method.queue)\n"
+ )
+ c = _one(_extract(tmp_path, "w.py", src), "consumer")
+ assert (c.contract_id, c.meta["queue"]) == ("topic::orders", "audit")
+
+ def test_another_member_of_the_result_is_not_the_queue(self, tmp_path: Path) -> None:
+ src = _AMQP + "const q = await ch.assertQueue('audit');\nawait ch.consume(q.other, h);\n"
+ assert _extract(tmp_path, "w.ts", src) == []
+
+
+class TestPythonClassConstants:
+ def test_pika_publish_reads_unspaced_class_constants_through_self(
+ self, tmp_path: Path
+ ) -> None:
+ src = (
+ "import pika\n\nclass Publisher:\n"
+ " EXCHANGE='robot-shop'\n"
+ " ROUTING_KEY = 'orders'\n\n"
+ " def publish(self, msg):\n"
+ " self._channel.basic_publish(exchange=self.EXCHANGE,\n"
+ " routing_key=self.ROUTING_KEY, body=msg)\n"
+ )
+ c = _one(_extract(tmp_path, "rabbitmq.py", src), "provider")
+ assert (c.contract_id, c.meta["routing_key"]) == ("topic::robot-shop", "orders")
+
+
class TestNats:
def test_subscribe_and_publish(self, tmp_path: Path) -> None:
src = 'nc.Subscribe("events.created", h)\nnc.Publish("events.deleted", d)\n'