382 lines
13 KiB
PHP
382 lines
13 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
use App\Attributes\Locked;
|
|
use App\Contracts\Action;
|
|
use App\Contracts\ActionInput;
|
|
use App\Contracts\HandlesLockTimeout;
|
|
use App\Contracts\ProvidesLockKey;
|
|
use App\Services\ActionExecutorService;
|
|
use Illuminate\Cache\ArrayStore;
|
|
use Illuminate\Cache\Repository;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Infrastructure\Adapters\Locks\LaravelCacheLock;
|
|
use Psr\Log\AbstractLogger;
|
|
use Psr\Log\LoggerInterface;
|
|
use Shared\Concurrency\Lock;
|
|
use Shared\Concurrency\LockTimeoutException;
|
|
|
|
describe('ActionExecutorService', function (): void {
|
|
it('executes action in transaction and logs success', function (): void {
|
|
// GIVEN
|
|
$logger = new class () extends AbstractLogger
|
|
{
|
|
/** @var array<int, string> */
|
|
public array $logs = [];
|
|
|
|
#[\Override]
|
|
public function log($level, string | \Stringable $message, array $context = []): void
|
|
{
|
|
$this->logs[] = (string) $message;
|
|
}
|
|
};
|
|
|
|
$action = new class () implements Action
|
|
{
|
|
#[\Override]
|
|
public function __invoke(ActionInput $input): string
|
|
{
|
|
return 'done';
|
|
}
|
|
};
|
|
|
|
$input = new class () implements ActionInput
|
|
{
|
|
};
|
|
$lock = new LaravelCacheLock(new Repository(new ArrayStore()));
|
|
$executor = new ActionExecutorService($lock, $logger);
|
|
|
|
// WHEN
|
|
$result = $executor->execute($action, $input);
|
|
|
|
// THEN
|
|
expect($result)->toBe('done')
|
|
->and($logger->logs)->toHaveCount(2)
|
|
->and($logger->logs[0])->toContain('Executing')
|
|
->and($logger->logs[1])->toContain('Succeeded');
|
|
});
|
|
|
|
it('logs error and rethrows when action fails', function (): void {
|
|
// GIVEN
|
|
$logger = new class () extends AbstractLogger
|
|
{
|
|
/** @var array<int, string> */
|
|
public array $logs = [];
|
|
|
|
#[\Override]
|
|
public function log($level, string | \Stringable $message, array $context = []): void
|
|
{
|
|
$this->logs[] = (string) $message;
|
|
}
|
|
};
|
|
|
|
$action = new class () implements Action
|
|
{
|
|
#[\Override]
|
|
public function __invoke(ActionInput $input): never
|
|
{
|
|
throw new \RuntimeException('Database failure');
|
|
}
|
|
};
|
|
|
|
$input = new class () implements ActionInput
|
|
{
|
|
};
|
|
$lock = new LaravelCacheLock(new Repository(new ArrayStore()));
|
|
$executor = new ActionExecutorService($lock, $logger);
|
|
|
|
// WHEN
|
|
expect(fn () => $executor->execute($action, $input))
|
|
// THEN
|
|
->toThrow(\RuntimeException::class, 'Database failure');
|
|
|
|
expect($logger->logs)->toHaveCount(2)
|
|
->and($logger->logs[0])->toContain('Executing')
|
|
->and($logger->logs[1])->toContain('Failed');
|
|
});
|
|
|
|
it('acquires lock before DB transaction starts and releases it after transaction commits', function (): void {
|
|
// GIVEN
|
|
$logger = \Mockery::mock(LoggerInterface::class);
|
|
$logger->shouldIgnoreMissing();
|
|
$store = new ArrayStore();
|
|
$innerLock = new LaravelCacheLock(new Repository($store));
|
|
$initialLevel = DB::transactionLevel();
|
|
$levelAtAcquire = null;
|
|
$levelInsideAction = null;
|
|
$lockHeldInsideAction = false;
|
|
$levelAfterCommit = null;
|
|
$lockHeldAfterCommit = false;
|
|
$capturedKey = null;
|
|
$capturedTtl = null;
|
|
$capturedWait = null;
|
|
|
|
$recordingLock = new class ($innerLock, $store, $levelAtAcquire, $levelAfterCommit, $lockHeldAfterCommit, $capturedKey, $capturedTtl, $capturedWait) implements Lock
|
|
{
|
|
public function __construct(
|
|
private readonly Lock $inner,
|
|
private readonly ArrayStore $store,
|
|
private ?int &$levelAtAcquire,
|
|
private ?int &$levelAfterCommit,
|
|
private bool &$lockHeldAfterCommit,
|
|
private ?string &$capturedKey,
|
|
private ?int &$capturedTtl,
|
|
private ?int &$capturedWait,
|
|
) {
|
|
}
|
|
|
|
#[\Override]
|
|
public function synchronize(
|
|
string $key,
|
|
callable $callback,
|
|
int $ttlSeconds = 30,
|
|
int $waitSeconds = 10,
|
|
): mixed {
|
|
$this->capturedKey = $key;
|
|
$this->capturedTtl = $ttlSeconds;
|
|
$this->capturedWait = $waitSeconds;
|
|
$this->levelAtAcquire = DB::transactionLevel();
|
|
|
|
return $this->inner->synchronize(
|
|
key: $key,
|
|
callback: function () use ($callback, $key, $ttlSeconds): mixed {
|
|
$result = $callback();
|
|
|
|
$this->levelAfterCommit = DB::transactionLevel();
|
|
$this->lockHeldAfterCommit = ! $this->store->lock($key, $ttlSeconds)->get();
|
|
|
|
return $result;
|
|
},
|
|
ttlSeconds: $ttlSeconds,
|
|
waitSeconds: $waitSeconds,
|
|
);
|
|
}
|
|
};
|
|
|
|
$action = new #[Locked(ttlSeconds: 45, waitSeconds: 7)] class ($store, $levelInsideAction, $lockHeldInsideAction) implements Action, ProvidesLockKey
|
|
{
|
|
public function __construct(
|
|
private readonly ArrayStore $store,
|
|
private ?int &$levelInsideAction,
|
|
private bool &$lockHeldInsideAction,
|
|
) {
|
|
}
|
|
|
|
#[\Override]
|
|
public function lockKey(ActionInput $input): string
|
|
{
|
|
return 'test:lock:order';
|
|
}
|
|
|
|
#[\Override]
|
|
public function __invoke(ActionInput $input): string
|
|
{
|
|
$this->levelInsideAction = DB::transactionLevel();
|
|
$this->lockHeldInsideAction = ! $this->store->lock('test:lock:order', 45)->get();
|
|
|
|
return 'committed';
|
|
}
|
|
};
|
|
|
|
$input = new class () implements ActionInput
|
|
{
|
|
};
|
|
$executor = new ActionExecutorService($recordingLock, $logger);
|
|
|
|
// WHEN
|
|
$result = $executor->execute($action, $input);
|
|
|
|
// THEN
|
|
expect($result)->toBe('committed')
|
|
->and($capturedKey)->toBe('test:lock:order')
|
|
->and($capturedTtl)->toBe(45)
|
|
->and($capturedWait)->toBe(7)
|
|
->and($levelAtAcquire)->toBe($initialLevel)
|
|
->and($levelInsideAction)->toBe($initialLevel + 1)
|
|
->and($lockHeldInsideAction)->toBeTrue()
|
|
->and($levelAfterCommit)->toBe($initialLevel)
|
|
->and($lockHeldAfterCommit)->toBeTrue()
|
|
->and($store->lock('test:lock:order', 45)->get())->toBeTrue();
|
|
});
|
|
|
|
it('uses Locked attribute key when ProvidesLockKey is not implemented', function (): void {
|
|
// GIVEN
|
|
$logger = \Mockery::mock(LoggerInterface::class);
|
|
$logger->shouldIgnoreMissing();
|
|
$lock = \Mockery::mock(Lock::class);
|
|
$lock->shouldReceive('synchronize')
|
|
->once()
|
|
->with('custom-key', \Mockery::type(\Closure::class), 30, 10)
|
|
->andReturnUsing(static fn (string $key, callable $callback): mixed => $callback());
|
|
|
|
$action = new #[Locked(key: 'custom-key')] class () implements Action
|
|
{
|
|
#[\Override]
|
|
public function __invoke(ActionInput $input): string
|
|
{
|
|
return 'custom-key-result';
|
|
}
|
|
};
|
|
|
|
$input = new class () implements ActionInput
|
|
{
|
|
};
|
|
$executor = new ActionExecutorService($lock, $logger);
|
|
|
|
// WHEN
|
|
$result = $executor->execute($action, $input);
|
|
|
|
// THEN
|
|
expect($result)->toBe('custom-key-result');
|
|
});
|
|
|
|
it('defaults lock key to action FQCN when neither Locked key nor ProvidesLockKey is provided', function (): void {
|
|
// GIVEN
|
|
$logger = \Mockery::mock(LoggerInterface::class);
|
|
$logger->shouldIgnoreMissing();
|
|
$action = new #[Locked] class () implements Action
|
|
{
|
|
#[\Override]
|
|
public function __invoke(ActionInput $input): string
|
|
{
|
|
return 'fqcn-key-result';
|
|
}
|
|
};
|
|
|
|
$lock = \Mockery::mock(Lock::class);
|
|
$lock->shouldReceive('synchronize')
|
|
->once()
|
|
->with($action::class, \Mockery::type(\Closure::class), 30, 10)
|
|
->andReturnUsing(static fn (string $key, callable $callback): mixed => $callback());
|
|
|
|
$input = new class () implements ActionInput
|
|
{
|
|
};
|
|
$executor = new ActionExecutorService($lock, $logger);
|
|
|
|
// WHEN
|
|
$result = $executor->execute($action, $input);
|
|
|
|
// THEN
|
|
expect($result)->toBe('fqcn-key-result');
|
|
});
|
|
|
|
it('returns onLockTimeout, logs warning, and skips action on LockTimeoutException when HandlesLockTimeout is implemented', function (): void {
|
|
// GIVEN
|
|
$logger = new class () extends AbstractLogger
|
|
{
|
|
/** @var array<int, array{level: mixed, message: string}> */
|
|
public array $entries = [];
|
|
|
|
#[\Override]
|
|
public function log($level, string | \Stringable $message, array $context = []): void
|
|
{
|
|
$this->entries[] = [
|
|
'level' => $level,
|
|
'message' => (string) $message,
|
|
];
|
|
}
|
|
};
|
|
|
|
$lock = \Mockery::mock(Lock::class);
|
|
$lock->shouldReceive('synchronize')
|
|
->once()
|
|
->with('test:lock:busy', \Mockery::type(\Closure::class), 30, 10)
|
|
->andThrow(new LockTimeoutException('Timed out waiting for lock'));
|
|
|
|
$invoked = false;
|
|
$action = new #[Locked(ttlSeconds: 30, waitSeconds: 10)] class ($invoked) implements Action, HandlesLockTimeout, ProvidesLockKey
|
|
{
|
|
public function __construct(
|
|
private bool &$invoked,
|
|
) {
|
|
}
|
|
|
|
#[\Override]
|
|
public function lockKey(ActionInput $input): string
|
|
{
|
|
return 'test:lock:busy';
|
|
}
|
|
|
|
#[\Override]
|
|
public function onLockTimeout(ActionInput $input): string
|
|
{
|
|
return 'lock-timeout-output';
|
|
}
|
|
|
|
#[\Override]
|
|
public function __invoke(ActionInput $input): string
|
|
{
|
|
$this->invoked = true;
|
|
|
|
return 'should-not-run';
|
|
}
|
|
};
|
|
|
|
$input = new class () implements ActionInput
|
|
{
|
|
};
|
|
$executor = new ActionExecutorService($lock, $logger);
|
|
|
|
// WHEN
|
|
$result = $executor->execute($action, $input);
|
|
|
|
// THEN
|
|
expect($result)->toBe('lock-timeout-output')
|
|
->and($invoked)->toBeFalse()
|
|
->and($logger->entries)->toHaveCount(2)
|
|
->and($logger->entries[0]['message'])->toContain('Executing')
|
|
->and($logger->entries[1]['level'])->toBe('warning')
|
|
->and($logger->entries[1]['message'])->toContain('Lock timeout');
|
|
});
|
|
|
|
it('rethrows LockTimeoutException and logs error when HandlesLockTimeout is not implemented', function (): void {
|
|
// GIVEN
|
|
$logger = new class () extends AbstractLogger
|
|
{
|
|
/** @var array<int, array{level: mixed, message: string}> */
|
|
public array $entries = [];
|
|
|
|
#[\Override]
|
|
public function log($level, string | \Stringable $message, array $context = []): void
|
|
{
|
|
$this->entries[] = [
|
|
'level' => $level,
|
|
'message' => (string) $message,
|
|
];
|
|
}
|
|
};
|
|
|
|
$lock = \Mockery::mock(Lock::class);
|
|
$lock->shouldReceive('synchronize')
|
|
->once()
|
|
->with('test:lock:unhandled', \Mockery::type(\Closure::class), 30, 10)
|
|
->andThrow(new LockTimeoutException('Timed out waiting for lock'));
|
|
|
|
$action = new #[Locked(key: 'test:lock:unhandled')] class () implements Action
|
|
{
|
|
#[\Override]
|
|
public function __invoke(ActionInput $input): string
|
|
{
|
|
return 'should-not-run';
|
|
}
|
|
};
|
|
|
|
$input = new class () implements ActionInput
|
|
{
|
|
};
|
|
$executor = new ActionExecutorService($lock, $logger);
|
|
|
|
// WHEN
|
|
expect(fn () => $executor->execute($action, $input))
|
|
// THEN
|
|
->toThrow(LockTimeoutException::class, 'Timed out waiting for lock');
|
|
|
|
expect($logger->entries)->toHaveCount(2)
|
|
->and($logger->entries[0]['level'])->toBe('info')
|
|
->and($logger->entries[0]['message'])->toContain('Executing')
|
|
->and($logger->entries[1]['level'])->toBe('error')
|
|
->and($logger->entries[1]['message'])->toContain('Failed');
|
|
});
|
|
});
|