vendor/symfony/messenger/EventListener/SendFailedMessageForRetryListener.php line 51

  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\EventListener;
  11. use Psr\Container\ContainerInterface;
  12. use Psr\EventDispatcher\EventDispatcherInterface;
  13. use Psr\Log\LoggerInterface;
  14. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  15. use Symfony\Component\Messenger\Envelope;
  16. use Symfony\Component\Messenger\Event\WorkerMessageFailedEvent;
  17. use Symfony\Component\Messenger\Event\WorkerMessageRetriedEvent;
  18. use Symfony\Component\Messenger\Exception\HandlerFailedException;
  19. use Symfony\Component\Messenger\Exception\RecoverableExceptionInterface;
  20. use Symfony\Component\Messenger\Exception\RuntimeException;
  21. use Symfony\Component\Messenger\Exception\UnrecoverableExceptionInterface;
  22. use Symfony\Component\Messenger\Retry\RetryStrategyInterface;
  23. use Symfony\Component\Messenger\Stamp\DelayStamp;
  24. use Symfony\Component\Messenger\Stamp\RedeliveryStamp;
  25. use Symfony\Component\Messenger\Stamp\StampInterface;
  26. use Symfony\Component\Messenger\Transport\Sender\SenderInterface;
  27. /**
  28.  * @author Tobias Schultze <http://tobion.de>
  29.  */
  30. class SendFailedMessageForRetryListener implements EventSubscriberInterface
  31. {
  32.     private ContainerInterface $sendersLocator;
  33.     private ContainerInterface $retryStrategyLocator;
  34.     private ?LoggerInterface $logger;
  35.     private ?EventDispatcherInterface $eventDispatcher;
  36.     private int $historySize;
  37.     public function __construct(ContainerInterface $sendersLocatorContainerInterface $retryStrategyLocatorLoggerInterface $logger nullEventDispatcherInterface $eventDispatcher nullint $historySize 10)
  38.     {
  39.         $this->sendersLocator $sendersLocator;
  40.         $this->retryStrategyLocator $retryStrategyLocator;
  41.         $this->logger $logger;
  42.         $this->eventDispatcher $eventDispatcher;
  43.         $this->historySize $historySize;
  44.     }
  45.     public function onMessageFailed(WorkerMessageFailedEvent $event)
  46.     {
  47.         $retryStrategy $this->getRetryStrategyForTransport($event->getReceiverName());
  48.         $envelope $event->getEnvelope();
  49.         $throwable $event->getThrowable();
  50.         $message $envelope->getMessage();
  51.         $context = [
  52.             'class' => $message::class,
  53.         ];
  54.         $shouldRetry $retryStrategy && $this->shouldRetry($throwable$envelope$retryStrategy);
  55.         $retryCount RedeliveryStamp::getRetryCountFromEnvelope($envelope);
  56.         if ($shouldRetry) {
  57.             $event->setForRetry();
  58.             ++$retryCount;
  59.             $delay $retryStrategy->getWaitingTime($envelope$throwable);
  60.             $this->logger?->warning('Error thrown while handling message {class}. Sending for retry #{retryCount} using {delay} ms delay. Error: "{error}"'$context + ['retryCount' => $retryCount'delay' => $delay'error' => $throwable->getMessage(), 'exception' => $throwable]);
  61.             // add the delay and retry stamp info
  62.             $retryEnvelope $this->withLimitedHistory($envelope, new DelayStamp($delay), new RedeliveryStamp($retryCount));
  63.             // re-send the message for retry
  64.             $this->getSenderForTransport($event->getReceiverName())->send($retryEnvelope);
  65.             $this->eventDispatcher?->dispatch(new WorkerMessageRetriedEvent($retryEnvelope$event->getReceiverName()));
  66.         } else {
  67.             $this->logger?->critical('Error thrown while handling message {class}. Removing from transport after {retryCount} retries. Error: "{error}"'$context + ['retryCount' => $retryCount'error' => $throwable->getMessage(), 'exception' => $throwable]);
  68.         }
  69.     }
  70.     /**
  71.      * Adds stamps to the envelope by keeping only the First + Last N stamps.
  72.      */
  73.     private function withLimitedHistory(Envelope $envelopeStampInterface ...$stamps): Envelope
  74.     {
  75.         foreach ($stamps as $stamp) {
  76.             $history $envelope->all($stamp::class);
  77.             if (\count($history) < $this->historySize) {
  78.                 $envelope $envelope->with($stamp);
  79.                 continue;
  80.             }
  81.             $history array_merge(
  82.                 [$history[0]],
  83.                 \array_slice($history, -$this->historySize 2),
  84.                 [$stamp]
  85.             );
  86.             $envelope $envelope->withoutAll($stamp::class)->with(...$history);
  87.         }
  88.         return $envelope;
  89.     }
  90.     public static function getSubscribedEvents(): array
  91.     {
  92.         return [
  93.             // must have higher priority than SendFailedMessageToFailureTransportListener
  94.             WorkerMessageFailedEvent::class => ['onMessageFailed'100],
  95.         ];
  96.     }
  97.     private function shouldRetry(\Throwable $eEnvelope $envelopeRetryStrategyInterface $retryStrategy): bool
  98.     {
  99.         $isRetryable $retryStrategy->isRetryable($envelope$e);
  100.         if ($isRetryable && $e instanceof RecoverableExceptionInterface) {
  101.             return true;
  102.         }
  103.         // if one or more nested Exceptions is an instance of RecoverableExceptionInterface we should retry
  104.         // if ALL nested Exceptions are an instance of UnrecoverableExceptionInterface we should not retry
  105.         if ($e instanceof HandlerFailedException) {
  106.             $shouldNotRetry true;
  107.             foreach ($e->getNestedExceptions() as $nestedException) {
  108.                 if ($isRetryable && $nestedException instanceof RecoverableExceptionInterface) {
  109.                     return true;
  110.                 }
  111.                 if (!$nestedException instanceof UnrecoverableExceptionInterface) {
  112.                     $shouldNotRetry false;
  113.                     break;
  114.                 }
  115.             }
  116.             if ($shouldNotRetry) {
  117.                 return false;
  118.             }
  119.         }
  120.         if ($e instanceof UnrecoverableExceptionInterface) {
  121.             return false;
  122.         }
  123.         return $isRetryable;
  124.     }
  125.     private function getRetryStrategyForTransport(string $alias): ?RetryStrategyInterface
  126.     {
  127.         if ($this->retryStrategyLocator->has($alias)) {
  128.             return $this->retryStrategyLocator->get($alias);
  129.         }
  130.         return null;
  131.     }
  132.     private function getSenderForTransport(string $alias): SenderInterface
  133.     {
  134.         if ($this->sendersLocator->has($alias)) {
  135.             return $this->sendersLocator->get($alias);
  136.         }
  137.         throw new RuntimeException(sprintf('Could not find sender "%s" based on the same receiver to send the failed message to for retry.'$alias));
  138.     }
  139. }