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): read JMS destinations as topic contracts (JmsTemplate, @JmsListener) (#4557)

Raghav Chamadiyaa2948c60d571
diff --git a/docs/architecture/language-support.md b/docs/architecture/language-support.md
index 7757c2528..6e9083fe8 100644
--- a/docs/architecture/language-support.md
+++ b/docs/architecture/language-support.md
@@ -1316,6 +1316,7 @@ 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 |
| **Topic (C# integration events)** | `IntegrationEvent` subclasses constructed and passed to a publish call, keyed by short type name | `AddSubscription<T, TH>`, `Subscribe<T, TH>`, `IIntegrationEventHandler<T>` |
+| **Topic (JMS)** | Spring `JmsTemplate` / `JmsMessagingTemplate` sends with a destination argument | `@JmsListener(destination)`, template `receive` / `receiveAndConvert`, listener containers' `setDestinationName` |
RabbitMQ topics are also read from Go (streadway/amqp, amqp091-go), including
a queue named through its declaration's result (`q.Name`).
diff --git a/docs/scale/WORKSPACES.md b/docs/scale/WORKSPACES.md
index 46d2b91f2..86fa14389 100644
--- a/docs/scale/WORKSPACES.md
+++ b/docs/scale/WORKSPACES.md
@@ -171,6 +171,7 @@ Scans source files for HTTP routes, gRPC services, database tables, message topi
| Topics | Kafka (Spring `KafkaTemplate` under any name, kafka-clients `ProducerRecord`, kafkajs, kafka-python, aiokafka, confluent-kafka for Python and .NET, Go sarama, segmentio/kafka-go and franz-go), RabbitMQ (Spring AMQP, amqplib, pika, php-amqplib), NATS, Redis pub/sub (ioredis/node-redis, redis-py, Laravel `Redis::publish`), BullMQ / Bull (`new Queue`, `@InjectQueue`, flows), SQS and SNS (AWS SDK v2/v3, boto3), NestJS `ClientProxy.emit`/`send`, MassTransit `Publish`/`Send`/`IRequestClient` (C#, VB.NET), Laravel job dispatch (`X::dispatch()->onQueue()`, `dispatch()`, `Queue::push*`, scheduled jobs) | The corresponding consumers (`new Worker`, `@Processor`, `ReceiveMessageCommand`, sqs-consumer, `subscribe`/`psubscribe`, `@EventPattern`/`@MessagePattern`, Laravel `ShouldQueue` classes on the queues they run on, MassTransit `IConsumer<T>`, open-generic consumers and saga events), plus RabbitMQ queue bindings (`bindQueue`, `queue_bind`) |
| Socket / WebSocket | SignalR `MapHub<T>("/path")`, FastAPI `@app.websocket("/path")`, `ws` `WebSocketServer({ path })`, NestJS `@WebSocketGateway`; events: socket.io `emit` (server and client), Laravel broadcast events (`broadcastOn` / `broadcastAs`), `Broadcast::on`, Pusher `trigger` | ClientWebSocket `ConnectAsync`, SignalR `HubConnectionBuilder.WithUrl`, NativeWebSocket and WebSocketSharp `new WebSocket(...)`, browser/Node `new WebSocket(url)`; events: socket.io `on` / `@SubscribeMessage`, Laravel Echo `listen` and `useEcho`, pusher-js `bind` |
| Topics: C# integration events | `new T(...)` of an `IntegrationEvent` subclass the repo declares, reaching `PublishAsync` / `Publish` or a repo method taking an `IntegrationEvent`; the id is the short type name, which the event bus routes by | `AddSubscription<T, TH>()`, `Subscribe<T, TH>()` on a declared event, and `IIntegrationEventHandler<T>` classes for events no registration subscribes |
+| Topics: JMS | Spring `JmsTemplate` / `JmsMessagingTemplate` `convertAndSend` / `send` / `sendAndReceive` / `convertSendAndReceive` on a receiver named for JMS (`jmsTemplate`, `orderJmsTemplate`, `getJmsTemplate()`) with a destination argument; ActiveMQ and IBM MQ `queue://` names read as the bare queue | `@JmsListener(destination = ...)`, `receive` / `receiveAndConvert`, `DefaultMessageListenerContainer.setDestinationName` |
Socket detection is toggled by `detect_socket` in the `contracts:` block below.
A topic, queue or route name is resolved when it is a literal or a constant the
diff --git a/packages/core/src/repowise/core/workspace/extractors/topic/__init__.py b/packages/core/src/repowise/core/workspace/extractors/topic/__init__.py
index f0fb37b2d..05f3b12bd 100644
--- a/packages/core/src/repowise/core/workspace/extractors/topic/__init__.py
+++ b/packages/core/src/repowise/core/workspace/extractors/topic/__init__.py
@@ -13,6 +13,7 @@ from .aws import SNS, SQS
from .bullmq import BULLMQ
from .csharp_events import CSHARP_EVENTS
from .dialect import topic_identity
+from .jms import JMS
from .kafka import KAFKA
from .laravel import LARAVEL_QUEUES
from .nats import NATS
@@ -34,6 +35,7 @@ DIALECTS: tuple[ContractDialect, ...] = (
NESTJS,
LARAVEL_QUEUES,
CSHARP_EVENTS,
+ JMS,
)
diff --git a/packages/core/src/repowise/core/workspace/extractors/topic/jms.py b/packages/core/src/repowise/core/workspace/extractors/topic/jms.py
new file mode 100644
index 000000000..1807f5061
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/extractors/topic/jms.py
@@ -0,0 +1,116 @@
+"""JMS producers and consumers: Spring `JmsTemplate`, `@JmsListener` and listener containers.
+
+A destination is a queue unless the connection factory says otherwise
+(Spring's ``pub-sub-domain`` defaults to false), so every row is a queue.
+ActiveMQ and IBM MQ also take a URI-style name: ``queue://orders`` and
+``queue:///ORDERS`` are the queue ``orders`` / ``ORDERS``, so the prefix is
+dropped. A ``topic://`` name is a different destination from the bare name
+and is kept as spelled, so it meets only the same spelling.
+
+A template is read on a receiver whose name says JMS (``jmsTemplate``,
+``topicJmsTemplate``, ``getJmsTemplate()``), in a file that names the type.
+A template under any other name needs the file's declared receivers (a
+:class:`.dialect.ReceiverCall` row, as Kafka's); this dialect declares none
+yet, so those calls are missed rather than guessed from the bare ``send`` verb.
+
+``@JmsListener`` names its destination only by the ``destination`` key;
+``containerFactory``, ``subscription`` and ``selector`` are not destinations.
+A ``${...}`` property placeholder does not resolve inside the file and is
+refused.
+"""
+
+from __future__ import annotations
+
+import re
+
+from repowise.core.workspace.contracts import TOPIC_KIND_QUEUE
+
+from ..langs import JAVA, KOTLIN
+from ..strings import Arg
+from .dialect import TopicCall, TopicDialect
+
+_JVM = JAVA | KOTLIN
+_TEMPLATES = ("JmsTemplate", "JmsMessagingTemplate", "JmsOperations")
+_FIRST = Arg(pos=0)
+
+# A receiver whose name ends in `jmsTemplate` / `JmsMessagingTemplate` /
+# `jmsOperations` (any prefix), or the `getJmsTemplate()` of JmsGatewaySupport.
+_RECEIVER = r"(?:\b\w*[jJ]ms(?:Messaging)?(?:Template|Operations)|\bgetJmsTemplate\s*\(\s*\))"
+
+# The one-argument send forms go to the template's default destination, and
+# their argument is the payload: `convertAndSend("hello")` names no queue. A
+# send is read only when its first argument (a literal or a dotted name) is
+# followed by a second.
+_FIRST_THEN = r"\s*(?:\"(?:[^\"\\]|\\.)*\"|[\w$.]+)\s*,"
+_HAS_SECOND_ARG = rf"(?={_FIRST_THEN})"
+# `convertAndSend(payload, m -> ...)` posts the payload to the default
+# destination through a post-processor lambda, so a lambda second argument
+# refuses the convert forms. A literal payload followed by a named
+# post-processor or header map still reads as a destination: the call shape
+# alone cannot tell those overloads apart.
+_DESTINATION_THEN_PAYLOAD = rf"(?={_FIRST_THEN}(?!\s*(?:[\w$]+|\([^()]*\))\s*->))"
+
+
+def _queue_name(text: str) -> str | None:
+ """``queue://orders`` and IBM MQ's ``queue:///ORDERS?targetClient=1`` name the queue."""
+ if not text.startswith("queue://"):
+ return text
+ return text[len("queue://") :].lstrip("/").partition("?")[0] or None
+
+
+def _template(verbs: str, role: str, label: str, guard: str = "") -> TopicCall:
+ return TopicCall(
+ head=re.compile(rf"{_RECEIVER}\s*\.\s*(?:{verbs})\s*\({guard}"),
+ role=role,
+ label=label,
+ extensions=_JVM,
+ name=_FIRST,
+ kind=TOPIC_KIND_QUEUE,
+ requires=_TEMPLATES,
+ normalize=_queue_name,
+ )
+
+
+JMS = TopicDialect(
+ name="jms",
+ calls=(
+ TopicCall(
+ head=re.compile(r"@JmsListener\s*\("),
+ role="consumer",
+ label="@JmsListener",
+ extensions=_JVM,
+ name=Arg(keys=("destination",)),
+ kind=TOPIC_KIND_QUEUE,
+ requires=("@JmsListener",),
+ normalize=_queue_name,
+ ),
+ # A listener container wired in code (`DefaultMessageListenerContainer`).
+ TopicCall(
+ head=re.compile(r"\.\s*setDestinationName\s*\("),
+ role="consumer",
+ label="setDestinationName",
+ extensions=_JVM,
+ name=_FIRST,
+ kind=TOPIC_KIND_QUEUE,
+ requires=("MessageListenerContainer",),
+ normalize=_queue_name,
+ ),
+ _template(
+ r"convertAndSend|convertSendAndReceive",
+ "provider",
+ "jmsTemplate.convertAndSend",
+ _DESTINATION_THEN_PAYLOAD,
+ ),
+ # `send(destination, session -> ...)`: the lambda is the message creator.
+ _template(r"send|sendAndReceive", "provider", "jmsTemplate.send", _HAS_SECOND_ARG),
+ # `receive()` with no argument reads the default destination and is
+ # skipped; `receiveSelected("sel")` names a selector, not a queue.
+ _template(
+ r"receive|receiveAndConvert",
+ "consumer",
+ "jmsTemplate.receive",
+ ),
+ ),
+)
+
+__all__ = ["JMS"]
diff --git a/tests/unit/workspace/test_jms_topics.py b/tests/unit/workspace/test_jms_topics.py
new file mode 100644
index 000000000..8f3edac28
--- /dev/null
+++ b/tests/unit/workspace/test_jms_topics.py
@@ -0,0 +1,153 @@
+"""JMS topic dialect: Spring JmsTemplate sends and receives, @JmsListener, listener containers."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from repowise.core.workspace.extractors.topic import TopicExtractor
+from repowise.core.workspace.matching import match_contracts
+from repowise.core.workspace.origins import ContractOrigin
+
+_IMPORT = "import org.springframework.jms.core.JmsTemplate;\n"
+
+
+def _extract(root: Path, rel: str, content: str, alias: str = "svc"):
+ path = root / rel
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(content, encoding="utf-8")
+ return TopicExtractor().extract(root, alias)
+
+
+def _ids(rows, role: str) -> list[str]:
+ return sorted(c.contract_id for c in rows if c.role == role)
+
+
+def test_jms_listener_reads_destination_not_container_factory(tmp_path: Path) -> None:
+ src = '@JmsListener(destination = "order", containerFactory = "jsaFactory")\nvoid f() {}'
+ [c] = _extract(tmp_path, "OrderReceiver.java", src)
+ assert (c.contract_id, c.role) == ("topic::order", "consumer")
+ assert c.meta == {"topic": "order", "broker": "jms", "kind": "queue"}
+ assert c.origin == ContractOrigin.CLIENT_CALL
+
+
+def test_jms_listener_without_destination_and_placeholder_are_refused(tmp_path: Path) -> None:
+ src = (
+ '@JmsListener(containerFactory = "jsaFactory", subscription = "sub")\nvoid a() {}\n'
+ '@JmsListener(destination = "${app.queue}")\nvoid b() {}\n'
+ )
+ assert _extract(tmp_path, "L.java", src) == []
+
+
+def test_template_sends_and_receives_under_jms_receiver_names(tmp_path: Path) -> None:
+ src = _IMPORT + (
+ 'static final String Q = "orders";\n'
+ "void f() {\n"
+ " jmsTemplate.convertAndSend(Q, order);\n"
+ ' this.topicJmsTemplate.send("audit", s -> s.createTextMessage(x));\n'
+ ' getJmsTemplate().convertAndSend("billing", b);\n'
+ ' jmsMessagingTemplate.convertAndSend("ledger", l);\n'
+ ' Object r = jmsTemplate.receiveAndConvert("replies");\n'
+ "}\n"
+ )
+ rows = _extract(tmp_path, "Sender.java", src)
+ assert _ids(rows, "provider") == [
+ "topic::audit",
+ "topic::billing",
+ "topic::ledger",
+ "topic::orders",
+ ]
+ assert _ids(rows, "consumer") == ["topic::replies"]
+
+
+def test_one_argument_send_is_the_default_destination(tmp_path: Path) -> None:
+ src = _IMPORT + (
+ 'jmsTemplate.convertAndSend("hello, world");\n'
+ "jmsTemplate.send(s -> s.createTextMessage(x));\n"
+ "jmsTemplate.receive();\n"
+ 'jmsTemplate.receiveSelected("type = \'a\'");\n'
+ 'jmsTemplate.convertAndSend("hello", m -> { m.setJMSType("t"); return m; });\n'
+ 'jmsTemplate.convertAndSend("hello", (m) -> m);\n'
+ )
+ assert _extract(tmp_path, "Sender.java", src) == []
+
+
+def test_request_reply_verbs_and_kotlin_templates(tmp_path: Path) -> None:
+ src = _IMPORT + (
+ 'jmsTemplate.sendAndReceive("quotes", s -> s.createTextMessage(x));\n'
+ 'jmsMessagingTemplate.convertSendAndReceive("prices", req, Price.class);\n'
+ )
+ assert _ids(_extract(tmp_path, "Q.java", src), "provider") == [
+ "topic::prices",
+ "topic::quotes",
+ ]
+ kt = _IMPORT + 'jmsTemplate.convertAndSend("orders", order)\n'
+ assert _ids(_extract(tmp_path / "kt", "S.kt", kt), "provider") == ["topic::orders"]
+
+
+def test_lookalike_templates_are_not_jms(tmp_path: Path) -> None:
+ # A STOMP messaging template and a template under a name that does not say JMS.
+ src = _IMPORT + (
+ 'messagingTemplate.convertAndSend("/topic/greetings", g);\n'
+ 'template.convertAndSend("orders", o);\n'
+ '// jmsTemplate.convertAndSend("commented", o);\n'
+ )
+ assert _extract(tmp_path, "Sender.java", src) == []
+
+
+def test_without_the_type_in_the_file_nothing_is_read(tmp_path: Path) -> None:
+ assert _extract(tmp_path, "S.java", 'jmsTemplate.convertAndSend("orders", o);') == []
+
+
+def test_listener_container_destination_name(tmp_path: Path) -> None:
+ src = (
+ "DefaultMessageListenerContainer c = new DefaultMessageListenerContainer();\n"
+ 'c.setDestinationName("personneQueue");\n'
+ 'template.setDefaultDestinationName("other");\n'
+ )
+ [c] = _extract(tmp_path, "JMSConfiguration.java", src)
+ assert (c.contract_id, c.role) == ("topic::personnequeue", "consumer")
+
+
+def test_uri_style_queue_names_drop_the_prefix(tmp_path: Path) -> None:
+ src = _IMPORT + (
+ 'jmsTemplate.convertAndSend("queue://orders", o);\n'
+ 'jmsTemplate.convertAndSend("queue:///DEV.QUEUE.1?targetClient=1", o);\n'
+ 'jmsTemplate.convertAndSend("topic://prices", p);\n'
+ )
+ assert _ids(_extract(tmp_path, "S.java", src), "provider") == [
+ "topic::dev.queue.1",
+ "topic::orders",
+ "topic::topic://prices",
+ ]
+
+
+def test_kotlin_listener(tmp_path: Path) -> None:
+ [c] = _extract(tmp_path, "L.kt", '@JmsListener(destination = "order")\nfun f(o: Order) {}')
+ assert c.contract_id == "topic::order"
+
+
+def test_sender_links_to_listener_in_another_repo(tmp_path: Path) -> None:
+ cart = _extract(
+ tmp_path / "cart",
+ "OrderSender.java",
+ _IMPORT + 'jmsTemplate.convertAndSend("order", order);',
+ "cart",
+ )
+ order = _extract(
+ tmp_path / "order",
+ "OrderReceiver.java",
+ '@JmsListener(destination = "queue://order")\nvoid receive(OrderDto o) {}',
+ "order",
+ )
+ links = [lk for lk in match_contracts(cart + order) if lk.contract_type == "topic"]
+ assert [(lk.provider_repo, lk.consumer_repo, lk.contract_id) for lk in links] == [
+ ("cart", "order", "topic::order")
+ ]
+
+
+def test_a_jms_queue_does_not_meet_a_kafka_topic_of_the_same_name(tmp_path: Path) -> None:
+ jms = _extract(
+ tmp_path / "a", "S.java", _IMPORT + 'jmsTemplate.convertAndSend("orders", o);', "a"
+ )
+ kafka = _extract(tmp_path / "b", "C.java", '@KafkaListener(topics = "orders")\nvoid f() {}', "b")
+ assert [lk for lk in match_contracts(jms + kafka) if lk.contract_type == "topic"] == []