*/ 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())); $eventDispatcher = new LaravelDomainEventDispatcher(); $executor = new ActionExecutorService($lock, $logger, $eventDispatcher); // 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 */ 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())); $eventDispatcher = new LaravelDomainEventDispatcher(); $executor = new ActionExecutorService($lock, $logger, $eventDispatcher); // 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 { }; $eventDispatcher = new LaravelDomainEventDispatcher(); $executor = new ActionExecutorService($recordingLock, $logger, $eventDispatcher); // 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 { }; $eventDispatcher = new LaravelDomainEventDispatcher(); $executor = new ActionExecutorService($lock, $logger, $eventDispatcher); // 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 { }; $eventDispatcher = new LaravelDomainEventDispatcher(); $executor = new ActionExecutorService($lock, $logger, $eventDispatcher); // 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 */ 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 { }; $eventDispatcher = new LaravelDomainEventDispatcher(); $executor = new ActionExecutorService($lock, $logger, $eventDispatcher); // 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 */ 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 { }; $eventDispatcher = new LaravelDomainEventDispatcher(); $executor = new ActionExecutorService($lock, $logger, $eventDispatcher); // 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'); }); it('flushes buffered events and calls onSucceeded only after transaction commit and lock release', function (): void { // GIVEN $logger = \Mockery::mock(LoggerInterface::class); $logger->shouldIgnoreMissing(); $store = new ArrayStore(); $innerLock = new LaravelCacheLock(new Repository($store)); $sequence = []; $recordingLock = new class ($innerLock, $sequence) implements Lock { /** @param list $sequence */ public function __construct( private readonly Lock $inner, private array &$sequence, ) { } #[\Override] public function synchronize( string $key, callable $callback, int $ttlSeconds = 30, int $waitSeconds = 10, ): mixed { $this->sequence[] = 'lock:acquire'; $result = $this->inner->synchronize($key, $callback, $ttlSeconds, $waitSeconds); $this->sequence[] = 'lock:release'; return $result; } }; $eventDispatcher = new class ($sequence) extends LaravelDomainEventDispatcher { /** @param list $sequence */ public function __construct( private array &$sequence, ) { } #[\Override] public function beginBuffering(): void { $this->sequence[] = 'events:begin'; } #[\Override] public function dispatch(Event $event): void { $this->sequence[] = 'events:dispatch'; } #[\Override] public function flush(): void { $this->sequence[] = 'events:flush'; } #[\Override] public function discard(): void { $this->sequence[] = 'events:discard'; } }; $action = new #[Locked(key: 'test:post-commit')] class ($sequence, $eventDispatcher) implements Action, HandlesSuccess { /** @param list $sequence */ public function __construct( private array &$sequence, private readonly LaravelDomainEventDispatcher $eventDispatcher, ) { } #[\Override] public function __invoke(ActionInput $input): string { $this->sequence[] = 'action:invoke'; $this->eventDispatcher->dispatch(new class () implements Event { }); return 'ok'; } #[\Override] public function onSuccess(ActionInput $input, mixed $result): void { $this->sequence[] = "action:onSuccess:{$result}"; } }; $input = new class () implements ActionInput { }; $executor = new ActionExecutorService($recordingLock, $logger, $eventDispatcher); // WHEN $result = $executor->execute($action, $input); // THEN expect($result)->toBe('ok') ->and($sequence)->toBe([ 'lock:acquire', 'events:begin', 'action:invoke', 'events:dispatch', 'lock:release', 'events:flush', 'action:onSuccess:ok', ]); }); it('discards buffered events and skips onSuccess when action throws', function (): void { // GIVEN $logger = \Mockery::mock(LoggerInterface::class); $logger->shouldIgnoreMissing(); $lock = new LaravelCacheLock(new Repository(new ArrayStore())); $eventDispatcher = \Mockery::mock(LaravelDomainEventDispatcher::class); $eventDispatcher->shouldReceive('beginBuffering')->once(); $eventDispatcher->shouldReceive('discard')->once(); $eventDispatcher->shouldNotReceive('flush'); $onSuccessCalled = false; $action = new class ($onSuccessCalled) implements Action, HandlesSuccess { public function __construct( private bool &$onSuccessCalled, ) { } #[\Override] public function __invoke(ActionInput $input): never { throw new \RuntimeException('Boom'); } #[\Override] public function onSuccess(ActionInput $input, mixed $result): void { $this->onSuccessCalled = true; } }; $input = new class () implements ActionInput { }; $executor = new ActionExecutorService($lock, $logger, $eventDispatcher); // WHEN expect(fn () => $executor->execute($action, $input)) // THEN ->toThrow(\RuntimeException::class, 'Boom'); expect($onSuccessCalled)->toBeFalse(); }); it('skips flush and onSuccess when lock timeout occurs and HandlesLockTimeout handles it', function (): void { // GIVEN $logger = \Mockery::mock(LoggerInterface::class); $logger->shouldIgnoreMissing(); $lock = \Mockery::mock(Lock::class); $lock->shouldReceive('synchronize') ->once() ->andThrow(new LockTimeoutException('Busy')); $eventDispatcher = \Mockery::mock(LaravelDomainEventDispatcher::class); $eventDispatcher->shouldNotReceive('beginBuffering'); $eventDispatcher->shouldNotReceive('flush'); $eventDispatcher->shouldNotReceive('discard'); $onSuccessCalled = false; $action = new #[Locked(key: 'test:timeout')] class ($onSuccessCalled) implements Action, HandlesLockTimeout, HandlesSuccess { public function __construct( private bool &$onSuccessCalled, ) { } #[\Override] public function onLockTimeout(ActionInput $input): string { return 'timeout-result'; } #[\Override] public function __invoke(ActionInput $input): string { return 'never'; } #[\Override] public function onSuccess(ActionInput $input, mixed $result): void { $this->onSuccessCalled = true; } }; $input = new class () implements ActionInput { }; $executor = new ActionExecutorService($lock, $logger, $eventDispatcher); // WHEN $result = $executor->execute($action, $input); // THEN expect($result)->toBe('timeout-result') ->and($onSuccessCalled)->toBeFalse(); }); it('rolls back DB writes, discards events, runs onFailure, skips onSuccess, and rethrows when action fails', function (): void { // GIVEN $logger = new class () extends AbstractLogger { /** @var array */ public array $entries = []; #[\Override] public function log($level, string | \Stringable $message, array $context = []): void { $this->entries[] = [ 'level' => $level, 'message' => (string) $message, ]; } }; $lock = new LaravelCacheLock(new Repository(new ArrayStore())); $eventDispatcher = \Mockery::mock(LaravelDomainEventDispatcher::class); $eventDispatcher->shouldReceive('beginBuffering')->once(); $eventDispatcher->shouldReceive('discard')->once(); $eventDispatcher->shouldNotReceive('flush'); $onSuccessCalled = false; $capturedException = null; $action = new class ($onSuccessCalled, $capturedException) implements Action, HandlesFailure, HandlesSuccess { public function __construct( private bool &$onSuccessCalled, private ?\Throwable &$capturedException, ) { } #[\Override] public function __invoke(ActionInput $input): string { Tag::query()->create([ 'label' => 'Should be rolled back', 'status' => true, ]); throw new \DomainException('Domain failure after DB write'); } #[\Override] public function onFailure(ActionInput $input, \Throwable $exception): void { $this->capturedException = $exception; } #[\Override] public function onSuccess(ActionInput $input, mixed $result): void { $this->onSuccessCalled = true; } }; $input = new class () implements ActionInput { }; $executor = new ActionExecutorService($lock, $logger, $eventDispatcher); // WHEN expect(fn () => $executor->execute($action, $input)) // THEN ->toThrow(\DomainException::class, 'Domain failure after DB write'); expect(Tag::query()->where('label', 'Should be rolled back')->exists())->toBeFalse() ->and($onSuccessCalled)->toBeFalse() ->and($capturedException)->toBeInstanceOf(\DomainException::class) ->and($logger->entries)->toHaveCount(2) ->and($logger->entries[1]['level'])->toBe('error'); }); it('rolls back DB writes and calls onFailure after releasing lock when Locked action implements HandlesFailure', function (): void { // GIVEN $logger = \Mockery::mock(LoggerInterface::class); $logger->shouldIgnoreMissing(); $store = new ArrayStore(); $lock = new LaravelCacheLock(new Repository($store)); $eventDispatcher = \Mockery::mock(LaravelDomainEventDispatcher::class); $eventDispatcher->shouldReceive('beginBuffering')->once(); $eventDispatcher->shouldReceive('discard')->once(); $eventDispatcher->shouldNotReceive('flush'); $onSuccessCalled = false; $lockReleasedInHook = false; $action = new #[Locked(key: 'test:locked:failure')] class ($onSuccessCalled, $lockReleasedInHook, $store) implements Action, HandlesFailure, HandlesSuccess { public function __construct( private bool &$onSuccessCalled, private bool &$lockReleasedInHook, private readonly ArrayStore $store, ) { } #[\Override] public function __invoke(ActionInput $input): string { Tag::query()->create([ 'label' => 'Locked rollback test', 'status' => true, ]); throw new \DomainException('Locked domain failure'); } #[\Override] public function onFailure(ActionInput $input, \Throwable $exception): void { $lock = $this->store->lock('test:locked:failure', 30); $this->lockReleasedInHook = $lock->get(); if ($this->lockReleasedInHook) { $lock->release(); } } #[\Override] public function onSuccess(ActionInput $input, mixed $result): void { $this->onSuccessCalled = true; } }; $input = new class () implements ActionInput { }; $executor = new ActionExecutorService($lock, $logger, $eventDispatcher); // WHEN expect(fn () => $executor->execute($action, $input)) // THEN ->toThrow(\DomainException::class, 'Locked domain failure'); expect(Tag::query()->where('label', 'Locked rollback test')->exists())->toBeFalse() ->and($onSuccessCalled)->toBeFalse() ->and($lockReleasedInHook)->toBeTrue() ->and($store->lock('test:locked:failure', 30)->get())->toBeTrue(); }); it('calls onFailure and rethrows LockTimeoutException when Locked action does not implement HandlesLockTimeout', function (): void { // GIVEN $logger = \Mockery::mock(LoggerInterface::class); $logger->shouldIgnoreMissing(); $lock = \Mockery::mock(Lock::class); $lock->shouldReceive('synchronize') ->once() ->andThrow(new LockTimeoutException('Busy')); $eventDispatcher = \Mockery::mock(LaravelDomainEventDispatcher::class); $eventDispatcher->shouldNotReceive('beginBuffering'); $eventDispatcher->shouldNotReceive('flush'); $eventDispatcher->shouldNotReceive('discard'); $capturedException = null; $action = new #[Locked(key: 'test:timeout:failure')] class ($capturedException) implements Action, HandlesFailure { public function __construct( private ?\Throwable &$capturedException, ) { } #[\Override] public function __invoke(ActionInput $input): string { return 'never'; } #[\Override] public function onFailure(ActionInput $input, \Throwable $exception): void { $this->capturedException = $exception; } }; $input = new class () implements ActionInput { }; $executor = new ActionExecutorService($lock, $logger, $eventDispatcher); // WHEN expect(fn () => $executor->execute($action, $input)) // THEN ->toThrow(LockTimeoutException::class, 'Busy'); expect($capturedException)->toBeInstanceOf(LockTimeoutException::class); }); });