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 <[email protected]>
  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.         if ($e instanceof RecoverableExceptionInterface) {
  100.             return true;
  101.         }
  102.         // if one or more nested Exceptions is an instance of RecoverableExceptionInterface we should retry
  103.         // if ALL nested Exceptions are an instance of UnrecoverableExceptionInterface we should not retry
  104.         if ($e instanceof HandlerFailedException) {
  105.             $shouldNotRetry true;
  106.             foreach ($e->getNestedExceptions() as $nestedException) {
  107.                 if ($nestedException instanceof RecoverableExceptionInterface) {
  108.                     return true;
  109.                 }
  110.                 if (!$nestedException instanceof UnrecoverableExceptionInterface) {
  111.                     $shouldNotRetry false;
  112.                     break;
  113.                 }
  114.             }
  115.             if ($shouldNotRetry) {
  116.                 return false;
  117.             }
  118.         }
  119.         if ($e instanceof UnrecoverableExceptionInterface) {
  120.             return false;
  121.         }
  122.         return $retryStrategy->isRetryable($envelope$e);
  123.     }
  124.     private function getRetryStrategyForTransport(string $alias): ?RetryStrategyInterface
  125.     {
  126.         if ($this->retryStrategyLocator->has($alias)) {
  127.             return $this->retryStrategyLocator->get($alias);
  128.         }
  129.         return null;
  130.     }
  131.     private function getSenderForTransport(string $alias): SenderInterface
  132.     {
  133.         if ($this->sendersLocator->has($alias)) {
  134.             return $this->sendersLocator->get($alias);
  135.         }
  136.         throw new RuntimeException(sprintf('Could not find sender "%s" based on the same receiver to send the failed message to for retry.'$alias));
  137.     }
  138. }