Skip to content
Merged
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
1 change: 1 addition & 0 deletions src/Symfony/Component/Messenger/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ CHANGELOG
7.4
---

* Add `--exclude-receivers` option to the `messenger:consume command`
* Allow any `ServiceResetterInterface` implementation in `ResetServicesListener`

7.3
Expand Down
42 changes: 34 additions & 8 deletions src/Symfony/Component/Messenger/Command/ConsumeMessagesCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ protected function configure(): void
new InputOption('queues', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Limit receivers to only consume from the specified queues'),
new InputOption('no-reset', null, InputOption::VALUE_NONE, 'Do not reset container services after each message'),
new InputOption('all', null, InputOption::VALUE_NONE, 'Consume messages from all receivers'),
new InputOption('exclude-receivers', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Exclude specific receivers/transports from consumption (can only be used with --all)'),
new InputOption('keepalive', null, InputOption::VALUE_OPTIONAL, 'Whether to use the transport\'s keepalive mechanism if implemented', self::DEFAULT_KEEPALIVE_INTERVAL),
])
->setHelp(<<<'EOF'
Expand All @@ -88,40 +89,44 @@ protected function configure(): void

<info>php %command.full_name% receiver1 receiver2</info>

Use the --limit option to limit the number of messages received:
Use the <info>--limit</info> option to limit the number of messages received:

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

Use the --failure-limit option to stop the worker when the given number of failed messages is reached:
Use the <info>--failure-limit</info> option to stop the worker when the given number of failed messages is reached:

<info>php %command.full_name% <receiver-name> --failure-limit=2</info>

Use the --memory-limit option to stop the worker if it exceeds a given memory usage limit. You can use shorthand byte values [K, M or G]:
Use the <info>--memory-limit</info> option to stop the worker if it exceeds a given memory usage limit. You can use shorthand byte values [K, M or G]:

<info>php %command.full_name% <receiver-name> --memory-limit=128M</info>

Use the --time-limit option to stop the worker when the given time limit (in seconds) is reached.
Use the <info>--time-limit</info> option to stop the worker when the given time limit (in seconds) is reached.
If a message is being handled, the worker will stop after the processing is finished:

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

Use the --bus option to specify the message bus to dispatch received messages
Use the <info>--bus</info> 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>

Use the --queues option to limit a receiver to only certain queues (only supported by some receivers):
Use the <info>--queues</info> option to limit a receiver to only certain queues (only supported by some receivers):

<info>php %command.full_name% <receiver-name> --queues=fasttrack</info>

Use the --no-reset option to prevent services resetting after each message (may lead to leaking services' state between messages):
Use the <info>--no-reset</info> option to prevent services resetting after each message (may lead to leaking services' state between messages):

<info>php %command.full_name% <receiver-name> --no-reset</info>

Use the --all option to consume from all receivers:
Use the <info>--all</info> option to consume from all receivers:

<info>php %command.full_name% --all</info>

Use the <info>--exclude-receivers</info> option to exclude specific receivers/transports from consumption (can only be used with <info>--all</info>):

<info>php %command.full_name% --all --exclude-receivers=<receiver-name></info>
EOF
)
;
Expand All @@ -132,6 +137,10 @@ protected function initialize(InputInterface $input, OutputInterface $output): v
if ($input->hasParameterOption('--keepalive')) {
$this->getApplication()->setAlarmInterval((int) ($input->getOption('keepalive') ?? self::DEFAULT_KEEPALIVE_INTERVAL));
}

if ($input->getOption('exclude-receivers') && !$input->getOption('all')) {
throw new InvalidOptionException('The "--exclude-receivers" option can only be used with the "--all" option.');
}
}

protected function interact(InputInterface $input, OutputInterface $output): void
Expand Down Expand Up @@ -169,9 +178,22 @@ protected function interact(InputInterface $input, OutputInterface $output): voi

protected function execute(InputInterface $input, OutputInterface $output): int
{
if ($input->getOption('exclude-receivers') && !$input->getOption('all')) {
throw new InvalidOptionException('The "--exclude-receivers" option can only be used with the "--all" option.');
}

$receivers = [];
$rateLimiters = [];
$receiverNames = $input->getOption('all') ? $this->receiverNames : $input->getArgument('receivers');

if ($input->getOption('all') && $excludedTransports = $input->getOption('exclude-receivers')) {
$receiverNames = array_diff($receiverNames, $excludedTransports);

if (!$receiverNames) {
throw new RuntimeException('All transports/receivers have been excluded, please specify at least one to consume from.');
}
}

foreach ($receiverNames as $receiverName) {
if (!$this->receiverLocator->has($receiverName)) {
$message = \sprintf('The receiver "%s" does not exist.', $receiverName);
Expand Down Expand Up @@ -276,6 +298,10 @@ public function complete(CompletionInput $input, CompletionSuggestions $suggesti
if ($input->mustSuggestOptionValuesFor('bus')) {
$suggestions->suggestValues($this->busIds);
}

if ($input->mustSuggestOptionValuesFor('exclude-receivers')) {
$suggestions->suggestValues($this->receiverNames);
}
}

public function getSubscribedSignals(): array
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -329,4 +329,156 @@ public static function provideCompletionSuggestions()
yield 'receiver (no repeat)' => [['async', ''], ['async_high', 'failed']];
yield 'option --bus' => [['--bus', ''], ['messenger.bus.default']];
}

public function testRunWithExcludeReceiversOption()
{
$envelope1 = new Envelope(new \stdClass(), [new BusNameStamp('dummy-bus')]);
$envelope2 = new Envelope(new \stdClass(), [new BusNameStamp('dummy-bus')]);
$envelope3 = new Envelope(new \stdClass(), [new BusNameStamp('dummy-bus')]);

$receiver1 = $this->createMock(ReceiverInterface::class);
$receiver1->method('get')->willReturn([$envelope1]);
$receiver2 = $this->createMock(ReceiverInterface::class);
$receiver2->method('get')->willReturn([$envelope2]);
$receiver3 = $this->createMock(ReceiverInterface::class);
$receiver3->method('get')->willReturn([$envelope3]);

$receiverLocator = new Container();
$receiverLocator->set('dummy-receiver1', $receiver1);
$receiverLocator->set('dummy-receiver2', $receiver2);
$receiverLocator->set('dummy-receiver3', $receiver3);

$bus = $this->createMock(MessageBusInterface::class);
// Only 2 messages should be dispatched (receiver1 and receiver3, receiver2 is excluded)
$bus->expects($this->exactly(2))->method('dispatch');

$busLocator = new Container();
$busLocator->set('dummy-bus', $bus);

$command = new ConsumeMessagesCommand(
new RoutableMessageBus($busLocator),
$receiverLocator, new EventDispatcher(),
receiverNames: ['dummy-receiver1', 'dummy-receiver2', 'dummy-receiver3']
);

$application = new Application();
if (method_exists($application, 'addCommand')) {
$application->addCommand($command);
} else {
$application->add($command);
}
$tester = new CommandTester($application->get('messenger:consume'));
$tester->execute([
'--all' => true,
'--exclude-receivers' => ['dummy-receiver2'],
'--limit' => 2,
]);

$tester->assertCommandIsSuccessful();
$this->assertStringContainsString('[OK] Consuming messages from transports "dummy-receiver1, dummy-receiver3"', $tester->getDisplay());
}

public function testRunWithExcludeReceiversMultipleQueues()
{
$envelope1 = new Envelope(new \stdClass(), [new BusNameStamp('dummy-bus')]);
$envelope2 = new Envelope(new \stdClass(), [new BusNameStamp('dummy-bus')]);
$envelope3 = new Envelope(new \stdClass(), [new BusNameStamp('dummy-bus')]);
$envelope4 = new Envelope(new \stdClass(), [new BusNameStamp('dummy-bus')]);

$receiver1 = $this->createMock(ReceiverInterface::class);
$receiver1->method('get')->willReturn([$envelope1]);
$receiver2 = $this->createMock(ReceiverInterface::class);
$receiver2->method('get')->willReturn([$envelope2]);
$receiver3 = $this->createMock(ReceiverInterface::class);
$receiver3->method('get')->willReturn([$envelope3]);
$receiver4 = $this->createMock(ReceiverInterface::class);
$receiver4->method('get')->willReturn([$envelope4]);

$receiverLocator = new Container();
$receiverLocator->set('dummy-receiver1', $receiver1);
$receiverLocator->set('dummy-receiver2', $receiver2);
$receiverLocator->set('dummy-receiver3', $receiver3);
$receiverLocator->set('dummy-receiver4', $receiver4);

$bus = $this->createMock(MessageBusInterface::class);
// Only 2 messages should be dispatched (receiver1 and receiver4, receiver2 and receiver3 are excluded)
$bus->expects($this->exactly(2))->method('dispatch');

$busLocator = new Container();
$busLocator->set('dummy-bus', $bus);

$command = new ConsumeMessagesCommand(
new RoutableMessageBus($busLocator),
$receiverLocator, new EventDispatcher(),
receiverNames: ['dummy-receiver1', 'dummy-receiver2', 'dummy-receiver3', 'dummy-receiver4']
);

$application = new Application();
if (method_exists($application, 'addCommand')) {
$application->addCommand($command);
} else {
$application->add($command);
}
$tester = new CommandTester($application->get('messenger:consume'));
$tester->execute([
'--all' => true,
'--exclude-receivers' => ['dummy-receiver2', 'dummy-receiver3'],
'--limit' => 2,
]);

$tester->assertCommandIsSuccessful();
$this->assertStringContainsString('[OK] Consuming messages from transports "dummy-receiver1, dummy-receiver4"', $tester->getDisplay());
}

public function testExcludeReceiverssWithoutAllOptionThrowsException()
{
$receiverLocator = new Container();
$receiverLocator->set('dummy-receiver', new \stdClass());

$command = new ConsumeMessagesCommand(new RoutableMessageBus(new Container()), $receiverLocator, new EventDispatcher());

$application = new Application();
if (method_exists($application, 'addCommand')) {
$application->addCommand($command);
} else {
$application->add($command);
}
$tester = new CommandTester($application->get('messenger:consume'));

$this->expectException(InvalidOptionException::class);
$this->expectExceptionMessage('The "--exclude-receivers" option can only be used with the "--all" option.');
$tester->execute([
'receivers' => ['dummy-receiver'],
'--exclude-receivers' => ['dummy-receiver'],
]);
}

public function testExcludeReceiversWithAllQueuesExcludedThrowsException()
{
$receiverLocator = new Container();
$receiverLocator->set('dummy-receiver1', new \stdClass());
$receiverLocator->set('dummy-receiver2', new \stdClass());

$command = new ConsumeMessagesCommand(
new RoutableMessageBus(new Container()),
$receiverLocator,
new EventDispatcher(),
receiverNames: ['dummy-receiver1', 'dummy-receiver2']
);

$application = new Application();
if (method_exists($application, 'addCommand')) {
$application->addCommand($command);
} else {
$application->add($command);
}
$tester = new CommandTester($application->get('messenger:consume'));

$this->expectException(\Symfony\Component\Console\Exception\RuntimeException::class);
$this->expectExceptionMessage('All transports/receivers have been excluded, please specify at least one to consume from.');
$tester->execute([
'--all' => true,
'--exclude-receivers' => ['dummy-receiver1', 'dummy-receiver2'],
]);
}
}
Loading