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

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\Exception\HandlerFailedException;
  17. use Symfony\Component\Messenger\Exception\RecoverableExceptionInterface;
  18. use Symfony\Component\Messenger\Exception\RuntimeException;
  19. use Symfony\Component\Messenger\Exception\UnrecoverableExceptionInterface;
  20. use Symfony\Component\Messenger\Retry\RetryStrategyInterface;
  21. use Symfony\Component\Messenger\Stamp\DelayStamp;
  22. use Symfony\Component\Messenger\Stamp\RedeliveryStamp;
  23. use Symfony\Component\Messenger\Stamp\StampInterface;
  24. use Symfony\Component\Messenger\Transport\Sender\SenderInterface;
  25. /**
  26.  * @author Tobias Schultze <http://tobion.de>
  27.  */
  28. class SendFailedMessageForRetryListener implements EventSubscriberInterface
  29. {
  30.     private $sendersLocator;
  31.     private $retryStrategyLocator;
  32.     private $logger;
  33.     private $historySize;
  34.     public function __construct(ContainerInterface $sendersLocatorContainerInterface $retryStrategyLocatorLoggerInterface $logger nullint $historySize 10)
  35.     {
  36.         $this->sendersLocator $sendersLocator;
  37.         $this->retryStrategyLocator $retryStrategyLocator;
  38.         $this->logger $logger;
  39.         $this->historySize $historySize;
  40.     }
  41.     public function onMessageFailed(WorkerMessageFailedEvent $event)
  42.     {
  43.         $retryStrategy $this->getRetryStrategyForTransport($event->getReceiverName());
  44.         $envelope $event->getEnvelope();
  45.         $throwable $event->getThrowable();
  46.         $message $envelope->getMessage();
  47.         $context = [
  48.             'message' => $message,
  49.             'class' => \get_class($message),
  50.         ];
  51.         $shouldRetry $retryStrategy && $this->shouldRetry($throwable$envelope$retryStrategy);
  52.         $retryCount RedeliveryStamp::getRetryCountFromEnvelope($envelope);
  53.         if ($shouldRetry) {
  54.             $event->setForRetry();
  55.             ++$retryCount;
  56.             $delay $retryStrategy->getWaitingTime($envelope$throwable);
  57.             if (null !== $this->logger) {
  58.                 $this->logger->error('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]);
  59.             }
  60.             // add the delay and retry stamp info
  61.             $retryEnvelope $this->withLimitedHistory($envelope, new DelayStamp($delay), new RedeliveryStamp($retryCount));
  62.             // re-send the message for retry
  63.             $this->getSenderForTransport($event->getReceiverName())->send($retryEnvelope);
  64.         } else {
  65.             if (null !== $this->logger) {
  66.                 $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]);
  67.             }
  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(\get_class($stamp));
  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(\get_class($stamp))->with(...$history);
  87.         }
  88.         return $envelope;
  89.     }
  90.     public static function getSubscribedEvents()
  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. }