diff --git a/CHANGELOG.md b/CHANGELOG.md index 6c82af6..4183d1f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,31 @@ All notable changes to this project will be documented in this file. This projec ## Unreleased +### Added + +- `FakeUnitOfWork` now has an `executions` property, counting the number of times its `execute()` method has been + called. + +### Changed + +- `FakeUnitOfWork` now records which execution each entry in its `sequence` belongs to, in the format + `execute:/:`, e.g. `execute:2/commit:1`. Previously entries were in the format + `:`, e.g. `commit:1`. As the unit of work manager handles re-attempts itself by executing the unit of + work once per attempt, this makes it possible to distinguish each attempt made by the manager. Tests that assert the + sequence will need updating to the new format. + +### Fixed + +- [#48](https://github.com/cloudcreativity/php-ddd-modules/issues/48) `UnitOfWorkManager` now allows an after commit + callback to start (and commit) a new unit of work, e.g. by dispatching a command that executes in a unit of work. + Previously this threw an exception, as the manager still considered the committed unit of work to be active. After + commit callbacks are now executed as a single FIFO queue: the after commit callbacks of a unit of work started this + way are added to the end of the queue, and are executed after the callback that started it has returned. Starting a + unit of work while another is executing (i.e. before it has committed) is still not allowed. +- `UnitOfWorkManager` now throws with the message "Cannot queue a before commit callback when not executing a unit of + work." if an after commit callback registers a before commit callback outside of a new unit of work. Previously the + message stated that the unit of work had been committed. + ## [7.0.0] - 2026-11-16 ### Added diff --git a/docs/guide/application/units-of-work.md b/docs/guide/application/units-of-work.md index 408fe06..425425d 100644 --- a/docs/guide/application/units-of-work.md +++ b/docs/guide/application/units-of-work.md @@ -300,6 +300,50 @@ commit callbacks from being executed. Once they have all been executed, if exact thrown. If more than one failed, an `AfterCommitCallbacksFailed` exception is thrown instead. Its `exceptions()` method returns all the exceptions in the order they were thrown, and its previous exception is the first one. +#### After Commit Queue + +After commit callbacks are executed as a FIFO (first in, first out) queue. If an after commit callback registers +another after commit callback, it is added to the end of the queue, rather than being executed immediately. + +An after commit callback can also start a new unit of work, as the previous unit of work has already committed. For +example, it might dispatch a command whose handler executes in a unit of work. The new unit of work executes its before +commit callbacks as normal. However, its after commit callbacks are added to the end of the same queue. So they are +executed after the callback that started the new unit of work has returned. + +```php +$manager->execute(function () use ($manager): void { + // executed first + $manager->afterCommit(function () use ($manager): void { + // starts and commits a new unit of work... + $manager->execute(function () use ($manager): void { + // ...whose after commit callback is added to the end of the queue: executed third. + $manager->afterCommit(function (): void { + // some deferred work. + }); + }); + }); + + // executed second + $manager->afterCommit(function (): void { + // some deferred work. + }); +}); +``` + +As the new unit of work's after commit callbacks are queued, any failure in them is thrown by the outermost call to +`execute()` along with any other after commit failures. It is not thrown by the call that started the new unit of work. + +:::warning +While the queue is FIFO, your after commit callbacks should **never** rely on the order they are executed in, or on +any knowledge of other after commit callbacks. Each callback should be an independent side effect of the committed +work. If one piece of work depends on another, it should be coordinated explicitly - for example, by having one piece +of work trigger the next, rather than relying on the order of the queue. +::: + +Starting a unit of work while another is still executing (i.e. before it has committed) is not allowed, and will throw +an exception. Likewise, an after commit callback cannot register a before commit callback, as the unit of work has +already committed - unless it does so within a new unit of work. + ## Deferring Domain Events When using the unit of work pattern, you **must** use the unit of work aware domain event dispatcher. This coordinates @@ -499,22 +543,40 @@ the fake unit of work. For example, if you wanted to check that the unit of work the second attempt: ```php +use CloudCreativity\Modules\Application\UnitOfWork\UnitOfWorkManager; use CloudCreativity\Modules\Testing\FakeUnitOfWork; $unitOfWork = new FakeUnitOfWork(); +$manager = new UnitOfWorkManager($unitOfWork); -// execute work that uses the unit of work +// execute work that uses the unit of work manager, with two attempts +$this->assertSame(2, $unitOfWork->executions); $this->assertSame(2, $unitOfWork->attempts); $this->assertSame(1, $unitOfWork->commits); $this->assertSame(1, $unitOfWork->rollbacks); -$this->assertSame( - ['attempt:1', 'rollback:1', 'attempt:2', 'commit:2'], - $unitOfWork->sequence, -); +$this->assertSame([ + 'execute:1/attempt:1', + 'execute:1/rollback:1', + 'execute:2/attempt:1', + 'execute:2/commit:1', +], $unitOfWork->sequence); ``` +Each entry in the sequence is in the format `execute:/:`. The execution is the number of the +call to the fake's `execute()` method, and the attempt is the number of the attempt within that call. + +Notice that the two attempts are recorded as two executions, each with a single attempt. This is because the unit of +work manager handles re-attempts itself, executing the fake unit of work once per attempt. The attempt number will +only be greater than one if you call the fake directly with more than one attempt. The `executions`, `attempts`, +`commits` and `rollbacks` properties are all counted across every call to the fake. + +A new unit of work started by an after commit callback is also recorded as a separate execution. For example, if the +work in the above example also started a new unit of work from an after commit callback, the sequence would continue +with `execute:3/attempt:1` and `execute:3/commit:1`. + The fake also implements the `active()` and `inactive()` methods. It is active while the callback passed to `execute()` is running, including on each retry, and inactive before and after. To match the unit of work manager, which does not support nested units of work, the fake throws a `RuntimeException` if `execute()` is called while it is -already active. +already active. As the fake is inactive once it has committed, an after commit callback can start a new unit of work, +in the same way as with a real unit of work. diff --git a/src/Application/UnitOfWork/UnitOfWorkManager.php b/src/Application/UnitOfWork/UnitOfWorkManager.php index ba5cb37..d740f62 100644 --- a/src/Application/UnitOfWork/UnitOfWorkManager.php +++ b/src/Application/UnitOfWork/UnitOfWorkManager.php @@ -19,21 +19,52 @@ use CloudCreativity\Modules\Contracts\Application\UnitOfWork\UnitOfWorkManager as IUnitOfWorkManager; use Throwable; +/** + * Coordinates work that must happen before and after a unit of work commits. + * + * Before commit callbacks are executed within the unit of work, so they are re-attempted with it. After commit + * callbacks are collected while the unit of work is executing, and are only executed once it has committed. + * + * After commit callbacks are executed as a single FIFO queue. A callback that registers another after commit + * callback, or that starts (and commits) a new unit of work, adds to the end of that queue. The queue is drained by + * the outermost call to `execute()`, so a unit of work started by an after commit callback returns before its own + * after commit callbacks are executed. + */ final class UnitOfWorkManager implements IUnitOfWorkManager { /** + * Callbacks to execute before the active unit of work commits. + * * @var callable[] */ private array $beforeCommit = []; /** + * Callbacks to execute after the active unit of work commits. + * + * These are only added to the queue once the unit of work has committed, so that callbacks registered + * by a failed attempt are discarded rather than executed. + * * @var callable[] */ private array $afterCommit = []; + /** + * Whether a unit of work is currently executing, i.e. it has not yet committed or rolled back. + */ private bool $active = false; - private bool $committed = false; + /** + * Whether the queue of after commit callbacks is being drained. + */ + private bool $draining = false; + + /** + * FIFO queue of after commit callbacks, for units of work that have committed. + * + * @var callable[] + */ + private array $queue = []; public function __construct( private readonly UnitOfWork $unitOfWork, @@ -41,6 +72,14 @@ public function __construct( ) { } + /** + * Execute the callback in a unit of work. + * + * A unit of work cannot be started while another is executing. It can however be started by an after commit + * callback, as the previous unit of work has committed at that point. In this scenario, the after commit + * callbacks of the new unit of work are added to the end of the queue that is already being drained, rather + * than being executed before this method returns. + */ public function execute(Closure $callback, int $attempts = 1): mixed { if ($this->active) { @@ -55,14 +94,23 @@ public function execute(Closure $callback, int $attempts = 1): mixed try { $result = $this->retry($callback, $attempts); - // The after commit callbacks are executed outside the retry scope, as the unit of work - // has been committed at this point: so it must not be re-attempted if they fail. - $this->committed = true; - $this->executeAfterCommit(); - return $result; + // The unit of work has committed: so its after commit callbacks are queued outside the retry + // scope. They must not cause the unit of work to be re-attempted if they fail. + $this->queue = [ + ...$this->queue, + ...$this->afterCommit, + ]; } finally { $this->reset(); } + + // If we are already draining, this unit of work was started by an after commit callback. Its own + // after commit callbacks will be executed by the drain that is already in progress. + if (!$this->draining) { + $this->drain(); + } + + return $result; } private function retry(Closure $callback, int $attempts): mixed @@ -97,30 +145,41 @@ private function transaction(Closure $callback): mixed } } + /** + * Reset the state of the unit of work that was executing. + * + * This does not affect the queue of after commit callbacks, which may be being drained for a unit of work + * that has already committed. + */ private function reset(): void { $this->active = false; - $this->committed = false; $this->beforeCommit = []; $this->afterCommit = []; } + /** + * Register a callback to execute before the unit of work commits. + * + * This is only possible while a unit of work is executing. After commit callbacks cannot register before + * commit callbacks, as the unit of work has already committed - unless they do so within a new unit of work. + */ public function beforeCommit(callable $callback): void { - if ($this->active && !$this->committed) { + if ($this->active) { $this->beforeCommit[] = $callback; return; } - if ($this->committed) { - throw new ApplicationException( - 'Cannot queue a before commit callback as unit of work has been committed.', - ); - } - throw new ApplicationException('Cannot queue a before commit callback when not executing a unit of work.'); } + /** + * Register a callback to execute after the unit of work commits. + * + * While a unit of work is executing, the callback is held until it commits. When called by an after commit + * callback (i.e. while the queue is being drained), the callback is added to the end of the queue. + */ public function afterCommit(callable $callback): void { if ($this->active) { @@ -128,6 +187,11 @@ public function afterCommit(callable $callback): void return; } + if ($this->draining) { + $this->queue[] = $callback; + return; + } + throw new ApplicationException('Cannot queue an after commit callback when not executing a unit of work.'); } @@ -139,17 +203,21 @@ private function executeBeforeCommit(): void } /** - * Execute the after commit callbacks. + * Drain the queue of after commit callbacks. * - * As the unit of work has been committed, a failing callback must not prevent the - * remaining callbacks from being executed. If exactly one callback fails, its exception - * is rethrown. If multiple fail, they are wrapped in a single exception. + * Callbacks are executed in FIFO order, including any that are added to the queue while it is being drained. + * + * As the unit of work has been committed, a failing callback must not prevent the remaining callbacks from being + * executed. If exactly one callback fails, its exception is rethrown. If multiple fail, they are wrapped in a + * single exception. This includes failures of after commit callbacks belonging to a unit of work started while + * draining. */ - private function executeAfterCommit(): void + private function drain(): void { + $this->draining = true; $exceptions = []; - while ($callback = array_shift($this->afterCommit)) { + while ($callback = array_shift($this->queue)) { try { $callback(); } catch (Throwable $ex) { @@ -157,6 +225,8 @@ private function executeAfterCommit(): void } } + $this->draining = false; + if (count($exceptions) === 1) { throw $exceptions[0]; } diff --git a/src/Testing/FakeUnitOfWork.php b/src/Testing/FakeUnitOfWork.php index d14af7e..2237083 100644 --- a/src/Testing/FakeUnitOfWork.php +++ b/src/Testing/FakeUnitOfWork.php @@ -20,13 +20,32 @@ final class FakeUnitOfWork implements UnitOfWork { + /** + * The number of times `execute()` has been called, excluding calls that were rejected. + */ + public int $executions = 0; + + /** + * The number of attempts, across every execution. + */ public int $attempts = 0; + /** + * The number of commits, across every execution. + */ public int $commits = 0; + /** + * The number of rollbacks, across every execution. + */ public int $rollbacks = 0; /** + * The sequence of what happened, across every execution. + * + * Each entry is in the format `execute:/:`, where the event is `attempt`, `commit` or + * `rollback`, and the attempt is the attempt number within that execution. + * * @var list */ public array $sequence = []; @@ -57,17 +76,19 @@ public function execute(Closure $callback, int $attempts = 1): mixed throw new RuntimeException('Fake unit of work is already active.'); } + $this->executions++; + for ($i = 1; $i <= $attempts; $i++) { $this->active = true; try { - $this->sequence[] = 'attempt:' . $i; + $this->sequence[] = sprintf('execute:%d/attempt:%d', $this->executions, $i); $this->attempts++; $result = $callback(); - $this->sequence[] = 'commit:' . $i; + $this->sequence[] = sprintf('execute:%d/commit:%d', $this->executions, $i); $this->commits++; return $result; } catch (Throwable $ex) { - $this->sequence[] = 'rollback:' . $i; + $this->sequence[] = sprintf('execute:%d/rollback:%d', $this->executions, $i); $this->rollbacks++; $this->exceptions->report($ex); diff --git a/tests/Integration/Testing/FakeUnitOfWorkManagerTest.php b/tests/Integration/Testing/FakeUnitOfWorkManagerTest.php new file mode 100644 index 0000000..440afad --- /dev/null +++ b/tests/Integration/Testing/FakeUnitOfWorkManagerTest.php @@ -0,0 +1,942 @@ + + */ + private array $log; + + protected function setUp(): void + { + parent::setUp(); + + $this->manager = new UnitOfWorkManager( + $this->unitOfWork = new FakeUnitOfWork(), + $this->reporter = new FakeExceptionReporter(), + ); + + $this->log = []; + } + + protected function tearDown(): void + { + unset($this->manager, $this->unitOfWork, $this->reporter, $this->log); + parent::tearDown(); + } + + // ------------------------------------------------------------------------- + // Executing a unit of work + // ------------------------------------------------------------------------- + + #[Test] + public function it_executes_the_callback_in_the_fake_unit_of_work(): void + { + $actual = $this->manager->execute(fn () => 'result'); + + $this->assertSame('result', $actual); + $this->assertSame(['execute:1/attempt:1', 'execute:1/commit:1'], $this->unitOfWork->sequence); + $this->assertSame(1, $this->unitOfWork->executions); + $this->assertSame(1, $this->unitOfWork->attempts); + $this->assertSame(1, $this->unitOfWork->commits); + $this->assertSame(0, $this->unitOfWork->rollbacks); + $this->assertSame([], $this->unitOfWork->exceptions->reported); + $this->assertSame([], $this->reporter->reported); + } + + #[Test] + public function it_executes_commit_callbacks_at_the_correct_point_in_the_fake_unit_of_work(): void + { + $snapshots = []; + + $this->manager->execute(function () use (&$snapshots): void { + $snapshots['callback'] = [$this->unitOfWork->active(), $this->unitOfWork->sequence]; + $this->manager->afterCommit(function () use (&$snapshots): void { + $snapshots['after'] = [$this->unitOfWork->active(), $this->unitOfWork->sequence]; + }); + $this->manager->beforeCommit(function () use (&$snapshots): void { + $snapshots['before'] = [$this->unitOfWork->active(), $this->unitOfWork->sequence]; + }); + }); + + $this->assertSame([ + 'callback' => [true, ['execute:1/attempt:1']], + 'before' => [true, ['execute:1/attempt:1']], + 'after' => [false, ['execute:1/attempt:1', 'execute:1/commit:1']], + ], $snapshots); + $this->assertTrue($this->unitOfWork->inactive()); + } + + #[Test] + public function it_executes_commit_callbacks_in_order(): void + { + $this->manager->execute(function (): void { + $this->log[] = 'callback'; + $this->manager->beforeCommit($this->record('before1')); + $this->manager->afterCommit($this->record('after1')); + $this->manager->beforeCommit(function (): void { + $this->log[] = 'before2'; + $this->manager->beforeCommit($this->record('before3')); + $this->manager->afterCommit($this->record('after3')); + }); + $this->manager->afterCommit($this->record('after2')); + }); + + $this->assertSame([ + 'callback', + 'before1', + 'before2', + 'before3', + 'after1', + 'after2', + 'after3', + ], $this->log); + $this->assertSame(['execute:1/attempt:1', 'execute:1/commit:1'], $this->unitOfWork->sequence); + } + + #[Test] + public function it_cannot_start_a_unit_of_work_within_an_active_one(): void + { + $actual = null; + + try { + $this->manager->execute(fn () => $this->manager->execute(fn () => 'result')); + } catch (ApplicationException $ex) { + $actual = $ex; + } + + $this->assertInstanceOf(ApplicationException::class, $actual); + $this->assertSame( + 'Not expecting unit of work manager to start a unit of work within an existing one.', + $actual->getMessage(), + ); + $this->assertSame(['execute:1/attempt:1', 'execute:1/rollback:1'], $this->unitOfWork->sequence); + $this->assertSame([$actual], $this->unitOfWork->exceptions->reported); + $this->assertTrue($this->unitOfWork->inactive()); + } + + #[Test] + public function it_cannot_queue_a_before_commit_callback_from_an_after_commit_callback(): void + { + $actual = null; + + try { + $this->manager->execute(function (): void { + $this->manager->afterCommit(fn () => $this->manager->beforeCommit($this->record('before'))); + }); + } catch (ApplicationException $ex) { + $actual = $ex; + } + + $this->assertInstanceOf(ApplicationException::class, $actual); + $this->assertSame( + 'Cannot queue a before commit callback when not executing a unit of work.', + $actual->getMessage(), + ); + $this->assertSame([], $this->log); + $this->assertSame(['execute:1/attempt:1', 'execute:1/commit:1'], $this->unitOfWork->sequence); + } + + // ------------------------------------------------------------------------- + // Rolling back and re-attempting + // ------------------------------------------------------------------------- + + #[Test] + public function it_retries_until_the_fake_unit_of_work_commits(): void + { + $ex1 = new RuntimeException('An error occurred.'); + $ex2 = new RuntimeException('Another error occurred.'); + + $actual = $this->manager->execute($this->failThenSucceed([$ex1, $ex2]), 3); + + $this->assertSame('result', $actual); + $this->assertSame([ + 'execute:1/attempt:1', + 'execute:1/rollback:1', + 'execute:2/attempt:1', + 'execute:2/rollback:1', + 'execute:3/attempt:1', + 'execute:3/commit:1', + ], $this->unitOfWork->sequence); + $this->assertSame(3, $this->unitOfWork->executions); + $this->assertSame(3, $this->unitOfWork->attempts); + $this->assertSame(1, $this->unitOfWork->commits); + $this->assertSame(2, $this->unitOfWork->rollbacks); + $this->assertSame([$ex1, $ex2], $this->unitOfWork->exceptions->reported); + $this->assertSame([$ex1, $ex2], $this->reporter->reported); + } + + #[Test] + public function it_rethrows_the_last_exception_when_every_attempt_fails(): void + { + $ex1 = new RuntimeException('An error occurred.'); + $ex2 = new RuntimeException('Another error occurred.'); + $actual = null; + + try { + $this->manager->execute($this->failThenSucceed([$ex1, $ex2]), 2); + } catch (RuntimeException $ex) { + $actual = $ex; + } + + $this->assertSame($ex2, $actual); + $this->assertSame([ + 'execute:1/attempt:1', + 'execute:1/rollback:1', + 'execute:2/attempt:1', + 'execute:2/rollback:1', + ], $this->unitOfWork->sequence); + $this->assertSame(2, $this->unitOfWork->executions); + $this->assertSame(2, $this->unitOfWork->attempts); + $this->assertSame(0, $this->unitOfWork->commits); + $this->assertSame(2, $this->unitOfWork->rollbacks); + $this->assertSame([$ex1, $ex2], $this->unitOfWork->exceptions->reported); + $this->assertSame([$ex1], $this->reporter->reported); // only "swallowed" exceptions are reported + $this->assertTrue($this->unitOfWork->inactive()); + } + + #[Test] + public function it_rolls_back_the_fake_unit_of_work_when_a_before_commit_callback_fails(): void + { + $ex = new LogicException('Boom!'); + $actual = null; + + try { + $this->manager->execute(function () use ($ex): void { + $this->manager->beforeCommit(fn () => throw $ex); + $this->manager->afterCommit($this->record('after')); + }); + } catch (LogicException $e) { + $actual = $e; + } + + $this->assertSame($ex, $actual); + $this->assertSame([], $this->log); + $this->assertSame(['execute:1/attempt:1', 'execute:1/rollback:1'], $this->unitOfWork->sequence); + $this->assertSame(0, $this->unitOfWork->commits); + $this->assertSame([$ex], $this->unitOfWork->exceptions->reported); + $this->assertSame([], $this->reporter->reported); + } + + #[Test] + public function it_retries_when_a_before_commit_callback_fails(): void + { + $ex = new LogicException('Boom!'); + $count = 0; + + $this->manager->execute(function () use ($ex, &$count): void { + $count++; + $attempt = $count; + $this->manager->beforeCommit(function () use ($ex, $attempt): void { + $this->log[] = 'before:' . $attempt; + if ($attempt === 1) { + throw $ex; + } + }); + $this->manager->afterCommit($this->record('after:' . $attempt)); + }, 2); + + $this->assertSame(['before:1', 'before:2', 'after:2'], $this->log); + $this->assertSame([ + 'execute:1/attempt:1', + 'execute:1/rollback:1', + 'execute:2/attempt:1', + 'execute:2/commit:1', + ], $this->unitOfWork->sequence); + $this->assertSame([$ex], $this->unitOfWork->exceptions->reported); + $this->assertSame([$ex], $this->reporter->reported); + } + + #[Test] + public function it_forgets_callbacks_registered_by_a_failed_attempt(): void + { + $ex = new LogicException('Boom!'); + $count = 0; + + $this->manager->execute(function () use ($ex, &$count): void { + $count++; + $this->manager->beforeCommit($this->record('before:' . $count)); + $this->manager->afterCommit($this->record('after:' . $count)); + if ($count === 1) { + throw $ex; + } + }, 2); + + $this->assertSame(['before:2', 'after:2'], $this->log); + $this->assertSame([ + 'execute:1/attempt:1', + 'execute:1/rollback:1', + 'execute:2/attempt:1', + 'execute:2/commit:1', + ], $this->unitOfWork->sequence); + } + + // ------------------------------------------------------------------------- + // Failing after commit callbacks + // ------------------------------------------------------------------------- + + #[Test] + public function it_does_not_retry_when_an_after_commit_callback_fails(): void + { + $ex = new LogicException('Boom!'); + $actual = null; + + try { + $this->manager->execute(function () use ($ex): void { + $this->manager->afterCommit(function () use ($ex): void { + $this->log[] = 'after1'; + throw $ex; + }); + $this->manager->afterCommit($this->record('after2')); + }, 3); + } catch (LogicException $e) { + $actual = $e; + } + + $this->assertSame($ex, $actual); + $this->assertSame(['after1', 'after2'], $this->log); + $this->assertSame(['execute:1/attempt:1', 'execute:1/commit:1'], $this->unitOfWork->sequence); + $this->assertSame(1, $this->unitOfWork->attempts); + $this->assertSame(0, $this->unitOfWork->rollbacks); + $this->assertSame([], $this->unitOfWork->exceptions->reported); + $this->assertSame([], $this->reporter->reported); + } + + #[Test] + public function it_executes_all_after_commit_callbacks_when_several_fail(): void + { + $ex1 = new LogicException('Boom 1!'); + $ex2 = new RuntimeException('Boom 2!'); + $actual = null; + + try { + $this->manager->execute(function () use ($ex1, $ex2): void { + $this->manager->afterCommit(fn () => throw $ex1); + $this->manager->afterCommit($this->record('after2')); + $this->manager->afterCommit(fn () => throw $ex2); + }, 3); + } catch (AfterCommitCallbacksFailed $e) { + $actual = $e; + } + + $this->assertInstanceOf(AfterCommitCallbacksFailed::class, $actual); + $this->assertSame([$ex1, $ex2], $actual->exceptions()); + $this->assertSame(['after2'], $this->log); + $this->assertSame(['execute:1/attempt:1', 'execute:1/commit:1'], $this->unitOfWork->sequence); + $this->assertSame([], $this->unitOfWork->exceptions->reported); + $this->assertSame([], $this->reporter->reported); + } + + // ------------------------------------------------------------------------- + // After commit callbacks that are queued while draining + // + // Once committed, the after commit callbacks are drained as a FIFO queue. + // Any after commit callback registered while draining is added to the end + // of the queue. + // ------------------------------------------------------------------------- + + #[Test] + public function it_queues_an_after_commit_callback_registered_while_draining(): void + { + $this->manager->execute(function (): void { + $this->manager->afterCommit(function (): void { + $this->log[] = 'after1:start'; + $this->manager->afterCommit($this->record('after3')); + $this->log[] = 'after1:end'; + }); + $this->manager->afterCommit($this->record('after2')); + }); + + $this->assertSame(['after1:start', 'after1:end', 'after2', 'after3'], $this->log); + $this->assertSame(['execute:1/attempt:1', 'execute:1/commit:1'], $this->unitOfWork->sequence); + } + + #[Test] + public function it_executes_remaining_callbacks_when_a_queued_callback_fails(): void + { + $ex = new LogicException('Boom!'); + $actual = null; + + try { + $this->manager->execute(function () use ($ex): void { + $this->manager->afterCommit(function () use ($ex): void { + $this->log[] = 'after1'; + $this->manager->afterCommit(function () use ($ex): void { + $this->log[] = 'after3'; + throw $ex; + }); + }); + $this->manager->afterCommit(function (): void { + $this->log[] = 'after2'; + $this->manager->afterCommit($this->record('after4')); + }); + }); + } catch (LogicException $e) { + $actual = $e; + } + + $this->assertSame($ex, $actual); + $this->assertSame(['after1', 'after2', 'after3', 'after4'], $this->log); + $this->assertSame(['execute:1/attempt:1', 'execute:1/commit:1'], $this->unitOfWork->sequence); + $this->assertSame([], $this->unitOfWork->exceptions->reported); + $this->assertSame([], $this->reporter->reported); + } + + #[Test] + public function it_collects_the_failure_of_a_queued_callback_with_other_failures(): void + { + $ex1 = new LogicException('Boom 1!'); + $ex2 = new RuntimeException('Boom 2!'); + $actual = null; + + try { + $this->manager->execute(function () use ($ex1, $ex2): void { + $this->manager->afterCommit(fn () => $this->manager->afterCommit(fn () => throw $ex2)); + $this->manager->afterCommit(fn () => throw $ex1); + }); + } catch (AfterCommitCallbacksFailed $e) { + $actual = $e; + } + + $this->assertInstanceOf(AfterCommitCallbacksFailed::class, $actual); + $this->assertSame([$ex1, $ex2], $actual->exceptions()); + $this->assertSame(['execute:1/attempt:1', 'execute:1/commit:1'], $this->unitOfWork->sequence); + } + + // ------------------------------------------------------------------------- + // Starting a unit of work from an after commit callback + // ------------------------------------------------------------------------- + + #[Test] + public function it_starts_a_new_unit_of_work_from_an_after_commit_callback(): void + { + $nested = null; + + $actual = $this->manager->execute(function () use (&$nested): string { + $this->manager->afterCommit(function () use (&$nested): void { + $nested = $this->manager->execute(fn () => 'nested-result'); + }); + return 'outer-result'; + }); + + $this->assertSame('outer-result', $actual); + $this->assertSame('nested-result', $nested); + $this->assertSame(2, $this->unitOfWork->executions); + $this->assertSame([ + 'execute:1/attempt:1', + 'execute:1/commit:1', + 'execute:2/attempt:1', + 'execute:2/commit:1', + ], $this->unitOfWork->sequence); + $this->assertSame(2, $this->unitOfWork->attempts); + $this->assertSame(2, $this->unitOfWork->commits); + $this->assertSame(0, $this->unitOfWork->rollbacks); + $this->assertTrue($this->unitOfWork->inactive()); + } + + #[Test] + public function it_executes_the_nested_unit_of_work_while_the_fake_unit_of_work_is_active(): void + { + $flags = []; + + $this->manager->execute(function () use (&$flags): void { + $flags['outer'] = $this->unitOfWork->active(); + $this->manager->afterCommit(function () use (&$flags): void { + $flags['after:start'] = $this->unitOfWork->active(); + $this->manager->execute(function () use (&$flags): void { + $flags['nested'] = $this->unitOfWork->active(); + }); + $flags['after:end'] = $this->unitOfWork->active(); + }); + }); + + $this->assertSame([ + 'outer' => true, + 'after:start' => false, + 'nested' => true, + 'after:end' => false, + ], $flags); + } + + /** + * Regression for the nested unit of work resetting the outer after commit queue. + */ + #[Test] + public function it_executes_remaining_after_commit_callbacks_after_a_nested_unit_of_work(): void + { + $this->manager->execute(function (): void { + $this->manager->afterCommit(function (): void { + $this->log[] = 'after1'; + $this->manager->execute($this->record('nested')); + }); + $this->manager->afterCommit($this->record('after2')); + $this->manager->afterCommit($this->record('after3')); + }); + + $this->assertSame(['after1', 'nested', 'after2', 'after3'], $this->log); + $this->assertSame([ + 'execute:1/attempt:1', + 'execute:1/commit:1', + 'execute:2/attempt:1', + 'execute:2/commit:1', + ], $this->unitOfWork->sequence); + } + + /** + * The nested unit of work executes its own before commit callbacks, but its after commit callbacks + * are added to the end of the queue being drained. So the nested unit of work returns before they + * are executed. + */ + #[Test] + public function it_executes_the_commit_callbacks_of_a_nested_unit_of_work(): void + { + $snapshots = []; + + $this->manager->execute(function () use (&$snapshots): void { + $this->manager->beforeCommit(function () use (&$snapshots): void { + $snapshots['outer:before'] = [$this->unitOfWork->active(), $this->unitOfWork->sequence]; + }); + $this->manager->afterCommit(function () use (&$snapshots): void { + $this->manager->execute(function () use (&$snapshots): void { + $this->manager->afterCommit(function () use (&$snapshots): void { + $snapshots['nested:after'] = [$this->unitOfWork->active(), $this->unitOfWork->sequence]; + }); + $this->manager->beforeCommit(function () use (&$snapshots): void { + $snapshots['nested:before'] = [$this->unitOfWork->active(), $this->unitOfWork->sequence]; + }); + }); + $snapshots['outer:after1:end'] = [$this->unitOfWork->active(), $this->unitOfWork->sequence]; + }); + $this->manager->afterCommit(function () use (&$snapshots): void { + $snapshots['outer:after2'] = [$this->unitOfWork->active(), $this->unitOfWork->sequence]; + }); + }); + + $this->assertSame([ + 'outer:before' => [true, ['execute:1/attempt:1']], + 'nested:before' => [true, ['execute:1/attempt:1', 'execute:1/commit:1', 'execute:2/attempt:1']], + 'outer:after1:end' => [false, [ + 'execute:1/attempt:1', + 'execute:1/commit:1', + 'execute:2/attempt:1', + 'execute:2/commit:1', + ]], + 'outer:after2' => [false, [ + 'execute:1/attempt:1', + 'execute:1/commit:1', + 'execute:2/attempt:1', + 'execute:2/commit:1', + ]], + 'nested:after' => [false, [ + 'execute:1/attempt:1', + 'execute:1/commit:1', + 'execute:2/attempt:1', + 'execute:2/commit:1', + ]], + ], $snapshots); + } + + #[Test] + public function it_queues_an_after_commit_callback_registered_after_a_nested_unit_of_work(): void + { + $this->manager->execute(function (): void { + $this->manager->afterCommit(function (): void { + $this->manager->execute(function (): void { + $this->log[] = 'nested'; + $this->manager->afterCommit($this->record('nested:after')); + }); + $this->manager->afterCommit($this->record('after3')); + $this->log[] = 'after1:end'; + }); + $this->manager->afterCommit($this->record('after2')); + }); + + $this->assertSame(['nested', 'after1:end', 'after2', 'nested:after', 'after3'], $this->log); + $this->assertSame([ + 'execute:1/attempt:1', + 'execute:1/commit:1', + 'execute:2/attempt:1', + 'execute:2/commit:1', + ], $this->unitOfWork->sequence); + } + + #[Test] + public function it_starts_a_unit_of_work_from_several_after_commit_callbacks(): void + { + $this->manager->execute(function (): void { + $this->manager->afterCommit(fn () => $this->manager->execute($this->record('nested1'))); + $this->manager->afterCommit(fn () => $this->manager->execute($this->record('nested2'))); + }); + + $this->assertSame(['nested1', 'nested2'], $this->log); + $this->assertSame([ + 'execute:1/attempt:1', + 'execute:1/commit:1', + 'execute:2/attempt:1', + 'execute:2/commit:1', + 'execute:3/attempt:1', + 'execute:3/commit:1', + ], $this->unitOfWork->sequence); + $this->assertSame(3, $this->unitOfWork->commits); + } + + #[Test] + public function it_starts_a_unit_of_work_from_a_nested_after_commit_callback(): void + { + $this->manager->execute(function (): void { + $this->log[] = 'outer'; + $this->manager->afterCommit(function (): void { + $this->manager->execute(function (): void { + $this->log[] = 'nested1'; + $this->manager->afterCommit(fn () => $this->manager->execute($this->record('nested2'))); + $this->manager->afterCommit($this->record('nested1:after')); + }); + }); + $this->manager->afterCommit($this->record('outer:after')); + }); + + $this->assertSame(['outer', 'nested1', 'outer:after', 'nested2', 'nested1:after'], $this->log); + $this->assertSame([ + 'execute:1/attempt:1', + 'execute:1/commit:1', + 'execute:2/attempt:1', + 'execute:2/commit:1', + 'execute:3/attempt:1', + 'execute:3/commit:1', + ], $this->unitOfWork->sequence); + $this->assertSame(3, $this->unitOfWork->executions); + $this->assertSame(3, $this->unitOfWork->attempts); + $this->assertSame(3, $this->unitOfWork->commits); + } + + #[Test] + public function it_retries_a_nested_unit_of_work(): void + { + $ex = new LogicException('Boom!'); + $count = 0; + + $this->manager->execute(function () use ($ex, &$count): void { + $this->manager->afterCommit(function () use ($ex, &$count): void { + $this->manager->execute(function () use ($ex, &$count): void { + $count++; + $this->manager->beforeCommit($this->record('nested:before:' . $count)); + $this->manager->afterCommit($this->record('nested:after:' . $count)); + if ($count === 1) { + throw $ex; + } + }, 2); + }); + $this->manager->afterCommit($this->record('outer:after')); + }); + + $this->assertSame(['nested:before:2', 'outer:after', 'nested:after:2'], $this->log); + $this->assertSame([ + 'execute:1/attempt:1', + 'execute:1/commit:1', + 'execute:2/attempt:1', + 'execute:2/rollback:1', + 'execute:3/attempt:1', + 'execute:3/commit:1', + ], $this->unitOfWork->sequence); + $this->assertSame(3, $this->unitOfWork->executions); + $this->assertSame(3, $this->unitOfWork->attempts); + $this->assertSame(2, $this->unitOfWork->commits); + $this->assertSame(1, $this->unitOfWork->rollbacks); + $this->assertSame([$ex], $this->unitOfWork->exceptions->reported); + $this->assertSame([$ex], $this->reporter->reported); + } + + #[Test] + public function it_executes_remaining_after_commit_callbacks_when_a_nested_unit_of_work_fails(): void + { + $ex = new LogicException('Boom!'); + $actual = null; + + try { + $this->manager->execute(function () use ($ex): void { + $this->manager->afterCommit(function () use ($ex): void { + $this->manager->execute(function () use ($ex): void { + $this->manager->beforeCommit($this->record('nested:before')); + $this->manager->afterCommit($this->record('nested:after')); + throw $ex; + }); + }); + $this->manager->afterCommit($this->record('outer:after')); + }); + } catch (LogicException $e) { + $actual = $e; + } + + $this->assertSame($ex, $actual); + $this->assertSame(['outer:after'], $this->log); + $this->assertSame([ + 'execute:1/attempt:1', + 'execute:1/commit:1', + 'execute:2/attempt:1', + 'execute:2/rollback:1', + ], $this->unitOfWork->sequence); + $this->assertSame(1, $this->unitOfWork->commits); + $this->assertSame(1, $this->unitOfWork->rollbacks); + $this->assertSame([$ex], $this->unitOfWork->exceptions->reported); + $this->assertSame([], $this->reporter->reported); + $this->assertTrue($this->unitOfWork->inactive()); + } + + /** + * As the nested after commit callbacks are queued, their failure is thrown by the outer unit of work, + * not the nested one. + */ + #[Test] + public function it_executes_remaining_after_commit_callbacks_when_a_nested_after_commit_callback_fails(): void + { + $ex = new LogicException('Boom!'); + $actual = null; + + try { + $this->manager->execute(function () use ($ex): void { + $this->manager->afterCommit(function () use ($ex): void { + $this->log[] = $this->manager->execute(function () use ($ex): string { + $this->manager->afterCommit(fn () => throw $ex); + $this->manager->afterCommit($this->record('nested:after')); + return 'nested:result'; + }); + }); + $this->manager->afterCommit($this->record('outer:after')); + }); + } catch (LogicException $e) { + $actual = $e; + } + + $this->assertSame($ex, $actual); + $this->assertSame(['nested:result', 'outer:after', 'nested:after'], $this->log); + $this->assertSame([ + 'execute:1/attempt:1', + 'execute:1/commit:1', + 'execute:2/attempt:1', + 'execute:2/commit:1', + ], $this->unitOfWork->sequence); + $this->assertSame(0, $this->unitOfWork->rollbacks); + $this->assertSame([], $this->unitOfWork->exceptions->reported); + $this->assertSame([], $this->reporter->reported); + } + + #[Test] + public function it_cannot_start_a_unit_of_work_within_a_nested_unit_of_work(): void + { + $actual = null; + + try { + $this->manager->execute(function (): void { + $this->manager->afterCommit(function (): void { + $this->manager->execute(fn () => $this->manager->execute(fn () => null)); + }); + $this->manager->afterCommit($this->record('outer:after')); + }); + } catch (ApplicationException $ex) { + $actual = $ex; + } + + $this->assertInstanceOf(ApplicationException::class, $actual); + $this->assertSame( + 'Not expecting unit of work manager to start a unit of work within an existing one.', + $actual->getMessage(), + ); + $this->assertSame(['outer:after'], $this->log); + $this->assertSame([ + 'execute:1/attempt:1', + 'execute:1/commit:1', + 'execute:2/attempt:1', + 'execute:2/rollback:1', + ], $this->unitOfWork->sequence); + $this->assertSame([$actual], $this->unitOfWork->exceptions->reported); + } + + #[Test] + public function it_cannot_queue_a_before_commit_callback_from_an_after_commit_callback_after_a_nested_unit_of_work(): void + { + $actual = null; + + try { + $this->manager->execute(function (): void { + $this->manager->afterCommit(function (): void { + $this->manager->execute(fn () => null); + $this->manager->beforeCommit($this->record('before')); + }); + }); + } catch (ApplicationException $ex) { + $actual = $ex; + } + + $this->assertInstanceOf(ApplicationException::class, $actual); + $this->assertSame( + 'Cannot queue a before commit callback when not executing a unit of work.', + $actual->getMessage(), + ); + $this->assertSame([], $this->log); + $this->assertSame([ + 'execute:1/attempt:1', + 'execute:1/commit:1', + 'execute:2/attempt:1', + 'execute:2/commit:1', + ], $this->unitOfWork->sequence); + } + + // ------------------------------------------------------------------------- + // Resetting state once the unit of work is complete + // ------------------------------------------------------------------------- + + #[Test] + public function it_is_reset_after_a_nested_unit_of_work(): void + { + $this->manager->execute(function (): void { + $this->manager->afterCommit(function (): void { + $this->manager->execute(function (): void { + $this->manager->afterCommit($this->record('nested:after')); + }); + }); + }); + + $actual = $this->manager->execute(function (): string { + $this->manager->beforeCommit($this->record('second:before')); + $this->manager->afterCommit($this->record('second:after')); + return 'result'; + }); + + $this->assertSame('result', $actual); + $this->assertSame(['nested:after', 'second:before', 'second:after'], $this->log); + $this->assertSame([ + 'execute:1/attempt:1', + 'execute:1/commit:1', + 'execute:2/attempt:1', + 'execute:2/commit:1', + 'execute:3/attempt:1', + 'execute:3/commit:1', + ], $this->unitOfWork->sequence); + $this->assertTrue($this->unitOfWork->inactive()); + } + + #[Test] + public function it_is_reset_after_a_nested_unit_of_work_fails(): void + { + try { + $this->manager->execute(function (): void { + $this->manager->afterCommit(function (): void { + $this->manager->execute(fn () => throw new LogicException('Boom!')); + }); + }); + } catch (LogicException) { + // expected + } + + $actual = $this->manager->execute(function (): string { + $this->manager->afterCommit($this->record('second:after')); + return 'result'; + }); + + $this->assertSame('result', $actual); + $this->assertSame(['second:after'], $this->log); + $this->assertSame([ + 'execute:1/attempt:1', + 'execute:1/commit:1', + 'execute:2/attempt:1', + 'execute:2/rollback:1', + 'execute:3/attempt:1', + 'execute:3/commit:1', + ], $this->unitOfWork->sequence); + } + + #[Test] + public function it_cannot_queue_an_after_commit_callback_once_the_unit_of_work_has_completed(): void + { + $this->manager->execute(function (): void { + $this->manager->afterCommit(fn () => $this->manager->execute(fn () => null)); + }); + + $this->expectException(ApplicationException::class); + $this->expectExceptionMessage('Cannot queue an after commit callback when not executing a unit of work.'); + + $this->manager->afterCommit($this->record('after')); + } + + #[Test] + public function it_cannot_queue_a_before_commit_callback_once_the_unit_of_work_has_completed(): void + { + $this->manager->execute(function (): void { + $this->manager->afterCommit(fn () => $this->manager->execute(fn () => null)); + }); + + $this->expectException(ApplicationException::class); + $this->expectExceptionMessage('Cannot queue a before commit callback when not executing a unit of work.'); + + $this->manager->beforeCommit($this->record('before')); + } + + /** + * Create a callback that records the provided entry in the log. + * + * @return Closure(): void + */ + private function record(string $entry): Closure + { + return function () use ($entry): void { + $this->log[] = $entry; + }; + } + + /** + * Create a callback that throws each of the provided exceptions in turn, then returns a result. + * + * @param list $exceptions + * @return Closure(): string + */ + private function failThenSucceed(array $exceptions): Closure + { + return function () use (&$exceptions): string { + $ex = array_shift($exceptions); + + if ($ex) { + throw $ex; + } + + return 'result'; + }; + } +} diff --git a/tests/Unit/Application/UnitOfWork/UnitOfWorkManagerTest.php b/tests/Unit/Application/UnitOfWork/UnitOfWorkManagerTest.php index 8557326..8f1f317 100644 --- a/tests/Unit/Application/UnitOfWork/UnitOfWorkManagerTest.php +++ b/tests/Unit/Application/UnitOfWork/UnitOfWorkManagerTest.php @@ -23,6 +23,7 @@ use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use RuntimeException; +use Throwable; final class UnitOfWorkManagerTest extends TestCase { @@ -652,7 +653,7 @@ public function it_fails_if_after_commit_callback_registers_before_commit_callba ->willReturnCallback(fn (Closure $callback) => $callback()); $this->expectException(ApplicationException::class); - $this->expectExceptionMessage('Cannot queue a before commit callback as unit of work has been committed.'); + $this->expectExceptionMessage('Cannot queue a before commit callback when not executing a unit of work.'); $this->manager->execute(function () { $this->manager->afterCommit(function () { @@ -678,4 +679,626 @@ public function it_fails_if_attempts_is_not_greater_than_zero(): void /** @phpstan-ignore-next-line */ $this->manager->execute(fn () => throw new LogicException('Boom!'), 0); } + + // ------------------------------------------------------------------------- + // After commit callbacks that are queued while draining + // + // Once committed, the after commit callbacks are drained as a FIFO queue. + // Any after commit callback registered while draining is added to the end + // of the queue. + // ------------------------------------------------------------------------- + + #[Test] + public function it_queues_an_after_commit_callback_registered_while_draining(): void + { + $sequence = []; + $this->willExecuteUnitOfWork(1, $sequence); + + $this->manager->execute(function () use (&$sequence): void { + $this->manager->afterCommit(function () use (&$sequence): void { + $sequence[] = 'after1:start'; + $this->manager->afterCommit(function () use (&$sequence): void { + $sequence[] = 'after3'; + }); + $sequence[] = 'after1:end'; + }); + $this->manager->afterCommit(function () use (&$sequence): void { + $sequence[] = 'after2'; + }); + }); + + $this->assertSame(['begin', 'commit', 'after1:start', 'after1:end', 'after2', 'after3'], $sequence); + } + + #[Test] + public function it_queues_an_after_commit_callback_registered_by_a_queued_callback(): void + { + $sequence = []; + $this->willExecuteUnitOfWork(1, $sequence); + + $this->manager->execute(function () use (&$sequence): void { + $this->manager->afterCommit(function () use (&$sequence): void { + $sequence[] = 'after1:start'; + $this->manager->afterCommit(function () use (&$sequence): void { + $sequence[] = 'after2:start'; + $this->manager->afterCommit(function () use (&$sequence): void { + $sequence[] = 'after3'; + }); + $sequence[] = 'after2:end'; + }); + $sequence[] = 'after1:end'; + }); + }); + + $this->assertSame([ + 'begin', + 'commit', + 'after1:start', + 'after1:end', + 'after2:start', + 'after2:end', + 'after3', + ], $sequence); + } + + #[Test] + public function it_executes_remaining_callbacks_when_a_queued_callback_fails(): void + { + $ex = new LogicException('Boom!'); + $sequence = []; + $actual = null; + $this->willExecuteUnitOfWork(1, $sequence); + + try { + $this->manager->execute(function () use ($ex, &$sequence): void { + $this->manager->afterCommit(function () use ($ex, &$sequence): void { + $sequence[] = 'after1'; + $this->manager->afterCommit(function () use ($ex, &$sequence): void { + $sequence[] = 'after3'; + throw $ex; + }); + }); + $this->manager->afterCommit(function () use (&$sequence): void { + $sequence[] = 'after2'; + $this->manager->afterCommit(function () use (&$sequence): void { + $sequence[] = 'after4'; + }); + }); + }, 3); + } catch (LogicException $e) { + $actual = $e; + } + + $this->assertSame($ex, $actual); + $this->assertSame(['begin', 'commit', 'after1', 'after2', 'after3', 'after4'], $sequence); + $this->assertSame([], $this->reporter->reported); + } + + #[Test] + public function it_collects_the_failure_of_a_queued_callback_with_other_failures(): void + { + $ex1 = new LogicException('Boom 1!'); + $ex2 = new RuntimeException('Boom 2!'); + $sequence = []; + $actual = null; + $this->willExecuteUnitOfWork(1, $sequence); + + try { + $this->manager->execute(function () use ($ex1, $ex2, &$sequence): void { + $this->manager->afterCommit(function () use ($ex2, &$sequence): void { + $sequence[] = 'after1'; + $this->manager->afterCommit(function () use ($ex2, &$sequence): void { + $sequence[] = 'after3'; + throw $ex2; + }); + }); + $this->manager->afterCommit(function () use ($ex1, &$sequence): void { + $sequence[] = 'after2'; + throw $ex1; + }); + }); + } catch (AfterCommitCallbacksFailed $e) { + $actual = $e; + } + + $this->assertInstanceOf(AfterCommitCallbacksFailed::class, $actual); + $this->assertSame([$ex1, $ex2], $actual->exceptions()); + $this->assertSame(['begin', 'commit', 'after1', 'after2', 'after3'], $sequence); + } + + // ------------------------------------------------------------------------- + // Starting a unit of work from an after commit callback + // ------------------------------------------------------------------------- + + #[Test] + public function it_allows_an_after_commit_callback_to_start_a_new_unit_of_work(): void + { + $sequence = []; + $nested = null; + $this->willExecuteUnitOfWork(2, $sequence); + + $actual = $this->manager->execute(function () use (&$sequence, &$nested): string { + $sequence[] = 'outer'; + $this->manager->afterCommit(function () use (&$sequence, &$nested): void { + $sequence[] = 'after:start'; + $nested = $this->manager->execute(function () use (&$sequence): string { + $sequence[] = 'nested'; + return 'nested-result'; + }); + $sequence[] = 'after:end'; + }); + return 'outer-result'; + }); + + $this->assertSame('outer-result', $actual); + $this->assertSame('nested-result', $nested); + $this->assertSame([ + 'begin', + 'outer', + 'commit', + 'after:start', + 'begin', + 'nested', + 'commit', + 'after:end', + ], $sequence); + } + + /** + * Regression for the nested unit of work resetting the outer after commit queue. + */ + #[Test] + public function it_executes_remaining_after_commit_callbacks_after_a_nested_unit_of_work(): void + { + $sequence = []; + $this->willExecuteUnitOfWork(2, $sequence); + + $this->manager->execute(function () use (&$sequence): void { + $this->manager->afterCommit(function () use (&$sequence): void { + $sequence[] = 'after1'; + $this->manager->execute(function () use (&$sequence): void { + $sequence[] = 'nested'; + }); + }); + $this->manager->afterCommit(function () use (&$sequence): void { + $sequence[] = 'after2'; + }); + $this->manager->afterCommit(function () use (&$sequence): void { + $sequence[] = 'after3'; + }); + }); + + $this->assertSame([ + 'begin', + 'commit', + 'after1', + 'begin', + 'nested', + 'commit', + 'after2', + 'after3', + ], $sequence); + } + + /** + * The nested unit of work executes its own before commit callbacks, but its after commit callbacks + * are added to the end of the queue being drained. So the nested unit of work returns before they + * are executed. + */ + #[Test] + public function it_executes_the_commit_callbacks_of_a_nested_unit_of_work(): void + { + $sequence = []; + $this->willExecuteUnitOfWork(2, $sequence); + + $this->manager->execute(function () use (&$sequence): void { + $sequence[] = 'outer'; + $this->manager->beforeCommit(function () use (&$sequence): void { + $sequence[] = 'outer:before'; + }); + $this->manager->afterCommit(function () use (&$sequence): void { + $sequence[] = 'outer:after1:start'; + $this->manager->execute(function () use (&$sequence): void { + $sequence[] = 'nested'; + $this->manager->afterCommit(function () use (&$sequence): void { + $sequence[] = 'nested:after'; + }); + $this->manager->beforeCommit(function () use (&$sequence): void { + $sequence[] = 'nested:before'; + }); + }); + $sequence[] = 'outer:after1:end'; + }); + $this->manager->afterCommit(function () use (&$sequence): void { + $sequence[] = 'outer:after2'; + }); + }); + + $this->assertSame([ + 'begin', + 'outer', + 'outer:before', + 'commit', + 'outer:after1:start', + 'begin', + 'nested', + 'nested:before', + 'commit', + 'outer:after1:end', + 'outer:after2', + 'nested:after', + ], $sequence); + } + + #[Test] + public function it_queues_an_after_commit_callback_registered_after_a_nested_unit_of_work(): void + { + $sequence = []; + $this->willExecuteUnitOfWork(2, $sequence); + + $this->manager->execute(function () use (&$sequence): void { + $this->manager->afterCommit(function () use (&$sequence): void { + $sequence[] = 'after1:start'; + $this->manager->execute(function () use (&$sequence): void { + $sequence[] = 'nested'; + $this->manager->afterCommit(function () use (&$sequence): void { + $sequence[] = 'nested:after'; + }); + }); + $this->manager->afterCommit(function () use (&$sequence): void { + $sequence[] = 'after3'; + }); + $sequence[] = 'after1:end'; + }); + $this->manager->afterCommit(function () use (&$sequence): void { + $sequence[] = 'after2'; + }); + }); + + $this->assertSame([ + 'begin', + 'commit', + 'after1:start', + 'begin', + 'nested', + 'commit', + 'after1:end', + 'after2', + 'nested:after', + 'after3', + ], $sequence); + } + + #[Test] + public function it_allows_a_nested_after_commit_callback_to_start_another_unit_of_work(): void + { + $sequence = []; + $this->willExecuteUnitOfWork(3, $sequence); + + $this->manager->execute(function () use (&$sequence): void { + $sequence[] = 'outer'; + $this->manager->afterCommit(function () use (&$sequence): void { + $this->manager->execute(function () use (&$sequence): void { + $sequence[] = 'nested1'; + $this->manager->afterCommit(function () use (&$sequence): void { + $this->manager->execute(function () use (&$sequence): void { + $sequence[] = 'nested2'; + }); + }); + $this->manager->afterCommit(function () use (&$sequence): void { + $sequence[] = 'nested1:after'; + }); + }); + }); + $this->manager->afterCommit(function () use (&$sequence): void { + $sequence[] = 'outer:after'; + }); + }); + + $this->assertSame([ + 'begin', + 'outer', + 'commit', + 'begin', + 'nested1', + 'commit', + 'outer:after', + 'begin', + 'nested2', + 'commit', + 'nested1:after', + ], $sequence); + } + + #[Test] + public function it_allows_a_nested_unit_of_work_to_be_retried(): void + { + $ex = new LogicException('Boom!'); + $sequence = []; + $count = 0; + $this->willExecuteUnitOfWork(3, $sequence); + + $this->manager->execute(function () use ($ex, &$sequence, &$count): void { + $this->manager->afterCommit(function () use ($ex, &$sequence, &$count): void { + $this->manager->execute(function () use ($ex, &$sequence, &$count): void { + $count++; + $sequence[] = 'nested:' . $count; + $this->manager->beforeCommit(function () use (&$sequence, $count): void { + $sequence[] = 'nested:before:' . $count; + }); + $this->manager->afterCommit(function () use (&$sequence, $count): void { + $sequence[] = 'nested:after:' . $count; + }); + if ($count === 1) { + throw $ex; + } + }, 2); + }); + $this->manager->afterCommit(function () use (&$sequence): void { + $sequence[] = 'outer:after'; + }); + }); + + $this->assertSame([ + 'begin', + 'commit', + 'begin', + 'nested:1', + 'rollback', + 'begin', + 'nested:2', + 'nested:before:2', + 'commit', + 'outer:after', + 'nested:after:2', + ], $sequence); + $this->assertSame([$ex], $this->reporter->reported); + } + + #[Test] + public function it_executes_remaining_after_commit_callbacks_when_a_nested_unit_of_work_fails(): void + { + $ex = new LogicException('Boom!'); + $sequence = []; + $actual = null; + $this->willExecuteUnitOfWork(2, $sequence); + + try { + $this->manager->execute(function () use ($ex, &$sequence): void { + $this->manager->afterCommit(function () use ($ex, &$sequence): void { + $sequence[] = 'after1'; + $this->manager->execute(function () use ($ex, &$sequence): void { + $sequence[] = 'nested'; + $this->manager->beforeCommit(function () use (&$sequence): void { + $sequence[] = 'nested:before'; + }); + $this->manager->afterCommit(function () use (&$sequence): void { + $sequence[] = 'nested:after'; + }); + throw $ex; + }); + }); + $this->manager->afterCommit(function () use (&$sequence): void { + $sequence[] = 'after2'; + }); + }); + } catch (LogicException $e) { + $actual = $e; + } + + $this->assertSame($ex, $actual); + $this->assertSame(['begin', 'commit', 'after1', 'begin', 'nested', 'rollback', 'after2'], $sequence); + $this->assertSame([], $this->reporter->reported); + } + + /** + * As the nested after commit callbacks are queued, their failure is thrown by the outer unit of work, + * not the nested one. + */ + #[Test] + public function it_executes_remaining_after_commit_callbacks_when_a_nested_after_commit_callback_fails(): void + { + $ex = new LogicException('Boom!'); + $sequence = []; + $actual = null; + $this->willExecuteUnitOfWork(2, $sequence); + + try { + $this->manager->execute(function () use ($ex, &$sequence): void { + $this->manager->afterCommit(function () use ($ex, &$sequence): void { + $sequence[] = $this->manager->execute(function () use ($ex, &$sequence): string { + $sequence[] = 'nested'; + $this->manager->afterCommit(function () use ($ex, &$sequence): void { + $sequence[] = 'nested:after1'; + throw $ex; + }); + $this->manager->afterCommit(function () use (&$sequence): void { + $sequence[] = 'nested:after2'; + }); + return 'nested:result'; + }); + }); + $this->manager->afterCommit(function () use (&$sequence): void { + $sequence[] = 'outer:after'; + }); + }); + } catch (LogicException $e) { + $actual = $e; + } + + $this->assertSame($ex, $actual); + $this->assertSame([ + 'begin', + 'commit', + 'begin', + 'nested', + 'commit', + 'nested:result', + 'outer:after', + 'nested:after1', + 'nested:after2', + ], $sequence); + $this->assertSame([], $this->reporter->reported); + } + + #[Test] + public function it_cannot_start_a_unit_of_work_within_a_nested_unit_of_work(): void + { + $sequence = []; + $this->willExecuteUnitOfWork(2, $sequence); + + $this->expectException(ApplicationException::class); + $this->expectExceptionMessage( + 'Not expecting unit of work manager to start a unit of work within an existing one.', + ); + + $this->manager->execute(function (): void { + $this->manager->afterCommit(function (): void { + $this->manager->execute(function (): void { + $this->manager->execute(fn () => null); + }); + }); + }); + } + + #[Test] + public function it_fails_if_after_commit_callback_registers_before_commit_callback_after_a_nested_unit_of_work(): void + { + $sequence = []; + $this->willExecuteUnitOfWork(2, $sequence); + + $this->expectException(ApplicationException::class); + $this->expectExceptionMessage('Cannot queue a before commit callback when not executing a unit of work.'); + + $this->manager->execute(function (): void { + $this->manager->afterCommit(function (): void { + $this->manager->execute(fn () => null); + $this->manager->beforeCommit(fn () => null); + }); + }); + } + + // ------------------------------------------------------------------------- + // Resetting state once the unit of work is complete + // ------------------------------------------------------------------------- + + #[Test] + public function it_is_reset_after_a_nested_unit_of_work(): void + { + $sequence = []; + $this->willExecuteUnitOfWork(3, $sequence); + + $this->manager->execute(function () use (&$sequence): void { + $this->manager->afterCommit(function () use (&$sequence): void { + $this->manager->execute(function () use (&$sequence): void { + $this->manager->afterCommit(function () use (&$sequence): void { + $sequence[] = 'nested:after'; + }); + }); + }); + }); + + $actual = $this->manager->execute(function () use (&$sequence): int { + $this->manager->beforeCommit(function () use (&$sequence): void { + $sequence[] = 'second:before'; + }); + $this->manager->afterCommit(function () use (&$sequence): void { + $sequence[] = 'second:after'; + }); + return 2; + }); + + $this->assertSame(2, $actual); + $this->assertSame([ + 'begin', + 'commit', + 'begin', + 'commit', + 'nested:after', + 'begin', + 'second:before', + 'commit', + 'second:after', + ], $sequence); + } + + #[Test] + public function it_cannot_queue_after_commit_callback_once_the_unit_of_work_has_completed(): void + { + $sequence = []; + $this->willExecuteUnitOfWork(1, $sequence); + + $this->manager->execute(function (): void { + $this->manager->afterCommit(fn () => null); + }); + + $this->expectException(ApplicationException::class); + $this->expectExceptionMessage('Cannot queue an after commit callback when not executing a unit of work.'); + + $this->manager->afterCommit(fn () => null); + } + + #[Test] + public function it_cannot_queue_after_commit_callback_once_after_commit_callbacks_have_failed(): void + { + $sequence = []; + $this->willExecuteUnitOfWork(1, $sequence); + + try { + $this->manager->execute(function (): void { + $this->manager->afterCommit(fn () => throw new LogicException('Boom!')); + }); + } catch (LogicException) { + // expected + } + + $this->expectException(ApplicationException::class); + $this->expectExceptionMessage('Cannot queue an after commit callback when not executing a unit of work.'); + + $this->manager->afterCommit(fn () => null); + } + + #[Test] + public function it_cannot_queue_before_commit_callback_once_the_unit_of_work_has_completed(): void + { + $sequence = []; + $this->willExecuteUnitOfWork(1, $sequence); + + $this->manager->execute(function (): void { + $this->manager->afterCommit(fn () => null); + }); + + $this->expectException(ApplicationException::class); + $this->expectExceptionMessage('Cannot queue a before commit callback when not executing a unit of work.'); + + $this->manager->beforeCommit(fn () => null); + } + + /** + * Expect the unit of work to be executed the given number of times, recording each execution in the sequence. + * + * @param list $sequence + * @param-out list $sequence + */ + private function willExecuteUnitOfWork(int $times, array &$sequence): void + { + $this->unitOfWork + ->expects($this->exactly($times)) + ->method('execute') + ->willReturnCallback(function (Closure $callback, int $attempts) use (&$sequence): mixed { + $this->assertSame(1, $attempts); + $sequence[] = 'begin'; + + try { + $result = $callback(); + } catch (Throwable $ex) { + $sequence[] = 'rollback'; + throw $ex; + } + + $sequence[] = 'commit'; + + return $result; + }); + } } diff --git a/tests/Unit/Testing/FakeUnitOfWorkTest.php b/tests/Unit/Testing/FakeUnitOfWorkTest.php index ef3fc5d..e4c8c3a 100644 --- a/tests/Unit/Testing/FakeUnitOfWorkTest.php +++ b/tests/Unit/Testing/FakeUnitOfWorkTest.php @@ -139,8 +139,9 @@ public function it_is_successful_on_first_attempt(): void $result = $unitOfWork->execute(fn () => 'result'); $this->assertSame('result', $result); - $this->assertSame(['attempt:1', 'commit:1'], $unitOfWork->sequence); + $this->assertSame(['execute:1/attempt:1', 'execute:1/commit:1'], $unitOfWork->sequence); $this->assertSame([], $unitOfWork->exceptions->reported); + $this->assertSame(1, $unitOfWork->executions); $this->assertSame(1, $unitOfWork->attempts); $this->assertSame(1, $unitOfWork->commits); $this->assertSame(0, $unitOfWork->rollbacks); @@ -172,14 +173,15 @@ public function it_is_successful_after_retrying(int $attempts): void $this->assertSame('result', $result); $this->assertSame([ - 'attempt:1', - 'rollback:1', - 'attempt:2', - 'rollback:2', - 'attempt:3', - 'commit:3', + 'execute:1/attempt:1', + 'execute:1/rollback:1', + 'execute:1/attempt:2', + 'execute:1/rollback:2', + 'execute:1/attempt:3', + 'execute:1/commit:3', ], $unitOfWork->sequence); $this->assertSame([$ex1, $ex2], $unitOfWork->exceptions->reported); + $this->assertSame(1, $unitOfWork->executions); $this->assertSame(3, $unitOfWork->attempts); $this->assertSame(1, $unitOfWork->commits); $this->assertSame(2, $unitOfWork->rollbacks); @@ -211,12 +213,13 @@ public function it_rolls_back_every_attempt_when_not_successful(): void } $this->assertSame([ - 'attempt:1', - 'rollback:1', - 'attempt:2', - 'rollback:2', + 'execute:1/attempt:1', + 'execute:1/rollback:1', + 'execute:1/attempt:2', + 'execute:1/rollback:2', ], $unitOfWork->sequence); $this->assertSame([$ex1, $ex2], $unitOfWork->exceptions->reported); + $this->assertSame(1, $unitOfWork->executions); $this->assertSame(2, $unitOfWork->attempts); $this->assertSame(0, $unitOfWork->commits); $this->assertSame(2, $unitOfWork->rollbacks); @@ -250,13 +253,52 @@ public function it_does_not_retry_when_the_exception_reporter_rethrows(): void } $this->assertSame($ex, $actual); - $this->assertSame(['attempt:1', 'rollback:1'], $unitOfWork->sequence); + $this->assertSame(['execute:1/attempt:1', 'execute:1/rollback:1'], $unitOfWork->sequence); + $this->assertSame(1, $unitOfWork->executions); $this->assertSame(1, $unitOfWork->attempts); $this->assertSame(0, $unitOfWork->commits); $this->assertSame(1, $unitOfWork->rollbacks); $this->assertSame([], $reporter->reported); } + #[Test] + public function it_records_each_execution_separately(): void + { + $ex = new RuntimeException('An error occurred.'); + $unitOfWork = new FakeUnitOfWork(); + $unitOfWork->execute(fn () => 'result'); + + $unitOfWork->execute($this->failThenSucceed([$ex]), 2); + + $this->assertSame([ + 'execute:1/attempt:1', + 'execute:1/commit:1', + 'execute:2/attempt:1', + 'execute:2/rollback:1', + 'execute:2/attempt:2', + 'execute:2/commit:2', + ], $unitOfWork->sequence); + $this->assertSame(2, $unitOfWork->executions); + $this->assertSame(3, $unitOfWork->attempts); + $this->assertSame(2, $unitOfWork->commits); + $this->assertSame(1, $unitOfWork->rollbacks); + } + + #[Test] + public function it_does_not_count_an_execution_that_is_rejected_because_it_is_already_active(): void + { + $unitOfWork = new FakeUnitOfWork(); + + try { + $unitOfWork->execute(fn () => $unitOfWork->execute(fn () => 'result')); + } catch (RuntimeException) { + // expected + } + + $this->assertSame(['execute:1/attempt:1', 'execute:1/rollback:1'], $unitOfWork->sequence); + $this->assertSame(1, $unitOfWork->executions); + } + /** * @return array */ @@ -281,6 +323,23 @@ public function it_throws_when_attempts_is_less_than_one(int $attempts): void $unitOfWork->execute(fn () => 'result', $attempts); } + #[DataProvider('invalidAttemptsProvider')] + #[Test] + public function it_does_not_count_an_execution_with_invalid_attempts(int $attempts): void + { + $unitOfWork = new FakeUnitOfWork(); + + try { + // @phpstan-ignore argument.type (deliberately violates the int<1, max> contract) + $unitOfWork->execute(fn () => 'result', $attempts); + } catch (InvalidArgumentException) { + // expected + } + + $this->assertSame([], $unitOfWork->sequence); + $this->assertSame(0, $unitOfWork->executions); + } + /** * Create a callback that throws each of the provided exceptions in turn, then returns a result. *