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...

65 lines
2.1 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 bool $maintenanceFirst = true;
private array $errors = [];
public function __construct(
?callable $maintenanceTick = null,
?callable $compensationTick = null
) {
if ($maintenanceTick === null) {
$maintenance = new CloudMaintenanceNoticeDeliveryService();
$maintenanceTick = [$maintenance, 'tick'];
}
if ($compensationTick === null) {
$compensation = new CloudServiceCompensationNotificationService();
$compensationTick = [$compensation, 'tick'];
}
$this->maintenanceTick = \Closure::fromCallable($maintenanceTick);
$this->compensationTick = \Closure::fromCallable($compensationTick);
}
public function tick(): bool
{
$this->errors = [];
$channels = $this->maintenanceFirst
? [
['maintenance_notification_failed', $this->maintenanceTick],
['notification_failed', $this->compensationTick],
]
: [
['notification_failed', $this->compensationTick],
['maintenance_notification_failed', $this->maintenanceTick],
];
$this->maintenanceFirst = !$this->maintenanceFirst;
$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;
}
}