Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 8 additions & 0 deletions docs/guide/application/units-of-work.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
44 changes: 44 additions & 0 deletions src/Application/UnitOfWork/AfterCommitCallbacksFailed.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

/*
* Copyright 2026 Cloud Creativity Limited
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/

declare(strict_types=1);

namespace CloudCreativity\Modules\Application\UnitOfWork;

use CloudCreativity\Modules\Contracts\Application\ApplicationException;
use RuntimeException;
use Throwable;

final class AfterCommitCallbacksFailed extends RuntimeException implements ApplicationException
{
/**
* @param non-empty-list<Throwable> $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<Throwable>
*/
public function exceptions(): array
{
return $this->exceptions;
}
}
56 changes: 45 additions & 11 deletions src/Application/UnitOfWork/UnitOfWorkManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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) {
Expand Down Expand Up @@ -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);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

/*
* Copyright 2026 Cloud Creativity Limited
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/

declare(strict_types=1);

namespace CloudCreativity\Modules\Tests\Unit\Application\UnitOfWork;

use CloudCreativity\Modules\Application\UnitOfWork\AfterCommitCallbacksFailed;
use CloudCreativity\Modules\Contracts\Application\ApplicationException;
use LogicException;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
use RuntimeException;

final class AfterCommitCallbacksFailedTest extends TestCase
{
#[Test]
public function it_wraps_multiple_exceptions(): void
{
$exceptions = [
$ex1 = new LogicException('Boom 1!'),
new RuntimeException('Boom 2!'),
new LogicException('Boom 3!'),
];

$actual = new AfterCommitCallbacksFailed($exceptions);

$this->assertInstanceOf(ApplicationException::class, $actual);
$this->assertSame('3 after commit callbacks failed.', $actual->getMessage());
$this->assertSame($exceptions, $actual->exceptions());
$this->assertSame($ex1, $actual->getPrevious());
}
}
157 changes: 157 additions & 0 deletions tests/Unit/Application/UnitOfWork/UnitOfWorkManagerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
{
Expand Down
Loading