src/EventSubscriber/Webhook/SendNotificationFailedSubscriber.php line 33

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\EventSubscriber\Webhook;
  4. use App\Entity\Admin\Webhook\Notification;
  5. use App\Message\Webhook\SendNotificationMessage;
  6. use App\Repository\Admin\Webhook\NotificationRepository;
  7. use Doctrine\ORM\EntityManagerInterface;
  8. use Psr\Log\LoggerInterface;
  9. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  10. use Symfony\Component\Messenger\Event\WorkerMessageFailedEvent;
  11. use Symfony\Component\Messenger\Stamp\RedeliveryStamp;
  12. /**
  13.  * Marks the notification as failed when Messenger stops retrying its message, whatever the cause.
  14.  */
  15. class SendNotificationFailedSubscriber implements EventSubscriberInterface
  16. {
  17.     public function __construct(
  18.         private NotificationRepository $notificationRepository,
  19.         private EntityManagerInterface $entityManager,
  20.         private LoggerInterface $channelNotificationLogger,
  21.     ) {
  22.     }
  23.     public static function getSubscribedEvents(): array
  24.     {
  25.         return [WorkerMessageFailedEvent::class => 'onMessageFailed'];
  26.     }
  27.     public function onMessageFailed(WorkerMessageFailedEvent $event): void
  28.     {
  29.         $message = $event->getEnvelope()->getMessage();
  30.         if (!$message instanceof SendNotificationMessage || $event->willRetry()) {
  31.             return;
  32.         }
  33.         try {
  34.             $notification = $this->notificationRepository->find($message->getNotificationId());
  35.             if (null === $notification || $notification->isNotified() || Notification::STATE_FAILED === $notification->getState()) {
  36.                 return;
  37.             }
  38.             $notification->setState(Notification::STATE_FAILED);
  39.             $this->entityManager->flush();
  40.             $this->channelNotificationLogger->error('Notification marked as failed, no retry left in Messenger', [
  41.                 'notificationId' => $notification->getId(),
  42.                 'retries' => RedeliveryStamp::getRetryCountFromEnvelope($event->getEnvelope()),
  43.                 'error' => $event->getThrowable()->getMessage(),
  44.             ]);
  45.         } catch (\Throwable $e) {
  46.             $this->channelNotificationLogger->error("Could not mark notification {$message->getNotificationId()} as failed", [
  47.                 'error' => $e->getMessage(),
  48.             ]);
  49.         }
  50.     }
  51. }