Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[Messenger] configure bus on transport #34247

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 1 commit 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
10 changes: 10 additions & 0 deletions UPGRADE-4.4.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,11 @@ FrameworkBundle
* Not tagging service route loaders with `routing.route_loader` has been deprecated.
* Overriding the methods `KernelTestCase::tearDown()` and `WebTestCase::tearDown()` without the `void` return-type is deprecated.
* Marked the `RouterDataCollector` class as `@final`.
* [BC BREAK] If you defined more than one bus, you must set the "bus" config option on the transport.
Messages received from this transport will be dispatched to this bus automatically. This replaces the
`--bus` option of `messenger:consume` command and the `BusNameStamp`.
* [BC Break] Removed `messenger.middleware.add_bus_name_stamp_middleware` service
* [BC Break] Removed `messenger.middleware.failed_message_processing_middleware` service

HttpClient
----------
Expand Down Expand Up @@ -179,6 +184,11 @@ Messenger
* [BC BREAK] Removed `StopWhenMessageCountIsExceededWorker` in favor of `StopWorkerOnMessageLimitListener`.
* [BC BREAK] Removed `StopWhenTimeLimitIsReachedWorker` in favor of `StopWorkerOnTimeLimitListener`.
* [BC BREAK] Removed `StopWhenRestartSignalIsReceived` in favor of `StopWorkerOnRestartSignalListener`.
* Deprecated `BusNameStamp`.
* [BC BREAK] Removed `AddBusNameStampMiddleware`.
* [BC BREAK] Removed `FailedMessageProcessingMiddleware`.
* [BC BREAK] Removed `--bus` option of `messenger:consume` command in favor of the "bus" config on the transport.
* [BC BREAK] Removed `$fallbackBus` argument from `RoutableMessageBus::__construct`.
* Marked the `MessengerDataCollector` class as `@final`.

Mime
Expand Down
6 changes: 6 additions & 0 deletions src/Symfony/Bundle/FrameworkBundle/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,13 @@ CHANGELOG
* Overriding the methods `KernelTestCase::tearDown()` and `WebTestCase::tearDown()` without the `void` return-type is deprecated.
* Added new `error_controller` configuration to handle system exceptions
* Added sort option for `translation:update` command.
* The `messenger.default_bus` config option is optional now even when having more than one bus to prevent unwanted autowiring.
* [BC BREAK] If you defined more than one bus, you must set the "bus" config option on the transport.
Messages received from this transport will be dispatched to this bus automatically. This replaces the
`--bus` option of `messenger:consume` command and the `BusNameStamp`.
* [BC Break] The `framework.messenger.routing.senders` config key is not deep merged anymore.
* [BC Break] Removed `messenger.middleware.add_bus_name_stamp_middleware` service
* [BC Break] Removed `messenger.middleware.failed_message_processing_middleware` service
* Added `secrets:*` commands and `%env(secret:...)%` processor to deal with secrets seamlessly.
* Made `framework.session.handler_id` accept a DSN
* Marked the `RouterDataCollector` class as `@final`.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1168,10 +1168,6 @@ private function addMessengerSection(ArrayNodeDefinition $rootNode)
->{!class_exists(FullStack::class) && interface_exists(MessageBusInterface::class) ? 'canBeDisabled' : 'canBeEnabled'}()
->fixXmlConfig('transport')
->fixXmlConfig('bus', 'buses')
->validate()
->ifTrue(function ($v) { return isset($v['buses']) && \count($v['buses']) > 1 && null === $v['default_bus']; })
->thenInvalid('You must specify the "default_bus" if you define more than one bus.')
->end()
->children()
->arrayNode('routing')
->normalizeKeys(false)
Expand Down Expand Up @@ -1247,7 +1243,14 @@ function ($a) {
->fixXmlConfig('option')
->children()
->scalarNode('dsn')->end()
->scalarNode('serializer')->defaultNull()->info('Service id of a custom serializer to use.')->end()
->scalarNode('serializer')
->defaultNull()
->info('Service id of a custom serializer to use.')
->end()
->scalarNode('bus')
->defaultNull()
->info('Bus name to dispatch received messages to. This only needs to be set if you have more than one bus.')
->end()
->arrayNode('options')
->normalizeKeys(false)
->defaultValue([])
Expand Down Expand Up @@ -1280,7 +1283,10 @@ function ($a) {
->defaultNull()
->info('Transport name to send failed messages to (after all retries have failed).')
->end()
->scalarNode('default_bus')->defaultNull()->end()
->scalarNode('default_bus')
->defaultNull()
->info('Bus name that will be used for autowiring MessageBusInterface. When there is only a single bus this happens automatically. With multiple buses you can set this option or use named autowiring based on the bus name or explicit wiring.')
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
->info('Bus name that will be used for autowiring MessageBusInterface. When there is only a single bus this happens automatically. With multiple buses you can set this option or use named autowiring based on the bus name or explicit wiring.')
->info('Bus name that will be used for autowiring MessageBusInterface. When there is only a single bus this happens automatically. With multiple buses, you can set this option or use named autowiring based on the bus name (or explicit wiring).')

Mostly, the last part of the sentence was confusing because it was "you can do X, or Y or Z" when really it's mean to read like "you can do X or Y (and Y is really 2 things). Hopefully this is clearer - it's minor regardless.

->end()
->arrayNode('buses')
->defaultValue(['messenger.bus.default' => ['default_middleware' => true, 'middleware' => []]])
->normalizeKeys(false)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1696,10 +1696,8 @@ private function registerMessengerConfiguration(array $config, ContainerBuilder

$defaultMiddleware = [
'before' => [
['id' => 'add_bus_name_stamp_middleware'],
['id' => 'reject_redelivered_message_middleware'],
['id' => 'dispatch_after_current_bus'],
['id' => 'failed_message_processing_middleware'],
],
'after' => [
['id' => 'send_message'],
Expand All @@ -1716,9 +1714,6 @@ private function registerMessengerConfiguration(array $config, ContainerBuilder
unset($defaultMiddleware['after'][1]['arguments']);
}

// argument to add_bus_name_stamp_middleware
$defaultMiddleware['before'][0]['arguments'] = [$busId];

$middleware = array_merge($defaultMiddleware['before'], $middleware, $defaultMiddleware['after']);
}

Expand Down Expand Up @@ -1763,7 +1758,7 @@ private function registerMessengerConfiguration(array $config, ContainerBuilder
$transportDefinition = (new Definition(TransportInterface::class))
->setFactory([new Reference('messenger.transport_factory'), 'createTransport'])
->setArguments([$transport['dsn'], $transport['options'] + ['transport_name' => $name], new Reference($serializerId)])
->addTag('messenger.receiver', ['alias' => $name])
->addTag('messenger.receiver', ['alias' => $name, 'bus' => $transport['bus']])
;
$container->setDefinition($transportId = 'messenger.transport.'.$name, $transportDefinition);
$senderAliases[$name] = $transportId;
Expand Down Expand Up @@ -1829,14 +1824,9 @@ private function registerMessengerConfiguration(array $config, ContainerBuilder
throw new LogicException(sprintf('Invalid Messenger configuration: the failure transport "%s" is not a valid transport or service id.', $config['failure_transport']));
}

$container->setParameter('messenger.failure_transport', $config['failure_transport']);
$container->getDefinition('messenger.failure.send_failed_message_to_failure_transport_listener')
->replaceArgument(0, $senderReferences[$config['failure_transport']]);
$container->getDefinition('console.command.messenger_failed_messages_retry')
->replaceArgument(0, $config['failure_transport']);
$container->getDefinition('console.command.messenger_failed_messages_show')
->replaceArgument(0, $config['failure_transport']);
$container->getDefinition('console.command.messenger_failed_messages_remove')
->replaceArgument(0, $config['failure_transport']);
} else {
$container->removeDefinition('messenger.failure.send_failed_message_to_failure_transport_listener');
$container->removeDefinition('console.command.messenger_failed_messages_retry');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@
</service>

<service id="console.command.messenger_consume_messages" class="Symfony\Component\Messenger\Command\ConsumeMessagesCommand">
<argument /> <!-- Routable message bus -->
<argument type="service" id="messenger.routable_message_bus" />
<argument type="service" id="messenger.receiver_locator" />
<argument type="service" id="event_dispatcher" />
<argument type="service" id="logger" on-invalid="null" />
Expand Down Expand Up @@ -115,7 +115,7 @@
</service>

<service id="console.command.messenger_failed_messages_retry" class="Symfony\Component\Messenger\Command\FailedMessagesRetryCommand">
<argument /> <!-- Receiver name -->
<argument>%messenger.failure_transport%</argument>
<argument /> <!-- Receiver -->
<argument type="service" id="messenger.routable_message_bus" />
<argument type="service" id="event_dispatcher" />
Expand All @@ -125,14 +125,14 @@
</service>

<service id="console.command.messenger_failed_messages_show" class="Symfony\Component\Messenger\Command\FailedMessagesShowCommand">
<argument /> <!-- Receiver name -->
<argument>%messenger.failure_transport%</argument>
<argument /> <!-- Receiver -->

<tag name="console.command" command="messenger:failed:show" />
</service>

<service id="console.command.messenger_failed_messages_remove" class="Symfony\Component\Messenger\Command\FailedMessagesRemoveCommand">
<argument /> <!-- Receiver name -->
<argument>%messenger.failure_transport%</argument>
<argument /> <!-- Receiver -->

<tag name="console.command" command="messenger:failed:remove" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,6 @@
</call>
</service>

<service id="messenger.middleware.add_bus_name_stamp_middleware" class="Symfony\Component\Messenger\Middleware\AddBusNameStampMiddleware" abstract="true" />

<service id="messenger.middleware.dispatch_after_current_bus" class="Symfony\Component\Messenger\Middleware\DispatchAfterCurrentBusMiddleware" />

<service id="messenger.middleware.validation" class="Symfony\Component\Messenger\Middleware\ValidationMiddleware">
Expand All @@ -50,8 +48,6 @@

<service id="messenger.middleware.reject_redelivered_message_middleware" class="Symfony\Component\Messenger\Middleware\RejectRedeliveredMessageMiddleware" />

<service id="messenger.middleware.failed_message_processing_middleware" class="Symfony\Component\Messenger\Middleware\FailedMessageProcessingMiddleware" />

<service id="messenger.middleware.traceable" class="Symfony\Component\Messenger\Middleware\TraceableMiddleware" abstract="true">
<argument type="service" id="debug.stopwatch" />
</service>
Expand Down Expand Up @@ -132,7 +128,6 @@
<!-- routable message bus -->
<service id="messenger.routable_message_bus" class="Symfony\Component\Messenger\RoutableMessageBus">
<argument /> <!-- Message bus locator -->
<argument type="service" id="messenger.default_bus" />
</service>
</services>
</container>
Original file line number Diff line number Diff line change
Expand Up @@ -250,27 +250,6 @@ public function provideValidLockConfigurationTests()
yield [['enabled' => false, 'resource' => [['name' => 'foo', 'value' => 'flock'], ['name' => 'foo', 'value' => 'semaphore'], ['name' => 'bar', 'value' => 'semaphore']]], ['enabled' => false, 'resources' => ['foo' => ['flock', 'semaphore'], 'bar' => ['semaphore']]]];
}

public function testItShowANiceMessageIfTwoMessengerBusesAreConfiguredButNoDefaultBus()
{
$expectedMessage = 'You must specify the "default_bus" if you define more than one bus.';
$this->expectException(InvalidConfigurationException::class);
$this->expectExceptionMessage($expectedMessage);
$processor = new Processor();
$configuration = new Configuration(true);

$processor->processConfiguration($configuration, [
'framework' => [
'messenger' => [
'default_bus' => null,
'buses' => [
'first_bus' => [],
'second_bus' => [],
],
],
],
]);
}

protected static function getBundleDefaultConfig()
{
return [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -679,7 +679,7 @@ public function testMessengerTransports()
$container = $this->createContainerFromFile('messenger_transports');
$this->assertTrue($container->hasDefinition('messenger.transport.default'));
$this->assertTrue($container->getDefinition('messenger.transport.default')->hasTag('messenger.receiver'));
$this->assertEquals([['alias' => 'default']], $container->getDefinition('messenger.transport.default')->getTag('messenger.receiver'));
$this->assertEquals([['alias' => 'default', 'bus' => null]], $container->getDefinition('messenger.transport.default')->getTag('messenger.receiver'));
$transportArguments = $container->getDefinition('messenger.transport.default')->getArguments();
$this->assertEquals(new Reference('messenger.default_serializer'), $transportArguments[2]);

Expand Down Expand Up @@ -737,20 +737,16 @@ public function testMessengerWithMultipleBuses()
$this->assertTrue($container->has('messenger.bus.commands'));
$this->assertSame([], $container->getDefinition('messenger.bus.commands')->getArgument(0));
$this->assertEquals([
['id' => 'add_bus_name_stamp_middleware', 'arguments' => ['messenger.bus.commands']],
['id' => 'reject_redelivered_message_middleware'],
['id' => 'dispatch_after_current_bus'],
['id' => 'failed_message_processing_middleware'],
['id' => 'send_message'],
['id' => 'handle_message'],
], $container->getParameter('messenger.bus.commands.middleware'));
$this->assertTrue($container->has('messenger.bus.events'));
$this->assertSame([], $container->getDefinition('messenger.bus.events')->getArgument(0));
$this->assertEquals([
['id' => 'add_bus_name_stamp_middleware', 'arguments' => ['messenger.bus.events']],
['id' => 'reject_redelivered_message_middleware'],
['id' => 'dispatch_after_current_bus'],
['id' => 'failed_message_processing_middleware'],
['id' => 'with_factory', 'arguments' => ['foo', true, ['bar' => 'baz']]],
['id' => 'send_message'],
['id' => 'handle_message'],
Expand Down
5 changes: 5 additions & 0 deletions src/Symfony/Component/Messenger/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@ CHANGELOG
* [BC BREAK] Removed `StopWhenMessageCountIsExceededWorker` in favor of `StopWorkerOnMessageLimitListener`.
* [BC BREAK] Removed `StopWhenTimeLimitIsReachedWorker` in favor of `StopWorkerOnTimeLimitListener`.
* [BC BREAK] Removed `StopWhenRestartSignalIsReceived` in favor of `StopWorkerOnRestartSignalListener`.
* Deprecated `BusNameStamp`.
* [BC BREAK] Removed `AddBusNameStampMiddleware`.
* [BC BREAK] Removed `FailedMessageProcessingMiddleware`.
* [BC BREAK] Removed `--bus` option of `messenger:consume` command in favor of the "bus" config on the transport.
* [BC BREAK] Removed `$fallbackBus` argument from `RoutableMessageBus::__construct`.
* The component is not marked as `@experimental` anymore.
* Marked the `MessengerDataCollector` class as `@final`.
* Added support for `DelayStamp` to the `redis` transport.
Expand Down
23 changes: 2 additions & 21 deletions src/Symfony/Component/Messenger/Command/ConsumeMessagesCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,18 +42,8 @@ class ConsumeMessagesCommand extends Command
private $receiverNames;
private $eventDispatcher;

/**
* @param RoutableMessageBus $routableBus
*/
public function __construct($routableBus, ContainerInterface $receiverLocator, EventDispatcherInterface $eventDispatcher, LoggerInterface $logger = null, array $receiverNames = [])
public function __construct(RoutableMessageBus $routableBus, ContainerInterface $receiverLocator, EventDispatcherInterface $eventDispatcher, LoggerInterface $logger = null, array $receiverNames = [])
{
if ($routableBus instanceof ContainerInterface) {
@trigger_error(sprintf('Passing a "%s" instance as first argument to "%s()" is deprecated since Symfony 4.4, pass a "%s" instance instead.', ContainerInterface::class, __METHOD__, RoutableMessageBus::class), E_USER_DEPRECATED);
$routableBus = new RoutableMessageBus($routableBus);
} elseif (!$routableBus instanceof RoutableMessageBus) {
throw new \TypeError(sprintf('The first argument must be an instance of "%s".', RoutableMessageBus::class));
}

$this->routableBus = $routableBus;
$this->receiverLocator = $receiverLocator;
$this->logger = $logger;
Expand All @@ -77,7 +67,6 @@ protected function configure(): void
new InputOption('memory-limit', 'm', InputOption::VALUE_REQUIRED, 'The memory limit the worker can consume'),
new InputOption('time-limit', 't', InputOption::VALUE_REQUIRED, 'The time limit in seconds the worker can run'),
new InputOption('sleep', null, InputOption::VALUE_REQUIRED, 'Seconds to sleep before asking for new messages after no messages were found', 1),
new InputOption('bus', 'b', InputOption::VALUE_REQUIRED, 'Name of the bus to which received messages should be dispatched (if not passed, bus is determined automatically)'),
])
->setDescription('Consumes messages')
->setHelp(<<<'EOF'
Expand All @@ -100,12 +89,6 @@ protected function configure(): void
Use the --time-limit option to stop the worker when the given time limit (in seconds) is reached:

<info>php %command.full_name% <receiver-name> --time-limit=3600</info>

Use the --bus option to specify the message bus to dispatch received messages
to instead of trying to determine it automatically. This is required if the
messages didn't originate from Messenger:

<info>php %command.full_name% <receiver-name> --bus=event_bus</info>
EOF
)
;
Expand Down Expand Up @@ -195,9 +178,7 @@ protected function execute(InputInterface $input, OutputInterface $output)
$io->comment('Re-run the command with a -vv option to see logs about consumed messages.');
}

$bus = $input->getOption('bus') ? $this->routableBus->getMessageBus($input->getOption('bus')) : $this->routableBus;

$worker = new Worker($receivers, $bus, $this->eventDispatcher, $this->logger);
$worker = new Worker($receivers, $this->routableBus, $this->eventDispatcher, $this->logger);
$worker->run([
'sleep' => $input->getOption('sleep') * 1000000,
]);
Expand Down
Loading