Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

[Messenger] Introduce DeduplicateMiddleware #54141

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

Merged
merged 1 commit into from
Feb 7, 2025
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
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@
use Symfony\Component\Messenger\Handler\BatchHandlerInterface;
use Symfony\Component\Messenger\MessageBus;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Messenger\Middleware\DeduplicateMiddleware;
use Symfony\Component\Messenger\Middleware\RouterContextMiddleware;
use Symfony\Component\Messenger\Transport\Serialization\SerializerInterface;
use Symfony\Component\Messenger\Transport\TransportFactoryInterface as MessengerTransportFactoryInterface;
Expand Down Expand Up @@ -2266,6 +2267,13 @@ private function registerMessengerConfiguration(array $config, ContainerBuilder
['id' => 'handle_message'],
],
];

if (class_exists(DeduplicateMiddleware::class) && class_exists(LockFactory::class)) {
$defaultMiddleware['before'][] = ['id' => 'deduplicate_middleware'];
} else {
$container->removeDefinition('messenger.middleware.deduplicate_middleware');
}

foreach ($config['buses'] as $busId => $bus) {
$middleware = $bus['middleware'];

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
use Symfony\Component\Messenger\EventListener\StopWorkerOnRestartSignalListener;
use Symfony\Component\Messenger\Handler\RedispatchMessageHandler;
use Symfony\Component\Messenger\Middleware\AddBusNameStampMiddleware;
use Symfony\Component\Messenger\Middleware\DeduplicateMiddleware;
use Symfony\Component\Messenger\Middleware\DispatchAfterCurrentBusMiddleware;
use Symfony\Component\Messenger\Middleware\FailedMessageProcessingMiddleware;
use Symfony\Component\Messenger\Middleware\HandleMessageMiddleware;
Expand Down Expand Up @@ -86,6 +87,11 @@
->tag('monolog.logger', ['channel' => 'messenger'])
->call('setLogger', [service('logger')->ignoreOnInvalid()])

->set('messenger.middleware.deduplicate_middleware', DeduplicateMiddleware::class)
->args([
service('lock.factory'),
])

->set('messenger.middleware.add_bus_name_stamp_middleware', AddBusNameStampMiddleware::class)
->abstract()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@
use Symfony\Component\Messenger\Bridge\Amqp\Transport\AmqpTransportFactory;
use Symfony\Component\Messenger\Bridge\Beanstalkd\Transport\BeanstalkdTransportFactory;
use Symfony\Component\Messenger\Bridge\Redis\Transport\RedisTransportFactory;
use Symfony\Component\Messenger\Middleware\DeduplicateMiddleware;
use Symfony\Component\Messenger\Transport\TransportFactory;
use Symfony\Component\Notifier\ChatterInterface;
use Symfony\Component\Notifier\TexterInterface;
Expand Down Expand Up @@ -1061,25 +1062,54 @@ 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', 'arguments' => [true]],
['id' => 'handle_message', 'arguments' => [false]],
], $container->getParameter('messenger.bus.commands.middleware'));

if (class_exists(DeduplicateMiddleware::class)) {
$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' => 'deduplicate_middleware'],
['id' => 'send_message', 'arguments' => [true]],
['id' => 'handle_message', 'arguments' => [false]],
], $container->getParameter('messenger.bus.commands.middleware'));
} else {
Comment on lines +1066 to +1076
Copy link
Contributor

@ro0NL ro0NL Mar 12, 2025

Choose a reason for hiding this comment

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

update the test deps next time to avoid these exra conditions :)

Copy link
Contributor

Choose a reason for hiding this comment

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

it's all maintenance

Copy link
Contributor

Choose a reason for hiding this comment

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

cc @fabpot

Copy link
Member

Choose a reason for hiding this comment

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

There’s not really a need to forbid using FrameworkBundle with Messenger < 7.3. But that would be the consequence if we cannot test it.

Copy link
Contributor

Choose a reason for hiding this comment

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

i dont like the if/else condition based on class presence generally

Copy link
Contributor

@ro0NL ro0NL Mar 12, 2025

Choose a reason for hiding this comment

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

7.2 is tested without class X
7.3 is tested with class X

it's that simple to me.

Copy link
Member

Choose a reason for hiding this comment

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

That would complicate things. Either we would require people to update FrameworkBundle and components at the same time which would make updating harder. Or we would not be able to test the bundle with the lowest deps which would not allow us to detect compatibility issues.

Copy link
Contributor

@ro0NL ro0NL Mar 12, 2025

Choose a reason for hiding this comment

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

we would require people to update FrameworkBundle and components at the same time which would make updating harder

generally yes, it that prevents if/else flows in your codebase. We should prefer branches then.

updating many sf packages from 7.2 to 7.x is not an issue.

$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', 'arguments' => [true]],
['id' => 'handle_message', 'arguments' => [false]],
], $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', 'arguments' => [true]],
['id' => 'handle_message', 'arguments' => [false]],
], $container->getParameter('messenger.bus.events.middleware'));

if (class_exists(DeduplicateMiddleware::class)) {
$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' => 'deduplicate_middleware'],
['id' => 'with_factory', 'arguments' => ['foo', true, ['bar' => 'baz']]],
['id' => 'send_message', 'arguments' => [true]],
['id' => 'handle_message', 'arguments' => [false]],
], $container->getParameter('messenger.bus.events.middleware'));
} else {
$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', 'arguments' => [true]],
['id' => 'handle_message', 'arguments' => [false]],
], $container->getParameter('messenger.bus.events.middleware'));
}

$this->assertTrue($container->has('messenger.bus.queries'));
$this->assertSame([], $container->getDefinition('messenger.bus.queries')->getArgument(0));
$this->assertEquals([
Expand Down
1 change: 1 addition & 0 deletions 1 src/Symfony/Component/Messenger/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ CHANGELOG
7.2
---

* Add `Symfony\Component\Messenger\Middleware\DeduplicateMiddleware` and `Symfony\Component\Messenger\Stamp\DeduplicateStamp`
* Add `$previous` to the exception output at the `messenger:failed:show` command
* `WrappedExceptionsInterface` now extends PHP's `Throwable` interface
* Add `#[AsMessage]` attribute with `$transport` parameter for message routing
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Messenger\Middleware;

use Symfony\Component\Lock\LockFactory;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\Stamp\DeduplicateStamp;
use Symfony\Component\Messenger\Stamp\ReceivedStamp;

final class DeduplicateMiddleware implements MiddlewareInterface
{
public function __construct(private LockFactory $lockFactory)
{
}

public function handle(Envelope $envelope, StackInterface $stack): Envelope
{
if (!$stamp = $envelope->last(DeduplicateStamp::class)) {
return $stack->next()->handle($envelope, $stack);
}

if (!$envelope->last(ReceivedStamp::class)) {
$lock = $this->lockFactory->createLockFromKey($stamp->getKey(), $stamp->getTtl(), autoRelease: false);

if (!$lock->acquire()) {
return $envelope;
}
} elseif ($stamp->onlyDeduplicateInQueue()) {
$this->lockFactory->createLockFromKey($stamp->getKey())->release();
}

try {
$envelope = $stack->next()->handle($envelope, $stack);
} finally {
if ($envelope->last(ReceivedStamp::class) && !$stamp->onlyDeduplicateInQueue()) {
$this->lockFactory->createLockFromKey($stamp->getKey())->release();
}
}
VincentLanglet marked this conversation as resolved.
Show resolved Hide resolved

return $envelope;
}
}
42 changes: 42 additions & 0 deletions 42 src/Symfony/Component/Messenger/Stamp/DeduplicateStamp.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Messenger\Stamp;

use Symfony\Component\Lock\Key;

final class DeduplicateStamp implements StampInterface
{
private Key $key;

public function __construct(
string $key,
private ?float $ttl = 300.0,
private bool $onlyDeduplicateInQueue = false,
) {
$this->key = new Key($key);
}

public function onlyDeduplicateInQueue(): bool
{
return $this->onlyDeduplicateInQueue;
}

public function getKey(): Key
{
return $this->key;
}

public function getTtl(): ?float
{
return $this->ttl;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Messenger\Tests\Middleware;

use Symfony\Component\Lock\LockFactory;
use Symfony\Component\Lock\Store\FlockStore;
use Symfony\Component\Lock\Store\SemaphoreStore;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\Middleware\DeduplicateMiddleware;
use Symfony\Component\Messenger\Stamp\DeduplicateStamp;
use Symfony\Component\Messenger\Stamp\ReceivedStamp;
use Symfony\Component\Messenger\Test\Middleware\MiddlewareTestCase;
use Symfony\Component\Messenger\Tests\Fixtures\DummyMessage;

final class DeduplicateMiddlewareTest extends MiddlewareTestCase
{
public function testDeduplicateMiddlewareIgnoreIfMessageIsNotLockable()
{
$message = new DummyMessage('Hello');
$envelope = new Envelope($message);

$lockFactory = $this->createMock(LockFactory::class);
$lockFactory->expects($this->never())->method('createLock');

$decorator = new DeduplicateMiddleware($lockFactory);

$decorator->handle($envelope, $this->getStackMock(true));
}

public function testDeduplicateMiddlewareIfMessageHasKey()
{
$message = new DummyMessage('Hello');
$envelope = new Envelope($message, [new DeduplicateStamp('id')]);

if (SemaphoreStore::isSupported()) {
$store = new SemaphoreStore();
} else {
$store = new FlockStore();
}

$decorator = new DeduplicateMiddleware(new LockFactory($store));

$envelope = $decorator->handle($envelope, $this->getStackMock(true));
$this->assertNotNull($envelope->last(DeduplicateStamp::class));

$message2 = new DummyMessage('Hello');
$envelope2 = new Envelope($message2, [new DeduplicateStamp('id')]);

$decorator->handle($envelope2, $this->getStackMock(false));

// Simulate receiving the first message
$envelope = $envelope->with(new ReceivedStamp('transport'));
$decorator->handle($envelope, $this->getStackMock(true));

$message3 = new DummyMessage('Hello');
$envelope3 = new Envelope($message3, [new DeduplicateStamp('id')]);
$decorator->handle($envelope3, $this->getStackMock(true));
}
}
2 changes: 2 additions & 0 deletions 2 src/Symfony/Component/Messenger/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"symfony/http-kernel": "^6.4|^7.0",
"symfony/process": "^6.4|^7.0",
"symfony/property-access": "^6.4|^7.0",
"symfony/lock": "^6.4|^7.0",
VincentLanglet marked this conversation as resolved.
Show resolved Hide resolved
"symfony/rate-limiter": "^6.4|^7.0",
"symfony/routing": "^6.4|^7.0",
"symfony/serializer": "^6.4|^7.0",
Expand All @@ -42,6 +43,7 @@
"symfony/event-dispatcher-contracts": "<2.5",
"symfony/framework-bundle": "<6.4",
"symfony/http-kernel": "<6.4",
"symfony/lock": "<6.4",
"symfony/serializer": "<6.4"
},
"autoload": {
Expand Down
Loading
Morty Proxy This is a proxified and sanitized view of the page, visit original site.