vendor/symfony/messenger/Middleware/RejectRedeliveredMessageMiddleware.php line 34

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <fabien@symfony.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace Symfony\Component\Messenger\Middleware;
  11. use Symfony\Component\Messenger\Bridge\Amqp\Transport\AmqpReceivedStamp;
  12. use Symfony\Component\Messenger\Envelope;
  13. use Symfony\Component\Messenger\Exception\RejectRedeliveredMessageException;
  14. /**
  15.  * Middleware that throws a RejectRedeliveredMessageException when a message is detected that has been redelivered by AMQP.
  16.  *
  17.  * The middleware runs before the HandleMessageMiddleware and prevents redelivered messages from being handled directly.
  18.  * The thrown exception is caught by the worker and will trigger the retry logic according to the retry strategy.
  19.  *
  20.  * AMQP redelivers messages when they do not get acknowledged or rejected. This can happen when the connection times out
  21.  * or an exception is thrown before acknowledging or rejecting. When such errors happen again while handling the
  22.  * redelivered message, the message would get redelivered again and again. The purpose of this middleware is to prevent
  23.  * infinite redelivery loops and to unblock the queue by republishing the redelivered messages as retries with a retry
  24.  * limit and potential delay.
  25.  *
  26.  * @author Tobias Schultze <http://tobion.de>
  27.  */
  28. class RejectRedeliveredMessageMiddleware implements MiddlewareInterface
  29. {
  30.     public function handle(Envelope $envelopeStackInterface $stack): Envelope
  31.     {
  32.         $amqpReceivedStamp $envelope->last(AmqpReceivedStamp::class);
  33.         if ($amqpReceivedStamp instanceof AmqpReceivedStamp && $amqpReceivedStamp->getAmqpEnvelope()->isRedelivery()) {
  34.             throw new RejectRedeliveredMessageException('Redelivered message from AMQP detected that will be rejected and trigger the retry logic.');
  35.         }
  36.         return $stack->next()->handle($envelope$stack);
  37.     }
  38. }