ldc-cocotte/app/Services/ActionExecutorService.php

275 lines
7.8 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Services;
use App\Attributes\Locked;
use App\Attributes\WithoutTransaction;
use App\Contracts\Action;
use App\Contracts\ActionInput;
use App\Contracts\Executor;
use App\Contracts\HandlesFailure;
use App\Contracts\HandlesLockTimeout;
use App\Contracts\HandlesSuccess;
use App\Contracts\ProvidesLockKey;
use App\Contracts\Query;
use App\Contracts\QueryInput;
use Illuminate\Support\Facades\DB;
use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher;
use Psr\Log\LoggerInterface;
use Shared\Concurrency\Lock;
use Shared\Concurrency\LockTimeoutException;
final class ActionExecutorService implements Executor
{
public function __construct(
private readonly Lock $lock,
private readonly LoggerInterface $logger,
private readonly LaravelDomainEventDispatcher $eventDispatcher,
) {
}
#[\Override]
public function execute(Action | Query $executable, ActionInput | QueryInput $input): mixed
{
$executableClass = $executable::class;
$actionName = class_basename($executableClass);
$type = $executable instanceof Action ? 'Action' : 'Query';
$this->logger->info("[{$type}] Executing {$actionName}", [
'action' => $executableClass,
'input' => $input::class,
]);
try {
if ($executable instanceof Action) {
$this->assertInputIsAction($input);
$lockedAttribute = $this->resolveLockedAttribute($executable);
if ($lockedAttribute !== null) {
return $this->executeWithLock($executable, $input, $actionName, $lockedAttribute);
}
return $this->executeWithoutLock($executable, $input, $actionName);
}
$this->assertInputIsQuery($input);
return $this->executeQuery(
$executable,
$input,
$actionName
);
} catch (\Throwable $e) {
$this->logger->error("[{$type}] Failed {$actionName}: {$e->getMessage()}", [
'action' => $executableClass,
'input' => $input::class,
'message' => $e->getMessage(),
'exception' => $e,
]);
throw $e;
}
}
/**
* @template TQuery of Query
* @template TQueryInput of QueryInput
*
* @param TQuery $executable
* @param TQueryInput $input
*/
private function executeQuery(Query $executable, QueryInput $input, string $actionName): mixed
{
$result = $executable($input);
$this->logger->info("[Query] Succeeded {$actionName}");
return $result;
}
/**
* @template TAction of Action
*
* @param TAction $executable
*/
private function resolveLockedAttribute(Action $executable): ?Locked
{
$reflection = new \ReflectionClass($executable);
$attributes = $reflection->getAttributes(Locked::class);
return ($attributes[0] ?? null)?->newInstance();
}
/**
* @template TAction of Action
*
* @param TAction $executable
*/
private function hasWithoutTransactionAttribute(Action $executable): bool
{
$reflection = new \ReflectionClass($executable);
return $reflection->getAttributes(WithoutTransaction::class) !== [];
}
/**
* @template TAction of Action
* @template TActionInput of ActionInput
*
* @param TAction $executable
* @param TActionInput $input
*/
private function executeWithLock(
Action $executable,
ActionInput $input,
string $actionName,
Locked $locked,
): mixed {
$lockKey = $executable instanceof ProvidesLockKey
? $executable->lockKey($input)
: ($locked->key ?? $executable::class);
try {
$result = $this->lock->synchronize(
key: $lockKey,
callback: fn (): mixed => $this->executeWithinTransaction($executable, $input, $actionName),
ttlSeconds: $locked->ttlSeconds,
waitSeconds: $locked->waitSeconds,
);
} catch (LockTimeoutException $e) {
if ($executable instanceof HandlesLockTimeout) {
$this->logger->warning("[Action] Lock timeout {$actionName}", [
'action' => $executable::class,
'input' => $input::class,
'lockKey' => $lockKey,
'message' => $e->getMessage(),
]);
return $executable->onLockTimeout($input);
}
$this->runFailureHook($executable, $input, $e);
throw $e;
} catch (\Throwable $e) {
$this->runFailureHook($executable, $input, $e);
throw $e;
}
$this->runPostCommitHooks($executable, $input, $result);
return $result;
}
/**
* @template TAction of Action
* @template TActionInput of ActionInput
*
* @param TAction $executable
* @param TActionInput $input
*/
private function executeWithoutLock(
Action $executable,
ActionInput $input,
string $actionName,
): mixed {
try {
$result = $this->executeWithinTransaction($executable, $input, $actionName);
} catch (\Throwable $e) {
$this->runFailureHook($executable, $input, $e);
throw $e;
}
$this->runPostCommitHooks($executable, $input, $result);
return $result;
}
/**
* @template TAction of Action
* @template TActionInput of ActionInput
*
* @param TAction $executable
* @param TActionInput $input
*/
private function runFailureHook(
Action $executable,
ActionInput $input,
\Throwable $exception,
): void {
if ($executable instanceof HandlesFailure) {
$executable->onFailure($input, $exception);
}
}
/**
* @template TAction of Action
* @template TActionInput of ActionInput
*
* @param TAction $executable
* @param TActionInput $input
*/
private function executeWithinTransaction(Action $executable, ActionInput $input, string $actionName): mixed
{
$this->eventDispatcher->beginBuffering();
$run = function () use ($executable, $input, $actionName): mixed {
$result = $executable($input);
$this->logger->info("[Action] Succeeded {$actionName}");
return $result;
};
try {
return $this->hasWithoutTransactionAttribute($executable)
? $run()
: DB::transaction($run);
} catch (\Throwable $e) {
$this->eventDispatcher->discard();
throw $e;
}
}
/**
* @template TAction of Action
* @template TActionInput of ActionInput
*
* @param TAction $executable
* @param TActionInput $input
*/
private function runPostCommitHooks(Action $executable, ActionInput $input, mixed $result): void
{
$this->eventDispatcher->flush();
if ($executable instanceof HandlesSuccess) {
$executable->onSuccess($input, $result);
}
}
/**
* @psalm-assert QueryInput $input
*/
private function assertInputIsQuery(mixed $input): void
{
if (! $input instanceof QueryInput) {
throw new \InvalidArgumentException('Input must be an instance of QueryInput.');
}
}
/**
* @psalm-assert ActionInput $input
*/
private function assertInputIsAction(mixed $input): void
{
if (! $input instanceof ActionInput) {
throw new \InvalidArgumentException('Input must be an instance of ActionInput.');
}
}
}