Skip to content

[Messenger] Automatically route messages when from_transport tag is set #35111

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 8 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -1047,6 +1047,10 @@ private function addMessengerSection(ArrayNodeDefinition $rootNode)
->then(static function (array $v): void { throw new InvalidConfigurationException(sprintf('The specified default bus "%s" is not configured. Available buses are "%s".', $v['default_bus'], implode('", "', array_keys($v['buses'])))); })
->end()
->children()
->booleanNode('auto_routing')
->info('Automatically create routing for handlers that specify "from_transport" via tag attribute or MessageSubscriberInterface.')
->defaultFalse()
->end()
->arrayNode('routing')
->normalizeKeys(false)
->useAttributeAsKey('message_class')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1568,6 +1568,8 @@ private function registerMessengerConfiguration(array $config, ContainerBuilder

$loader->load('messenger.xml');

$container->setParameter('messenger.auto_routing', $config['auto_routing']);

if (null === $config['default_bus'] && 1 === \count($config['buses'])) {
$config['default_bus'] = key($config['buses']);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd">

<parameters>
<parameter id="messenger.auto_routing">false</parameter>
</parameters>

<services>
<defaults public="false" />

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -480,6 +480,7 @@ class_exists(SemaphoreStore::class) && SemaphoreStore::isSupported() ? 'semaphor
],
'default_bus' => null,
'buses' => ['messenger.bus.default' => ['default_middleware' => true, 'middleware' => []]],
'auto_routing' => false,
],
'disallow_search_engine_index' => true,
'http_client' => [
Expand Down
4 changes: 3 additions & 1 deletion src/Symfony/Component/Messenger/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ CHANGELOG
-----

* The `LoggingMiddleware` class has been removed, pass a logger to `SendMessageMiddleware` instead.
* made `SendersLocator` require a `ContainerInterface` as 2nd argument
* Made `SendersLocator` require a `ContainerInterface` as 2nd argument
* Added `auto_routing` option to configuration. This will automatically create routing for messages
to the given transport that the handler defines via the `from_transport` attribute.

4.4.0
-----
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,10 +63,16 @@ public function process(ContainerBuilder $container)
if ($container->hasDefinition('messenger.receiver_locator')) {
$this->registerReceivers($container, $busIds);
}
$this->registerHandlers($container, $busIds);

$autoRouting = false;
if ($container->hasParameter('messenger.auto_routing')) {
$autoRouting = $container->getParameter('messenger.auto_routing');
}

$this->registerHandlers($container, $busIds, $autoRouting);
}

private function registerHandlers(ContainerBuilder $container, array $busIds)
private function registerHandlers(ContainerBuilder $container, array $busIds, bool $autoRouting)
{
$definitions = [];
$handlersByBusAndMessage = [];
Expand Down Expand Up @@ -165,20 +171,42 @@ private function registerHandlers(ContainerBuilder $container, array $busIds)
}
}

$messageToSendersMapping = [];
if ($container->hasDefinition('messenger.receiver_locator')) {
$messageToSendersMapping = $container->getDefinition('messenger.senders_locator')
->getArgument(0);
}

$handlersLocatorMappingByBus = [];
foreach ($handlersByBusAndMessage as $bus => $handlersByMessage) {
foreach ($handlersByMessage as $message => $handlers) {
$handlerDescriptors = [];
foreach ($handlers as $handler) {
$definitions[$definitionId = '.messenger.handler_descriptor.'.ContainerBuilder::hash($bus.':'.$message.':'.$handler[0])] = (new Definition(HandlerDescriptor::class))->setArguments([new Reference($handler[0]), $handler[1]]);
$handlerDescriptors[] = new Reference($definitionId);

if ($autoRouting && isset($handler[1]['from_transport'])) {
if (!isset($messageToSendersMapping[$message])) {
$messageToSendersMapping[$message] = [];
}

if (!\in_array($handler[1]['from_transport'], $messageToSendersMapping[$message])) {
$messageToSendersMapping[$message][] = $handler[1]['from_transport'];
}
}
}

$handlersLocatorMappingByBus[$bus][$message] = new IteratorArgument($handlerDescriptors);
}
}
$container->addDefinitions($definitions);

if ($container->hasDefinition('messenger.receiver_locator')) {
$container->getDefinition('messenger.senders_locator')
->replaceArgument(0, $messageToSendersMapping)
;
}

foreach ($busIds as $bus) {
$container->register($locatorId = $bus.'.messenger.handlers_locator', HandlersLocator::class)
->setArgument(0, $handlersLocatorMappingByBus[$bus] ?? [])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
use Symfony\Component\Messenger\Tests\Fixtures\SecondMessage;
use Symfony\Component\Messenger\Transport\AmqpExt\AmqpReceiver;
use Symfony\Component\Messenger\Transport\Receiver\ReceiverInterface;
use Symfony\Component\Messenger\Transport\Sender\SendersLocator;

class MessengerPassTest extends TestCase
{
Expand Down Expand Up @@ -602,10 +603,58 @@ public function testItRegistersTheDebugCommand()
], $container->getDefinition('console.command.messenger_debug')->getArgument(0));
}

public function testAutomaticallyRouteMessagesWhenFromTransportTagIsSet()
{
$container = $this->getContainerBuilder($busId = 'message_bus');
$container->setParameter('messenger.auto_routing', true);
$container
->register(DummyHandler::class, DummyHandler::class)
->addTag('messenger.message_handler', ['from_transport' => 'async'])
;
$container
->register(SecondDummyHandler::class, SecondDummyHandler::class)
->addTag('messenger.message_handler', ['from_transport' => 'sync'])
;

(new MessengerPass())->process($container);

$messageToSendersMapping = $container->getDefinition('messenger.senders_locator')->getArgument(0);
$this->assertCount(1, $messageToSendersMapping);
$this->assertSame([DummyMessage::class => ['async', 'sync']], $messageToSendersMapping);
}

public function testAutomaticallyRouteMessagesWhenFromTransportOptionIsSet()
{
$container = $this->getContainerBuilder('message_bus');
$container->setParameter('messenger.auto_routing', true);
$container->register('command_bus', MessageBusInterface::class)->addTag('messenger.bus')->setArgument(0, []);

$container
->register(HandlerFromTransportWithAutoRoute::class, HandlerFromTransportWithAutoRoute::class)
->addTag('messenger.message_handler');

(new MessengerPass())->process($container);

$mapping = $container->getDefinition('message_bus.messenger.handlers_locator')->getArgument(0);

$this->assertHandlerDescriptor(
$container,
$mapping,
DummyMessage::class,
[[HandlerFromTransportWithAutoRoute::class, 'exec']],
[['from_transport' => 'async']]
);

$messageToSendersMapping = $container->getDefinition('messenger.senders_locator')->getArgument(0);
$this->assertCount(1, $messageToSendersMapping);
$this->assertSame([DummyMessage::class => ['async']], $messageToSendersMapping);
}

private function getContainerBuilder(string $busId = 'message_bus'): ContainerBuilder
{
$container = new ContainerBuilder();
$container->setParameter('kernel.debug', true);
$container->setParameter('messenger.auto_routing', false);

$container->register($busId, MessageBusInterface::class)->addTag('messenger.bus')->setArgument(0, []);
if ('message_bus' !== $busId) {
Expand All @@ -616,6 +665,10 @@ private function getContainerBuilder(string $busId = 'message_bus'): ContainerBu
->addArgument(new Reference('service_container'))
;

$container->register('messenger.senders_locator', SendersLocator::class)
->addArgument([])
;

return $container;
}

Expand Down Expand Up @@ -657,6 +710,13 @@ public function __invoke(DummyMessage $message): void
}
}

class SecondDummyHandler
{
public function __invoke(DummyMessage $message): void
{
}
}

class DummyReceiver implements ReceiverInterface
{
public function get(): iterable
Expand Down Expand Up @@ -847,3 +907,15 @@ public function handle(Envelope $message, StackInterface $stack): Envelope
return $stack->next()->handle($message, $stack);
}
}

class HandlerFromTransportWithAutoRoute implements MessageSubscriberInterface
{
public static function getHandledMessages(): iterable
{
yield DummyMessage::class => ['method' => 'exec', 'from_transport' => 'async'];
}

public function exec(DummyMessage $message)
{
}
}