*/ 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(); $lvl1 = null; $lvl2 = null; $held2 = false; $lvl3 = null; $held3 = false; $key = null; $ttl = null; $wait = null; $recordingLock = new class ($innerLock, $store, $lvl1, $lvl3, $held3, $key, $ttl, $wait) implements Lock { public function __construct( private readonly Lock $inner, private readonly ArrayStore $store, public ?int &$lvl1, public ?int &$lvl3, public bool &$held3, public ?string &$key, public ?int &$ttl, public ?int &$wait, ) { } #[\Override] public function synchronize( string $key, callable $callback, int $ttlSeconds = 30, int $waitSeconds = 10, ): mixed { $this->key = $key; $this->ttl = $ttlSeconds; $this->wait = $waitSeconds; $this->lvl1 = DB::transactionLevel(); return $this->inner->synchronize( key: $key, callback: function () use ($callback, $key, $ttlSeconds): mixed { $result = $callback(); $this->lvl3 = DB::transactionLevel(); $this->held3 = ! $this->store->lock($key, $ttlSeconds)->get(); return $result; }, ttlSeconds: $ttlSeconds, waitSeconds: $waitSeconds, ); } }; $action = new #[Locked(ttlSeconds: 45, waitSeconds: 7)] class ($store, $lvl2, $held2) implements Action, ProvidesLockKey { public function __construct( private readonly ArrayStore $store, public ?int &$lvl2, public bool &$held2, ) { } #[\Override] public function lockKey(ActionInput $input): string { return 'test:lock:order'; } #[\Override] public function __invoke(ActionInput $input): string { $this->lvl2 = DB::transactionLevel(); $this->held2 = ! $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($key)->toBe('test:lock:order') ->and($ttl)->toBe(45) ->and($wait)->toBe(7) ->and($lvl1)->toBe($initialLevel) ->and($lvl2)->toBe($initialLevel + 1) ->and($held2)->toBeTrue() ->and($lvl3)->toBe($initialLevel) ->and($held3)->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( public 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, public 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( public 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( public 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 { assert(is_string($result)); $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( public 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( public 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( public bool &$onSuccessCalled, public ?\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'); $ok = false; $free = false; $action = new #[Locked(key: 'test:locked:failure')] class ($ok, $free, $store) implements Action, HandlesFailure, HandlesSuccess { public function __construct( public bool &$ok, public bool &$free, 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->free = (bool) $lock->get(); if ($this->free) { $lock->release(); } } #[\Override] public function onSuccess(ActionInput $input, mixed $result): void { $this->ok = 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($ok)->toBeFalse() ->and($free)->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( public ?\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); }); it('runs WithoutTransaction action outside DB transaction and flushes events dispatched inside onSuccess', function (): void { // GIVEN $lock = \Mockery::mock(Lock::class); $lock->shouldNotReceive('synchronize'); $logger = \Mockery::mock(LoggerInterface::class); $logger->shouldIgnoreMissing(); $postHookEvent = new class () implements Event { }; $eventDispatcher = \Mockery::mock(LaravelDomainEventDispatcher::class); $eventDispatcher->shouldReceive('beginBuffering')->once()->ordered(); $eventDispatcher->shouldReceive('flush')->once()->ordered(); $eventDispatcher->shouldReceive('dispatch')->once()->with($postHookEvent)->ordered(); $txLevel = null; $action = new #[WithoutTransaction] class ($txLevel, $postHookEvent, $eventDispatcher) implements Action, HandlesSuccess { public function __construct( public ?int &$txLevel, private readonly Event $event, private readonly LaravelDomainEventDispatcher $dispatcher, ) { } #[\Override] public function __invoke(ActionInput $input): string { $this->txLevel = DB::transactionLevel(); return 'exported'; } #[\Override] public function onSuccess(ActionInput $input, mixed $result): void { $this->dispatcher->dispatch($this->event); } }; $input = new class () implements ActionInput { }; $executor = new ActionExecutorService($lock, $logger, $eventDispatcher); $baseTx = DB::transactionLevel(); // WHEN $result = $executor->execute($action, $input); // THEN expect($result)->toBe('exported') ->and($txLevel)->toBe($baseTx); }); });