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

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