<?php
declare(strict_types=1);
namespace App\EventSubscriber\Webhook;
use App\Entity\Admin\Webhook\Notification;
use App\Message\Webhook\SendNotificationMessage;
use App\Repository\Admin\Webhook\NotificationRepository;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Messenger\Event\WorkerMessageFailedEvent;
use Symfony\Component\Messenger\Stamp\RedeliveryStamp;
/**
* Marks the notification as failed when Messenger stops retrying its message, whatever the cause.
*/
class SendNotificationFailedSubscriber implements EventSubscriberInterface
{
public function __construct(
private NotificationRepository $notificationRepository,
private EntityManagerInterface $entityManager,
private LoggerInterface $channelNotificationLogger,
) {
}
public static function getSubscribedEvents(): array
{
return [WorkerMessageFailedEvent::class => 'onMessageFailed'];
}
public function onMessageFailed(WorkerMessageFailedEvent $event): void
{
$message = $event->getEnvelope()->getMessage();
if (!$message instanceof SendNotificationMessage || $event->willRetry()) {
return;
}
try {
$notification = $this->notificationRepository->find($message->getNotificationId());
if (null === $notification || $notification->isNotified() || Notification::STATE_FAILED === $notification->getState()) {
return;
}
$notification->setState(Notification::STATE_FAILED);
$this->entityManager->flush();
$this->channelNotificationLogger->error('Notification marked as failed, no retry left in Messenger', [
'notificationId' => $notification->getId(),
'retries' => RedeliveryStamp::getRetryCountFromEnvelope($event->getEnvelope()),
'error' => $event->getThrowable()->getMessage(),
]);
} catch (\Throwable $e) {
$this->channelNotificationLogger->error("Could not mark notification {$message->getNotificationId()} as failed", [
'error' => $e->getMessage(),
]);
}
}
}