Skip to content

[Messenger][AmqpExt] Add a retry mechanism for AMQP messages #27008

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 2 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
4 changes: 3 additions & 1 deletion UPGRADE-4.2.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,9 @@ Messenger
---------

* The `handle` method of the `Symfony\Component\Messenger\Middleware\ValidationMiddleware` and `Symfony\Component\Messenger\Asynchronous\Middleware\SendMessageMiddleware` middlewares now requires an `Envelope` object to be given (because they implement the `EnvelopeAwareInterface`). When using these middleware with the provided `MessageBus`, you will not have to do anything. If you use the middlewares any other way, you can use `Envelope::wrap($message)` to create an envelope for your message.

* The method `getConnectionCredentials` of the AMQP transport class `Symfony\Component\Messenger\Transport\AmqpExt\Connection`
has been renamed to `getConnectionConfiguration`.

Security
--------

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@
<argument type="service" id="messenger.transport.encoder" />
<argument type="service" id="messenger.transport.decoder" />
<argument>%kernel.debug%</argument>
<argument type="service" id="logger" on-invalid="null" />

<tag name="messenger.transport_factory" />
</service>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ public function testItNonAcknowledgeTheMessageIfAnExceptionHappened()
$connection = $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->getMock();
$connection->method('get')->willReturn($envelope);

$connection->expects($this->once())->method('nack')->with($envelope);
$connection->expects($this->once())->method('nack')->with($envelope, AMQP_REQUEUE);

$receiver = new AmqpReceiver($serializer, $connection);
$receiver->receive(function () {
Expand Down Expand Up @@ -101,6 +101,60 @@ public function testItRejectsTheMessageIfTheExceptionIsARejectMessageExceptionIn
throw new WillNeverWorkException('Well...');
});
}

public function testItPublishesTheMessageForRetryIfSuchConfiguration()
{
$serializer = new Serializer(
new SerializerComponent\Serializer(array(new ObjectNormalizer()), array('json' => new JsonEncoder()))
);

$envelope = $this->getMockBuilder(\AMQPEnvelope::class)->getMock();
$envelope->method('getBody')->willReturn('{"message": "Hi"}');
$envelope->method('getHeaders')->willReturn(array(
'type' => DummyMessage::class,
));

$connection = $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->getMock();
$connection->method('get')->willReturn($envelope);
$connection->method('getConnectionConfiguration')->willReturn(array('retry' => array('attempts' => 3)));
$connection->method('publishForRetry')->with($envelope)->willReturn(true);

$connection->expects($this->once())->method('ack')->with($envelope);

$receiver = new AmqpReceiver($serializer, $connection);
$receiver->receive(function (Envelope $envelope) use ($receiver) {
$this->assertEquals(new DummyMessage('Hi'), $envelope->getMessage());
$receiver->stop();
});
}

/**
* @expectedException \Symfony\Component\Messenger\Tests\Transport\AmqpExt\InterruptException
*/
public function testItThrowsTheExceptionIfTheRetryPublishDidNotWork()
{
$serializer = new Serializer(
new SerializerComponent\Serializer(array(new ObjectNormalizer()), array('json' => new JsonEncoder()))
);

$envelope = $this->getMockBuilder(\AMQPEnvelope::class)->getMock();
$envelope->method('getBody')->willReturn('{"message": "Hi"}');
$envelope->method('getHeaders')->willReturn(array(
'type' => DummyMessage::class,
));

$connection = $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->getMock();
$connection->method('get')->willReturn($envelope);
$connection->method('getConnectionConfiguration')->willReturn(array('retry' => array('attempts' => 3)));
$connection->method('publishForRetry')->with($envelope)->willReturn(false);

$connection->expects($this->never())->method('ack')->with($envelope);

$receiver = new AmqpReceiver($serializer, $connection);
$receiver->receive(function () {
throw new InterruptException('Well...');
});
}
}

class InterruptException extends \Exception
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public function testItCreatesTheTransport()
true
);

$expectedTransport = new AmqpTransport($encoder, $decoder, Connection::fromDsn('amqp://localhost', array('foo' => 'bar'), true), array('foo' => 'bar'), true);
$expectedTransport = new AmqpTransport($encoder, $decoder, Connection::fromDsn('amqp://localhost', array('foo' => 'bar'), true));

$this->assertEquals($expectedTransport, $factory->createTransport('amqp://localhost', array('foo' => 'bar')));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,98 @@ public function testItCanDisableTheSetup()
$connection = Connection::fromDsn('amqp://localhost/%2f/messages?queue[routing_key]=my_key&auto-setup=false', array(), true, $factory);
$connection->publish('body');
}

public function testItRetriesTheMessage()
{
$amqpConnection = $this->getMockBuilder(\AMQPConnection::class)->disableOriginalConstructor()->getMock();
$amqpChannel = $this->getMockBuilder(\AMQPChannel::class)->disableOriginalConstructor()->getMock();
$retryQueue = $this->getMockBuilder(\AMQPQueue::class)->disableOriginalConstructor()->getMock();

$factory = $this->getMockBuilder(AmqpFactory::class)->getMock();
$factory->method('createConnection')->willReturn($amqpConnection);
$factory->method('createChannel')->willReturn($amqpChannel);
$factory->method('createQueue')->willReturn($retryQueue);
$factory->method('createExchange')->will($this->onConsecutiveCalls(
$retryExchange = $this->getMockBuilder(\AMQPExchange::class)->disableOriginalConstructor()->getMock(),
$amqpExchange = $this->getMockBuilder(\AMQPExchange::class)->disableOriginalConstructor()->getMock()
));

$amqpExchange->expects($this->once())->method('setName')->with('messages');
$amqpExchange->method('getName')->willReturn('messages');

$retryExchange->expects($this->once())->method('setName')->with('retry');
$retryExchange->expects($this->once())->method('declareExchange');
$retryExchange->method('getName')->willReturn('retry');

$retryQueue->expects($this->once())->method('setName')->with('retry_queue_1');
$retryQueue->expects($this->once())->method('setArguments')->with(array(
'x-message-ttl' => 10000,
'x-dead-letter-exchange' => 'messages',
));

$retryQueue->expects($this->once())->method('declareQueue');
$retryQueue->expects($this->once())->method('bind')->with('retry', 'attempt_1');

$envelope = $this->getMockBuilder(\AMQPEnvelope::class)->getMock();
$envelope->method('getHeader')->with('symfony-messenger-attempts')->willReturn(false);
$envelope->method('getHeaders')->willReturn(array('x-some-headers' => 'foo'));
$envelope->method('getBody')->willReturn('{}');

$retryExchange->expects($this->once())->method('publish')->with('{}', 'attempt_1', AMQP_NOPARAM, array('headers' => array('x-some-headers' => 'foo', 'symfony-messenger-attempts' => 1)));

$connection = Connection::fromDsn('amqp://localhost/%2f/messages', array('retry' => array('attempts' => 3)), false, $factory);
$connection->publishForRetry($envelope);
}

public function testItRetriesTheMessageWithADifferentRoutingKeyAndTTLs()
{
$amqpConnection = $this->getMockBuilder(\AMQPConnection::class)->disableOriginalConstructor()->getMock();
$amqpChannel = $this->getMockBuilder(\AMQPChannel::class)->disableOriginalConstructor()->getMock();
$retryQueue = $this->getMockBuilder(\AMQPQueue::class)->disableOriginalConstructor()->getMock();

$factory = $this->getMockBuilder(AmqpFactory::class)->getMock();
$factory->method('createConnection')->willReturn($amqpConnection);
$factory->method('createChannel')->willReturn($amqpChannel);
$factory->method('createQueue')->willReturn($retryQueue);
$factory->method('createExchange')->will($this->onConsecutiveCalls(
$retryExchange = $this->getMockBuilder(\AMQPExchange::class)->disableOriginalConstructor()->getMock(),
$amqpExchange = $this->getMockBuilder(\AMQPExchange::class)->disableOriginalConstructor()->getMock()
));

$amqpExchange->expects($this->once())->method('setName')->with('messages');
$amqpExchange->method('getName')->willReturn('messages');

$retryExchange->expects($this->once())->method('setName')->with('retry');
$retryExchange->expects($this->once())->method('declareExchange');
$retryExchange->method('getName')->willReturn('retry');

$connectionOptions = array(
'retry' => array(
'attempts' => 3,
'dead_routing_key' => 'my_dead_routing_key',
'ttl' => array(30000, 60000, 120000),
),
);

$connection = Connection::fromDsn('amqp://localhost/%2f/messages', $connectionOptions, false, $factory);

$messageRetriedTwice = $this->getMockBuilder(\AMQPEnvelope::class)->getMock();
$messageRetriedTwice->method('getHeader')->with('symfony-messenger-attempts')->willReturn('2');
$messageRetriedTwice->method('getHeaders')->willReturn(array('symfony-messenger-attempts' => '2'));
$messageRetriedTwice->method('getBody')->willReturn('{}');

$retryQueue->expects($this->once())->method('setName')->with('retry_queue_3');
$retryQueue->expects($this->once())->method('setArguments')->with(array(
'x-message-ttl' => 120000,
'x-dead-letter-exchange' => 'messages',
));

$retryQueue->expects($this->once())->method('declareQueue');
$retryQueue->expects($this->once())->method('bind')->with('retry', 'attempt_3');

$retryExchange->expects($this->once())->method('publish')->with('{}', 'attempt_3', AMQP_NOPARAM, array('headers' => array('symfony-messenger-attempts' => 3)));
$connection->publishForRetry($messageRetriedTwice);
}
}

class TestAmqpFactory extends AmqpFactory
Expand Down
33 changes: 29 additions & 4 deletions src/Symfony/Component/Messenger/Transport/AmqpExt/AmqpReceiver.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

namespace Symfony\Component\Messenger\Transport\AmqpExt;

use Psr\Log\LoggerInterface;
use Symfony\Component\Messenger\Transport\AmqpExt\Exception\RejectMessageExceptionInterface;
use Symfony\Component\Messenger\Transport\ReceiverInterface;
use Symfony\Component\Messenger\Transport\Serialization\DecoderInterface;
Expand All @@ -22,14 +23,18 @@
*/
class AmqpReceiver implements ReceiverInterface
{
private const DEFAULT_LOOP_SLEEP_IN_MICRO_SECONDS = 200000;

private $decoder;
private $connection;
private $logger;
private $shouldStop;

public function __construct(DecoderInterface $decoder, Connection $connection)
public function __construct(DecoderInterface $decoder, Connection $connection, LoggerInterface $logger = null)
{
$this->decoder = $decoder;
$this->connection = $connection;
$this->logger = $logger;
}

/**
Expand All @@ -39,10 +44,11 @@ public function receive(callable $handler): void
{
while (!$this->shouldStop) {
$AMQPEnvelope = $this->connection->get();

if (null === $AMQPEnvelope) {
$handler(null);

usleep($this->connection->getConnectionCredentials()['loop_sleep'] ?? 200000);
usleep($this->connection->getConnectionConfiguration()['loop_sleep'] ?? self::DEFAULT_LOOP_SLEEP_IN_MICRO_SECONDS);
if (\function_exists('pcntl_signal_dispatch')) {
pcntl_signal_dispatch();
}
Expand All @@ -62,9 +68,25 @@ public function receive(callable $handler): void

throw $e;
} catch (\Throwable $e) {
$this->connection->nack($AMQPEnvelope, AMQP_REQUEUE);
try {
$retried = $this->connection->publishForRetry($AMQPEnvelope);
} catch (\Throwable $retryException) {
$this->logger && $this->logger->warning(sprintf('Retrying message #%s failed. Requeuing it now.', $AMQPEnvelope->getMessageId()), array(
'retryException' => $retryException,
'exception' => $e,
));

throw $e;
$retried = false;
}

if (!$retried) {
$this->connection->nack($AMQPEnvelope, AMQP_REQUEUE);

throw $e;
}

// Acknowledge current message as another one as been requeued.
$this->connection->ack($AMQPEnvelope);
} finally {
if (\function_exists('pcntl_signal_dispatch')) {
pcntl_signal_dispatch();
Expand All @@ -73,6 +95,9 @@ public function receive(callable $handler): void
}
}

/**
* {@inheritdoc}
*/
public function stop(): void
{
$this->shouldStop = true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

namespace Symfony\Component\Messenger\Transport\AmqpExt;

use Psr\Log\LoggerInterface;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\Transport\Serialization\DecoderInterface;
use Symfony\Component\Messenger\Transport\Serialization\EncoderInterface;
Expand All @@ -26,12 +27,14 @@ class AmqpTransport implements TransportInterface
private $connection;
private $receiver;
private $sender;
private $logger;

public function __construct(EncoderInterface $encoder, DecoderInterface $decoder, Connection $connection)
public function __construct(EncoderInterface $encoder, DecoderInterface $decoder, Connection $connection, LoggerInterface $logger = null)
{
$this->encoder = $encoder;
$this->decoder = $decoder;
$this->connection = $connection;
$this->logger = $logger;
}

/**
Expand Down Expand Up @@ -60,7 +63,7 @@ public function send(Envelope $envelope): void

private function getReceiver()
{
return $this->receiver = new AmqpReceiver($this->decoder, $this->connection);
return $this->receiver = new AmqpReceiver($this->decoder, $this->connection, $this->logger);
}

private function getSender()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

namespace Symfony\Component\Messenger\Transport\AmqpExt;

use Psr\Log\LoggerInterface;
use Symfony\Component\Messenger\Transport\Serialization\DecoderInterface;
use Symfony\Component\Messenger\Transport\Serialization\EncoderInterface;
use Symfony\Component\Messenger\Transport\TransportFactoryInterface;
Expand All @@ -24,17 +25,19 @@ class AmqpTransportFactory implements TransportFactoryInterface
private $encoder;
private $decoder;
private $debug;
private $logger;

public function __construct(EncoderInterface $encoder, DecoderInterface $decoder, bool $debug)
public function __construct(EncoderInterface $encoder, DecoderInterface $decoder, bool $debug, LoggerInterface $logger = null)
{
$this->encoder = $encoder;
$this->decoder = $decoder;
$this->debug = $debug;
$this->logger = $logger;
}

public function createTransport(string $dsn, array $options): TransportInterface
{
return new AmqpTransport($this->encoder, $this->decoder, Connection::fromDsn($dsn, $options, $this->debug));
return new AmqpTransport($this->encoder, $this->decoder, Connection::fromDsn($dsn, $options, $this->debug), $this->logger);
}

public function supports(string $dsn, array $options): bool
Expand Down
Loading