diff --git a/CHANGELOG.md b/CHANGELOG.md index a01614cc..fc3dd178 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,18 @@ All notable changes to this project will be documented in this file. This projec ## Unreleased +### Added + +- New `AfterCommitCallbacksFailed` exception, thrown by the unit of work manager when more than one after commit + callback fails. + +### Fixed + +- [#46](https://github.com/cloudcreativity/php-ddd-modules/issues/46) `UnitOfWorkManager` no longer re-attempts the unit + of work when an after commit callback throws, as the unit of work has already been committed. A failing after commit + callback also no longer prevents the remaining after commit callbacks from being executed. If one callback fails its + exception is thrown; if more than one fails, an `AfterCommitCallbacksFailed` exception is thrown. + ## [6.1.1] - 2026-11-14 ### Fixed diff --git a/docs/guide/application/units-of-work.md b/docs/guide/application/units-of-work.md index b0a98f0b..0c6f0614 100644 --- a/docs/guide/application/units-of-work.md +++ b/docs/guide/application/units-of-work.md @@ -229,6 +229,9 @@ $manager = new UnitOfWorkManager( The second constructor argument of the unit of work manager is an [exception reporter.](../infrastructure/exception-reporting) This is useful if the unit of work manager is handling multiple commit attempts. It allows it to report any exceptions that occur prior to a re-attempt. + +Only failures that occur before the unit of work commits are re-attempted. Once the unit of work has committed, an +exception thrown by an after commit callback is not re-attempted, as this would execute the committed work again. ::: ### Singleton Instance @@ -266,6 +269,11 @@ $manager->afterCommit(function (): void { }); ``` +As the transaction has already been committed, a failing after commit callback does not prevent the remaining after +commit callbacks from being executed. Once they have all been executed, if exactly one of them failed, its exception is +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. + ## Deferring Domain Events When using the unit of work pattern, you **must** use the unit of work aware domain event dispatcher. This coordinates diff --git a/src/Application/UnitOfWork/AfterCommitCallbacksFailed.php b/src/Application/UnitOfWork/AfterCommitCallbacksFailed.php new file mode 100644 index 00000000..ece89150 --- /dev/null +++ b/src/Application/UnitOfWork/AfterCommitCallbacksFailed.php @@ -0,0 +1,44 @@ + $exceptions + */ + public function __construct(private readonly array $exceptions) + { + assert(count($exceptions) > 1, 'Expecting more than one exception.'); + + parent::__construct( + sprintf('%d after commit callbacks failed.', count($exceptions)), + 0, + $exceptions[0], + ); + } + + /** + * Get the exceptions thrown by the after commit callbacks, in the order they were thrown. + * + * @return non-empty-list + */ + public function exceptions(): array + { + return $this->exceptions; + } +} diff --git a/src/Application/UnitOfWork/UnitOfWorkManager.php b/src/Application/UnitOfWork/UnitOfWorkManager.php index 69e6a784..ba5cb37f 100644 --- a/src/Application/UnitOfWork/UnitOfWorkManager.php +++ b/src/Application/UnitOfWork/UnitOfWorkManager.php @@ -53,7 +53,16 @@ public function execute(Closure $callback, int $attempts = 1): mixed throw new ApplicationException('Attempts must be greater than zero.'); } - return $this->retry($callback, $attempts); + 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; + } finally { + $this->reset(); + } } private function retry(Closure $callback, int $attempts): mixed @@ -75,23 +84,27 @@ private function retry(Closure $callback, int $attempts): mixed private function transaction(Closure $callback): mixed { try { - $result = $this->unitOfWork->execute(function () use ($callback) { + return $this->unitOfWork->execute(function () use ($callback) { $this->active = true; $value = $callback(); $this->executeBeforeCommit(); return $value; }); - $this->committed = true; - $this->executeAfterCommit(); - return $result; - } finally { - $this->active = false; - $this->committed = false; - $this->beforeCommit = []; - $this->afterCommit = []; + } catch (Throwable $ex) { + // Forget any callbacks registered by the failed attempt, so they are not executed twice. + $this->reset(); + throw $ex; } } + private function reset(): void + { + $this->active = false; + $this->committed = false; + $this->beforeCommit = []; + $this->afterCommit = []; + } + public function beforeCommit(callable $callback): void { if ($this->active && !$this->committed) { @@ -125,10 +138,31 @@ private function executeBeforeCommit(): void } } + /** + * Execute the 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. + */ private function executeAfterCommit(): void { + $exceptions = []; + while ($callback = array_shift($this->afterCommit)) { - $callback(); + try { + $callback(); + } catch (Throwable $ex) { + $exceptions[] = $ex; + } + } + + if (count($exceptions) === 1) { + throw $exceptions[0]; + } + + if (count($exceptions) > 1) { + throw new AfterCommitCallbacksFailed($exceptions); } } } diff --git a/tests/Unit/Application/UnitOfWork/AfterCommitCallbacksFailedTest.php b/tests/Unit/Application/UnitOfWork/AfterCommitCallbacksFailedTest.php new file mode 100644 index 00000000..33eed4a4 --- /dev/null +++ b/tests/Unit/Application/UnitOfWork/AfterCommitCallbacksFailedTest.php @@ -0,0 +1,40 @@ +assertInstanceOf(ApplicationException::class, $actual); + $this->assertSame('3 after commit callbacks failed.', $actual->getMessage()); + $this->assertSame($exceptions, $actual->exceptions()); + $this->assertSame($ex1, $actual->getPrevious()); + } +} diff --git a/tests/Unit/Application/UnitOfWork/UnitOfWorkManagerTest.php b/tests/Unit/Application/UnitOfWork/UnitOfWorkManagerTest.php index 61745e4a..85573261 100644 --- a/tests/Unit/Application/UnitOfWork/UnitOfWorkManagerTest.php +++ b/tests/Unit/Application/UnitOfWork/UnitOfWorkManagerTest.php @@ -14,6 +14,7 @@ use Closure; use CloudCreativity\Modules\Application\ApplicationException; +use CloudCreativity\Modules\Application\UnitOfWork\AfterCommitCallbacksFailed; use CloudCreativity\Modules\Application\UnitOfWork\UnitOfWorkManager; use CloudCreativity\Modules\Contracts\Application\Ports\UnitOfWork; use CloudCreativity\Modules\Testing\FakeExceptionReporter; @@ -442,6 +443,162 @@ function () use (&$sequence): void { $this->assertSame([$ex, $ex], $this->reporter->reported); } + /** + * Scenario where an after commit callback fails. + * + * The unit of work has already been committed at this point, so the callback must not be + * retried. The remaining after commit callbacks must still be executed, and the exception + * from the after commit callback must be thrown as-is. + */ + #[Test] + public function it_does_not_retry_when_after_commit_callback_fails(): void + { + $ex = new LogicException('Boom!'); + $sequence = []; + $actual = null; + + $this->unitOfWork + ->expects($this->once()) + ->method('execute') + ->willReturnCallback(function (Closure $closure) use (&$sequence): mixed { + $sequence[] = 'begin'; + $result = $closure(); + $sequence[] = 'committed'; + return $result; + }); + + try { + $this->manager->execute(function () use ($ex, &$sequence): void { + $sequence[] = 'callback'; + $this->manager->afterCommit(function () use ($ex, &$sequence): void { + $sequence[] = 'after1'; + throw $ex; + }); + $this->manager->afterCommit(function () use (&$sequence): void { + $sequence[] = 'after2'; + }); + }, 3); + } catch (LogicException $e) { + $actual = $e; + } + + $this->assertSame($ex, $actual); + $this->assertSame(['begin', 'callback', 'committed', 'after1', 'after2'], $sequence); + $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!'); + $sequence = []; + $actual = null; + + $this->unitOfWork + ->expects($this->once()) + ->method('execute') + ->willReturnCallback(fn (Closure $closure): mixed => $closure()); + + try { + $this->manager->execute(function () use ($ex1, $ex2, &$sequence): void { + $this->manager->afterCommit(function () use ($ex1, &$sequence): void { + $sequence[] = 'after1'; + $this->manager->afterCommit(function () use (&$sequence): void { + $sequence[] = 'after4'; + }); + throw $ex1; + }); + $this->manager->afterCommit(function () use (&$sequence): void { + $sequence[] = 'after2'; + }); + $this->manager->afterCommit(function () use ($ex2, &$sequence): void { + $sequence[] = 'after3'; + throw $ex2; + }); + }, 3); + } catch (AfterCommitCallbacksFailed $e) { + $actual = $e; + } + + $this->assertInstanceOf(AfterCommitCallbacksFailed::class, $actual); + $this->assertSame('2 after commit callbacks failed.', $actual->getMessage()); + $this->assertSame([$ex1, $ex2], $actual->exceptions()); + $this->assertSame($ex1, $actual->getPrevious()); + $this->assertSame(['after1', 'after2', 'after3', 'after4'], $sequence); + $this->assertSame([], $this->reporter->reported); + } + + /** + * Scenario where the first attempt fails before commit, the second attempt commits, + * and then an after commit callback fails. + */ + #[Test] + public function it_does_not_retry_after_commit_following_a_failed_attempt(): void + { + $first = new RuntimeException('First attempt failed.'); + $ex = new LogicException('After commit failed.'); + $sequence = []; + $count = 0; + $actual = null; + + $this->unitOfWork + ->expects($this->exactly(2)) + ->method('execute') + ->willReturnCallback(function (Closure $closure) use (&$sequence): mixed { + try { + $sequence[] = 'begin'; + $result = $closure(); + $sequence[] = 'committed'; + return $result; + } catch (\Throwable $ex) { + $sequence[] = 'rollback'; + throw $ex; + } + }); + + try { + $this->manager->execute(function () use ($first, $ex, &$sequence, &$count): void { + $count++; + $this->manager->afterCommit(function () use ($ex, &$sequence): void { + $sequence[] = 'after1'; + throw $ex; + }); + if ($count === 1) { + throw $first; + } + }, 3); + } catch (LogicException $e) { + $actual = $e; + } + + $this->assertSame($ex, $actual); + $this->assertSame(['begin', 'rollback', 'begin', 'committed', 'after1'], $sequence); + $this->assertSame([$first], $this->reporter->reported); + } + + #[Test] + public function it_flushes_callbacks_when_after_commit_callback_fails(): void + { + $this->unitOfWork + ->expects($this->exactly(2)) + ->method('execute') + ->willReturnCallback(fn (Closure $callback) => $callback()); + + try { + $this->manager->execute(function () { + $this->manager->afterCommit(fn () => throw new LogicException('Boom!')); + }, 2); + } catch (LogicException) { + // expected + } + + // this would error if the manager is not empty at this point. + $actual = $this->manager->execute(fn () => 2); + + $this->assertSame(2, $actual); + } + #[Test] public function it_fails_if_before_callbacks_are_queued_before_transaction(): void {