You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Services/Cloud/CloudNotificationDeliverySe...

74 lines
2.5 KiB
PHP

<?php
namespace App\Services\Cloud;
/** Fair, failure-isolated dispatcher for customer notification outboxes. */
final class CloudNotificationDeliveryService
{
private readonly \Closure $maintenanceTick;
private readonly \Closure $compensationTick;
private readonly \Closure $abuseAlertTick;
private int $firstChannel = 0;
private array $errors = [];
public function __construct(
?callable $maintenanceTick = null,
?callable $compensationTick = null,
?callable $abuseAlertTick = null
) {
if ($maintenanceTick === null) {
$maintenance = new CloudMaintenanceNoticeDeliveryService();
$maintenanceTick = [$maintenance, 'tick'];
}
if ($compensationTick === null) {
$compensation = new CloudServiceCompensationNotificationService();
$compensationTick = [$compensation, 'tick'];
}
if ($abuseAlertTick === null) {
$abuseAlerts = new CloudAbuseAlertDeliveryService();
$abuseAlertTick = [$abuseAlerts, 'tick'];
}
$this->maintenanceTick = \Closure::fromCallable($maintenanceTick);
$this->compensationTick = \Closure::fromCallable($compensationTick);
$this->abuseAlertTick = \Closure::fromCallable($abuseAlertTick);
}
public function tick(): bool
{
$this->errors = [];
$catalog = [
['maintenance_notification_failed', $this->maintenanceTick],
['notification_failed', $this->compensationTick],
['abuse_alert_notification_failed', $this->abuseAlertTick],
];
$channels = [];
for ($offset = 0; $offset < count($catalog); $offset++) {
$channels[] = $catalog[
($this->firstChannel + $offset) % count($catalog)
];
}
$this->firstChannel = ($this->firstChannel + 1) % count($catalog);
$worked = false;
foreach ($channels as [$errorCode, $tick]) {
try {
$worked = $tick() === true || $worked;
} catch (\Throwable $error) {
$this->errors[] = $errorCode;
fwrite(
STDERR,
'cloud notification channel temporarily unavailable: '
. $errorCode . PHP_EOL
);
}
}
return $worked;
}
/** @return list<string> */
public function observationErrors(): array
{
return $this->errors;
}
}