Merge pull request #48 from maelgangloff/refactor/domain-message

refactor: split ProcessDomain message
This commit is contained in:
Maël Gangloff
2024-08-27 00:19:09 +02:00
committed by GitHub
11 changed files with 266 additions and 180 deletions

View File

@@ -21,10 +21,12 @@ framework:
Symfony\Component\Mailer\Messenger\SendEmailMessage: async
Symfony\Component\Notifier\Message\ChatMessage: async
Symfony\Component\Notifier\Message\SmsMessage: async
App\Message\UpdateRdapServers: async
App\Message\OrderDomain: async
App\Message\ProcessWatchListsTrigger: async
App\Message\ProcessWatchListTrigger: async
App\Message\ProcessDomainTrigger: async
App\Message\SendDomainEventNotif: async
App\Message\UpdateDomainsFromWatchlist: async
App\Message\UpdateRdapServers: async
# Route your messages to the transports
# 'App\Message\YourMessage': async

View File

@@ -4,7 +4,7 @@ namespace App\Controller;
use App\Entity\Domain;
use App\Entity\WatchList;
use App\Message\ProcessDomainTrigger;
use App\Message\SendDomainEventNotif;
use App\Repository\DomainRepository;
use App\Service\RDAPService;
use Psr\Log\LoggerInterface;
@@ -80,7 +80,7 @@ class DomainRefreshController extends AbstractController
/** @var WatchList $watchList */
foreach ($watchLists as $watchList) {
$this->bus->dispatch(new ProcessDomainTrigger($watchList->getToken(), $domain->getLdhName(), $updatedAt));
$this->bus->dispatch(new SendDomainEventNotif($watchList->getToken(), $domain->getLdhName(), $updatedAt));
}
return $domain;

View File

@@ -2,7 +2,7 @@
namespace App\Message;
final class ProcessDomainTrigger
final class OrderDomain
{
public function __construct(
public string $watchListToken,

View File

@@ -0,0 +1,13 @@
<?php
namespace App\Message;
final class SendDomainEventNotif
{
public function __construct(
public string $watchListToken,
public string $ldhName,
public \DateTimeImmutable $updatedAt
) {
}
}

View File

@@ -2,7 +2,7 @@
namespace App\Message;
final readonly class ProcessWatchListTrigger
final readonly class UpdateDomainsFromWatchlist
{
public function __construct(
public string $watchListToken,

View File

@@ -0,0 +1,99 @@
<?php
namespace App\MessageHandler;
use App\Config\Provider\AbstractProvider;
use App\Entity\Domain;
use App\Entity\WatchList;
use App\Message\OrderDomain;
use App\Notifier\DomainOrderErrorNotification;
use App\Notifier\DomainOrderNotification;
use App\Repository\DomainRepository;
use App\Repository\WatchListRepository;
use App\Service\ChatNotificationService;
use App\Service\StatService;
use Psr\Cache\CacheItemPoolInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Symfony\Component\Mime\Address;
use Symfony\Component\Notifier\Recipient\Recipient;
use Symfony\Contracts\HttpClient\HttpClientInterface;
#[AsMessageHandler]
final readonly class OrderDomainHandler
{
private Address $sender;
public function __construct(
string $mailerSenderEmail,
string $mailerSenderName,
private WatchListRepository $watchListRepository,
private DomainRepository $domainRepository,
private KernelInterface $kernel,
private HttpClientInterface $client,
private CacheItemPoolInterface $cacheItemPool,
private MailerInterface $mailer,
private LoggerInterface $logger,
private StatService $statService,
private ChatNotificationService $chatNotificationService
) {
$this->sender = new Address($mailerSenderEmail, $mailerSenderName);
}
/**
* @throws TransportExceptionInterface
* @throws \Symfony\Component\Notifier\Exception\TransportExceptionInterface
* @throws \Throwable
*/
public function __invoke(OrderDomain $message): void
{
/** @var WatchList $watchList */
$watchList = $this->watchListRepository->findOneBy(['token' => $message->watchListToken]);
/** @var Domain $domain */
$domain = $this->domainRepository->findOneBy(['ldhName' => $message->ldhName]);
$connector = $watchList->getConnector();
if (null !== $connector && $domain->getDeleted()) {
$this->logger->notice('Watchlist {watchlist} is linked to connector {connector}. A purchase attempt will be made for domain name {ldhName} with provider {provider}.', [
'watchlist' => $message->watchListToken,
'connector' => $connector->getId(),
'ldhName' => $message->ldhName,
'provider' => $connector->getProvider()->value,
]);
try {
$provider = $connector->getProvider();
if (null === $provider) {
throw new \Exception('Provider not found');
}
$connectorProviderClass = $provider->getConnectorProvider();
/** @var AbstractProvider $connectorProvider */
$connectorProvider = new $connectorProviderClass($connector->getAuthData(), $this->client, $this->cacheItemPool, $this->kernel);
$connectorProvider->orderDomain($domain, $this->kernel->isDebug());
$notification = (new DomainOrderNotification($this->sender, $domain, $connector));
$this->mailer->send($notification->asEmailMessage(new Recipient($watchList->getUser()->getEmail()))->getMessage());
$this->chatNotificationService->sendChatNotification($watchList, $notification);
$this->statService->incrementStat('stats.domain.purchased');
} catch (\Throwable $exception) {
$this->logger->warning('Unable to complete purchase. An error message is sent to user {username}.', [
'username' => $watchList->getUser()->getUserIdentifier(),
]);
$notification = (new DomainOrderErrorNotification($this->sender, $domain));
$this->mailer->send($notification->asEmailMessage(new Recipient($watchList->getUser()->getEmail()))->getMessage());
$this->chatNotificationService->sendChatNotification($watchList, $notification);
$this->statService->incrementStat('stats.domain.purchase.failed');
throw $exception;
}
}
}
}

View File

@@ -1,166 +0,0 @@
<?php
namespace App\MessageHandler;
use App\Config\Provider\AbstractProvider;
use App\Config\TriggerAction;
use App\Config\WebhookScheme;
use App\Entity\Domain;
use App\Entity\DomainEvent;
use App\Entity\WatchList;
use App\Entity\WatchListTrigger;
use App\Message\ProcessDomainTrigger;
use App\Notifier\DomainOrderErrorNotification;
use App\Notifier\DomainOrderNotification;
use App\Notifier\DomainUpdateNotification;
use App\Repository\DomainRepository;
use App\Repository\WatchListRepository;
use App\Service\StatService;
use Psr\Cache\CacheItemPoolInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Symfony\Component\Messenger\Exception\ExceptionInterface;
use Symfony\Component\Mime\Address;
use Symfony\Component\Notifier\Notification\ChatNotificationInterface;
use Symfony\Component\Notifier\Recipient\Recipient;
use Symfony\Component\Notifier\Transport\AbstractTransportFactory;
use Symfony\Component\Notifier\Transport\Dsn;
use Symfony\Contracts\HttpClient\HttpClientInterface;
#[AsMessageHandler]
final readonly class ProcessDomainTriggerHandler
{
private Address $sender;
public function __construct(
string $mailerSenderEmail,
string $mailerSenderName,
private WatchListRepository $watchListRepository,
private DomainRepository $domainRepository,
private KernelInterface $kernel,
private LoggerInterface $logger,
private HttpClientInterface $client,
private MailerInterface $mailer,
private CacheItemPoolInterface $cacheItemPool,
private StatService $statService
) {
$this->sender = new Address($mailerSenderEmail, $mailerSenderName);
}
/**
* @throws TransportExceptionInterface
* @throws \Exception
* @throws ExceptionInterface
*/
public function __invoke(ProcessDomainTrigger $message): void
{
/** @var WatchList $watchList */
$watchList = $this->watchListRepository->findOneBy(['token' => $message->watchListToken]);
/** @var Domain $domain */
$domain = $this->domainRepository->findOneBy(['ldhName' => $message->ldhName]);
$connector = $watchList->getConnector();
if (null !== $connector && $domain->getDeleted()) {
$this->logger->notice('Watchlist {watchlist} is linked to connector {connector}. A purchase attempt will be made for domain name {ldhName} with provider {provider}.', [
'watchlist' => $message->watchListToken,
'connector' => $connector->getId(),
'ldhName' => $message->ldhName,
'provider' => $connector->getProvider()->value,
]);
try {
$provider = $connector->getProvider();
if (null === $provider) {
throw new \Exception('Provider not found');
}
$connectorProviderClass = $provider->getConnectorProvider();
/** @var AbstractProvider $connectorProvider */
$connectorProvider = new $connectorProviderClass($connector->getAuthData(), $this->client, $this->cacheItemPool, $this->kernel);
$connectorProvider->orderDomain($domain, $this->kernel->isDebug());
$notification = (new DomainOrderNotification($this->sender, $domain, $connector));
$this->mailer->send($notification->asEmailMessage(new Recipient($watchList->getUser()->getEmail()))->getMessage());
$this->sendChatNotification($watchList, $notification);
$this->statService->incrementStat('stats.domain.purchased');
} catch (\Throwable) {
$this->logger->warning('Unable to complete purchase. An error message is sent to user {username}.', [
'username' => $watchList->getUser()->getUserIdentifier(),
]);
$notification = (new DomainOrderErrorNotification($this->sender, $domain));
$this->mailer->send($notification->asEmailMessage(new Recipient($watchList->getUser()->getEmail()))->getMessage());
$this->sendChatNotification($watchList, $notification);
$this->statService->incrementStat('stats.domain.purchase.failed');
}
}
/** @var DomainEvent $event */
foreach ($domain->getEvents()->filter(fn ($event) => $message->updatedAt < $event->getDate() && $event->getDate() < new \DateTime()) as $event) {
$watchListTriggers = $watchList->getWatchListTriggers()
->filter(fn ($trigger) => $trigger->getEvent() === $event->getAction());
/** @var WatchListTrigger $watchListTrigger */
foreach ($watchListTriggers->getIterator() as $watchListTrigger) {
$this->logger->info('Action {event} has been detected on the domain name {ldhName}. A notification is sent to user {username}.', [
'event' => $event->getAction(),
'ldhName' => $message->ldhName,
'username' => $watchList->getUser()->getUserIdentifier(),
]);
$recipient = new Recipient($watchList->getUser()->getEmail());
$notification = new DomainUpdateNotification($this->sender, $event);
if (TriggerAction::SendEmail == $watchListTrigger->getAction()) {
$this->mailer->send($notification->asEmailMessage($recipient)->getMessage());
} elseif (TriggerAction::SendChat == $watchListTrigger->getAction()) {
$this->sendChatNotification($watchList, $notification);
}
$this->statService->incrementStat('stats.alert.sent');
}
}
}
/**
* @throws \Symfony\Component\Notifier\Exception\TransportExceptionInterface
*/
private function sendChatNotification(WatchList $watchList, ChatNotificationInterface $notification): void
{
$webhookDsn = $watchList->getWebhookDsn();
if (null !== $webhookDsn && 0 !== count($webhookDsn)) {
foreach ($webhookDsn as $dsnString) {
$dsn = new Dsn($dsnString);
$scheme = $dsn->getScheme();
$webhookScheme = WebhookScheme::tryFrom($scheme);
if (null !== $webhookScheme) {
$transportFactoryClass = $webhookScheme->getChatTransportFactory();
/** @var AbstractTransportFactory $transportFactory */
$transportFactory = new $transportFactoryClass();
try {
$transportFactory->create($dsn)->send($notification->asChatMessage(new Recipient()));
$this->logger->info('Chat message sent with {schema} for Watchlist {token}',
[
'scheme' => $webhookScheme->name,
'token' => $watchList->getToken(),
]);
} catch (\Throwable) {
$this->logger->error('Unable to send a chat message to {scheme} for Watchlist {token}',
[
'scheme' => $webhookScheme->name,
'token' => $watchList->getToken(),
]);
}
}
}
}
}
}

View File

@@ -4,7 +4,7 @@ namespace App\MessageHandler;
use App\Entity\WatchList;
use App\Message\ProcessWatchListsTrigger;
use App\Message\ProcessWatchListTrigger;
use App\Message\UpdateDomainsFromWatchlist;
use App\Repository\WatchListRepository;
use Random\Randomizer;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
@@ -30,7 +30,7 @@ final readonly class ProcessWatchListsTriggerHandler
/** @var WatchList $watchList */
foreach ($watchLists as $watchList) {
$this->bus->dispatch(new ProcessWatchListTrigger($watchList->getToken()));
$this->bus->dispatch(new UpdateDomainsFromWatchlist($watchList->getToken()));
}
}
}

View File

@@ -0,0 +1,80 @@
<?php
namespace App\MessageHandler;
use App\Config\TriggerAction;
use App\Entity\Domain;
use App\Entity\DomainEvent;
use App\Entity\WatchList;
use App\Entity\WatchListTrigger;
use App\Message\SendDomainEventNotif;
use App\Notifier\DomainUpdateNotification;
use App\Repository\DomainRepository;
use App\Repository\WatchListRepository;
use App\Service\ChatNotificationService;
use App\Service\StatService;
use Psr\Log\LoggerInterface;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Symfony\Component\Messenger\Exception\ExceptionInterface;
use Symfony\Component\Mime\Address;
use Symfony\Component\Notifier\Recipient\Recipient;
#[AsMessageHandler]
final readonly class SendDomainEventNotifHandler
{
private Address $sender;
public function __construct(
string $mailerSenderEmail,
string $mailerSenderName,
private LoggerInterface $logger,
private MailerInterface $mailer,
private StatService $statService,
private DomainRepository $domainRepository,
private WatchListRepository $watchListRepository,
private ChatNotificationService $chatNotificationService
) {
$this->sender = new Address($mailerSenderEmail, $mailerSenderName);
}
/**
* @throws TransportExceptionInterface
* @throws \Exception
* @throws ExceptionInterface
*/
public function __invoke(SendDomainEventNotif $message): void
{
/** @var WatchList $watchList */
$watchList = $this->watchListRepository->findOneBy(['token' => $message->watchListToken]);
/** @var Domain $domain */
$domain = $this->domainRepository->findOneBy(['ldhName' => $message->ldhName]);
/** @var DomainEvent $event */
foreach ($domain->getEvents()->filter(fn ($event) => $message->updatedAt < $event->getDate() && $event->getDate() < new \DateTime()) as $event) {
$watchListTriggers = $watchList->getWatchListTriggers()
->filter(fn ($trigger) => $trigger->getEvent() === $event->getAction());
/** @var WatchListTrigger $watchListTrigger */
foreach ($watchListTriggers->getIterator() as $watchListTrigger) {
$this->logger->info('Action {event} has been detected on the domain name {ldhName}. A notification is sent to user {username}.', [
'event' => $event->getAction(),
'ldhName' => $message->ldhName,
'username' => $watchList->getUser()->getUserIdentifier(),
]);
$recipient = new Recipient($watchList->getUser()->getEmail());
$notification = new DomainUpdateNotification($this->sender, $event);
if (TriggerAction::SendEmail == $watchListTrigger->getAction()) {
$this->mailer->send($notification->asEmailMessage($recipient)->getMessage());
} elseif (TriggerAction::SendChat == $watchListTrigger->getAction()) {
$this->chatNotificationService->sendChatNotification($watchList, $notification);
}
$this->statService->incrementStat('stats.alert.sent');
}
}
}
}

View File

@@ -4,12 +4,14 @@ namespace App\MessageHandler;
use App\Entity\Domain;
use App\Entity\WatchList;
use App\Message\ProcessDomainTrigger;
use App\Message\ProcessWatchListTrigger;
use App\Message\OrderDomain;
use App\Message\SendDomainEventNotif;
use App\Message\UpdateDomainsFromWatchlist;
use App\Notifier\DomainUpdateErrorNotification;
use App\Repository\WatchListRepository;
use App\Service\RDAPService;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
@@ -19,7 +21,7 @@ use Symfony\Component\Mime\Address;
use Symfony\Component\Notifier\Recipient\Recipient;
#[AsMessageHandler]
final readonly class ProcessWatchListTriggerHandler
final readonly class UpdateDomainsFromWatchlistHandler
{
private Address $sender;
@@ -40,7 +42,7 @@ final readonly class ProcessWatchListTriggerHandler
* @throws \Exception
* @throws ExceptionInterface
*/
public function __invoke(ProcessWatchListTrigger $message): void
public function __invoke(UpdateDomainsFromWatchlist $message): void
{
/** @var WatchList $watchList */
$watchList = $this->watchListRepository->findOneBy(['token' => $message->watchListToken]);
@@ -61,6 +63,10 @@ final readonly class ProcessWatchListTriggerHandler
try {
$this->RDAPService->registerDomain($domain->getLdhName());
} catch (NotFoundHttpException) {
if (null !== $watchList->getConnector()) {
$this->bus->dispatch(new OrderDomain($watchList->getToken(), $domain->getLdhName(), $updatedAt));
}
} catch (\Throwable $e) {
$this->logger->error('An update error email is sent to user {username}.', [
'username' => $watchList->getUser()->getUserIdentifier(),
@@ -71,7 +77,7 @@ final readonly class ProcessWatchListTriggerHandler
$this->mailer->send($email->getMessage());
}
$this->bus->dispatch(new ProcessDomainTrigger($watchList->getToken(), $domain->getLdhName(), $updatedAt));
$this->bus->dispatch(new SendDomainEventNotif($watchList->getToken(), $domain->getLdhName(), $updatedAt));
}
}
}

View File

@@ -0,0 +1,52 @@
<?php
namespace App\Service;
use App\Config\WebhookScheme;
use App\Entity\WatchList;
use Psr\Log\LoggerInterface;
use Symfony\Component\Notifier\Notification\ChatNotificationInterface;
use Symfony\Component\Notifier\Recipient\Recipient;
use Symfony\Component\Notifier\Transport\AbstractTransportFactory;
use Symfony\Component\Notifier\Transport\Dsn;
readonly class ChatNotificationService
{
public function __construct(
private LoggerInterface $logger
) {
}
public function sendChatNotification(WatchList $watchList, ChatNotificationInterface $notification): void
{
$webhookDsn = $watchList->getWebhookDsn();
if (null !== $webhookDsn && 0 !== count($webhookDsn)) {
foreach ($webhookDsn as $dsnString) {
$dsn = new Dsn($dsnString);
$scheme = $dsn->getScheme();
$webhookScheme = WebhookScheme::tryFrom($scheme);
if (null !== $webhookScheme) {
$transportFactoryClass = $webhookScheme->getChatTransportFactory();
/** @var AbstractTransportFactory $transportFactory */
$transportFactory = new $transportFactoryClass();
try {
$transportFactory->create($dsn)->send($notification->asChatMessage(new Recipient()));
$this->logger->info('Chat message sent with {schema} for Watchlist {token}',
[
'scheme' => $webhookScheme->name,
'token' => $watchList->getToken(),
]);
} catch (\Throwable) {
$this->logger->error('Unable to send a chat message to {scheme} for Watchlist {token}',
[
'scheme' => $webhookScheme->name,
'token' => $watchList->getToken(),
]);
}
}
}
}
}
}