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
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,17 @@ All notable changes to this project will be documented in this file. This projec

- `FakeUnitOfWork` now has an `executions` property, counting the number of times its `execute()` method has been
called.
- New `AfterCommitFailure` interface, implemented by the `AfterCommitCallbacksFailed` exception. Calling code can catch
this interface to know that the unit of work committed, but one or more after commit callbacks failed. Its
`exceptions()` method returns the exceptions thrown by the after commit callbacks.

### Changed

- `UnitOfWorkManager` now throws an `AfterCommitCallbacksFailed` exception if any after commit callback fails,
including when only one fails. Previously a single failure was rethrown as-is, which meant calling code could not
distinguish it from a unit of work that failed and did not commit. The original exception is available via the
`exceptions()` method, and is the previous exception.

- `FakeUnitOfWork` now records which execution each entry in its `sequence` belongs to, in the format
`execute:<execution>/<event>:<attempt>`, e.g. `execute:2/commit:1`. Previously entries were in the format
`<event>:<attempt>`, e.g. `commit:1`. As the unit of work manager handles re-attempts itself by executing the unit of
Expand Down
30 changes: 27 additions & 3 deletions docs/guide/application/units-of-work.md
Original file line number Diff line number Diff line change
Expand Up @@ -296,9 +296,30 @@ $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.
commit callbacks from being executed. Once they have all been executed, if any of them failed, an
`AfterCommitCallbacksFailed` exception is thrown - even if only one of them failed. Its `exceptions()` method returns
all the exceptions in the order they were thrown, and its previous exception is the first one.

This exception implements the `AfterCommitFailure` interface. Catch this interface if your code needs to distinguish a
unit of work that failed and was not committed, from one that was committed but where some of the after commit work
failed:

```php
use CloudCreativity\Modules\Contracts\Application\UnitOfWork\AfterCommitFailure;

try {
$manager->execute(function (): void {
// some work.
});
} catch (AfterCommitFailure $ex) {
// the unit of work committed, but some after commit work failed.
foreach ($ex->exceptions() as $failure) {
// ...
}
}
```

Any other exception thrown by `execute()` means the unit of work did not commit.

#### After Commit Queue

Expand Down Expand Up @@ -332,6 +353,9 @@ $manager->execute(function () use ($manager): void {

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.
Likewise, if the new unit of work fails and is not committed, its exception is thrown to the after commit callback that
started it. If not caught, it becomes one of the after commit failures of the outermost unit of work - which did
commit.

:::warning
While the queue is FIFO, your after commit callbacks should **never** rely on the order they are executed in, or on
Expand Down
17 changes: 7 additions & 10 deletions src/Application/UnitOfWork/AfterCommitCallbacksFailed.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,31 +12,28 @@

namespace CloudCreativity\Modules\Application\UnitOfWork;

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

final class AfterCommitCallbacksFailed extends RuntimeException implements ApplicationException
final class AfterCommitCallbacksFailed extends RuntimeException implements AfterCommitFailure
{
/**
* @param non-empty-list<Throwable> $exceptions
*/
public function __construct(private readonly array $exceptions)
{
assert(count($exceptions) > 1, 'Expecting more than one exception.');
assert(count($exceptions) > 0, 'Expecting at least one exception.');

$count = count($exceptions);

parent::__construct(
sprintf('%d after commit callbacks failed.', count($exceptions)),
$count === 1 ? '1 after commit callback failed.' : sprintf('%d after commit callbacks failed.', $count),
0,
$exceptions[0],
array_first($exceptions),
);
}

/**
* 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;
Expand Down
20 changes: 11 additions & 9 deletions src/Application/UnitOfWork/UnitOfWorkManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@
* 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.
*
* If any after commit callbacks fail, the outermost call to `execute()` throws an `AfterCommitFailure` once the
* queue has been drained. This indicates that the unit of work did commit, even though it threw.
*/
final class UnitOfWorkManager implements IUnitOfWorkManager
{
Expand Down Expand Up @@ -78,7 +81,8 @@ public function __construct(
* 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.
* than being executed before this method returns. Any failures of those callbacks are therefore thrown by the
* outermost call to this method.
*/
public function execute(Closure $callback, int $attempts = 1): mixed
{
Expand Down Expand Up @@ -208,9 +212,11 @@ private function executeBeforeCommit(): void
* 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.
* executed. Once the queue is drained, any failures are wrapped in a single `AfterCommitCallbacksFailed`
* exception - even if only one callback failed. This allows calling code to know that the unit of work did
* commit. This includes failures of after commit callbacks belonging to a unit of work started while draining.
*
* @throws AfterCommitCallbacksFailed
*/
private function drain(): void
{
Expand All @@ -227,11 +233,7 @@ private function drain(): void

$this->draining = false;

if (count($exceptions) === 1) {
throw $exceptions[0];
}

if (count($exceptions) > 1) {
if ($exceptions !== []) {
throw new AfterCommitCallbacksFailed($exceptions);
}
}
Expand Down
32 changes: 32 additions & 0 deletions src/Contracts/Application/UnitOfWork/AfterCommitFailure.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?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\Contracts\Application\UnitOfWork;

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

/**
* Thrown when a unit of work committed, but one or more of its after commit callbacks failed.
*
* As the unit of work has committed, it cannot be rolled back or re-attempted. Catching this exception allows
* calling code to distinguish this scenario from a unit of work that failed and did not commit.
*/
interface AfterCommitFailure extends ApplicationException
{
/**
* Get the exceptions thrown by the after commit callbacks, in the order they were thrown.
*
* @return non-empty-list<Throwable>
*/
public function exceptions(): array;
}
7 changes: 7 additions & 0 deletions src/Contracts/Application/UnitOfWork/UnitOfWorkManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,23 @@
namespace CloudCreativity\Modules\Contracts\Application\UnitOfWork;

use Closure;
use Throwable;

interface UnitOfWorkManager
{
/**
* Execute the provided closure within a unit of work.
*
* If the closure (or committing the unit of work) fails, the exception is thrown and the unit of work will not
* have committed. If the unit of work commits but one or more after commit callbacks fail, an
* `AfterCommitFailure` exception is thrown instead. This allows calling code to distinguish the two scenarios.
*
* @template TReturn
* @param Closure(): TReturn $callback
* @param int<1, max> $attempts
* @return TReturn
* @throws AfterCommitFailure if the commit succeeded but an exception was thrown afterwards.
* @throws Throwable if an exception occurs during the unit of work.
*/
public function execute(Closure $callback, int $attempts = 1): mixed;

Expand Down
59 changes: 40 additions & 19 deletions tests/Integration/Testing/FakeUnitOfWorkManagerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use CloudCreativity\Modules\Application\ApplicationException;
use CloudCreativity\Modules\Application\UnitOfWork\AfterCommitCallbacksFailed;
use CloudCreativity\Modules\Application\UnitOfWork\UnitOfWorkManager;
use CloudCreativity\Modules\Contracts\Application\UnitOfWork\AfterCommitFailure;
use CloudCreativity\Modules\Testing\FakeExceptionReporter;
use CloudCreativity\Modules\Testing\FakeUnitOfWork;
use LogicException;
Expand Down Expand Up @@ -162,14 +163,15 @@ public function it_cannot_queue_a_before_commit_callback_from_an_after_commit_ca
$this->manager->execute(function (): void {
$this->manager->afterCommit(fn () => $this->manager->beforeCommit($this->record('before')));
});
} catch (ApplicationException $ex) {
} catch (AfterCommitCallbacksFailed $ex) {
$actual = $ex;
}

$this->assertInstanceOf(ApplicationException::class, $actual);
$previous = $this->assertSoleAfterCommitFailure($actual);
$this->assertInstanceOf(ApplicationException::class, $previous);
$this->assertSame(
'Cannot queue a before commit callback when not executing a unit of work.',
$actual->getMessage(),
$previous->getMessage(),
);
$this->assertSame([], $this->log);
$this->assertSame(['execute:1/attempt:1', 'execute:1/commit:1'], $this->unitOfWork->sequence);
Expand Down Expand Up @@ -327,11 +329,11 @@ public function it_does_not_retry_when_an_after_commit_callback_fails(): void
});
$this->manager->afterCommit($this->record('after2'));
}, 3);
} catch (LogicException $e) {
} catch (AfterCommitCallbacksFailed $e) {
$actual = $e;
}

$this->assertSame($ex, $actual);
$this->assertSame($ex, $this->assertSoleAfterCommitFailure($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);
Expand Down Expand Up @@ -409,11 +411,11 @@ public function it_executes_remaining_callbacks_when_a_queued_callback_fails():
$this->manager->afterCommit($this->record('after4'));
});
});
} catch (LogicException $e) {
} catch (AfterCommitCallbacksFailed $e) {
$actual = $e;
}

$this->assertSame($ex, $actual);
$this->assertSame($ex, $this->assertSoleAfterCommitFailure($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);
Expand Down Expand Up @@ -701,11 +703,11 @@ public function it_executes_remaining_after_commit_callbacks_when_a_nested_unit_
});
$this->manager->afterCommit($this->record('outer:after'));
});
} catch (LogicException $e) {
} catch (AfterCommitCallbacksFailed $e) {
$actual = $e;
}

$this->assertSame($ex, $actual);
$this->assertSame($ex, $this->assertSoleAfterCommitFailure($actual));
$this->assertSame(['outer:after'], $this->log);
$this->assertSame([
'execute:1/attempt:1',
Expand Down Expand Up @@ -741,11 +743,11 @@ public function it_executes_remaining_after_commit_callbacks_when_a_nested_after
});
$this->manager->afterCommit($this->record('outer:after'));
});
} catch (LogicException $e) {
} catch (AfterCommitCallbacksFailed $e) {
$actual = $e;
}

$this->assertSame($ex, $actual);
$this->assertSame($ex, $this->assertSoleAfterCommitFailure($actual));
$this->assertSame(['nested:result', 'outer:after', 'nested:after'], $this->log);
$this->assertSame([
'execute:1/attempt:1',
Expand All @@ -770,14 +772,15 @@ public function it_cannot_start_a_unit_of_work_within_a_nested_unit_of_work(): v
});
$this->manager->afterCommit($this->record('outer:after'));
});
} catch (ApplicationException $ex) {
} catch (AfterCommitCallbacksFailed $ex) {
$actual = $ex;
}

$this->assertInstanceOf(ApplicationException::class, $actual);
$previous = $this->assertSoleAfterCommitFailure($actual);
$this->assertInstanceOf(ApplicationException::class, $previous);
$this->assertSame(
'Not expecting unit of work manager to start a unit of work within an existing one.',
$actual->getMessage(),
$previous->getMessage(),
);
$this->assertSame(['outer:after'], $this->log);
$this->assertSame([
Expand All @@ -786,7 +789,7 @@ public function it_cannot_start_a_unit_of_work_within_a_nested_unit_of_work(): v
'execute:2/attempt:1',
'execute:2/rollback:1',
], $this->unitOfWork->sequence);
$this->assertSame([$actual], $this->unitOfWork->exceptions->reported);
$this->assertSame([$previous], $this->unitOfWork->exceptions->reported);
}

#[Test]
Expand All @@ -801,14 +804,15 @@ public function it_cannot_queue_a_before_commit_callback_from_an_after_commit_ca
$this->manager->beforeCommit($this->record('before'));
});
});
} catch (ApplicationException $ex) {
} catch (AfterCommitCallbacksFailed $ex) {
$actual = $ex;
}

$this->assertInstanceOf(ApplicationException::class, $actual);
$previous = $this->assertSoleAfterCommitFailure($actual);
$this->assertInstanceOf(ApplicationException::class, $previous);
$this->assertSame(
'Cannot queue a before commit callback when not executing a unit of work.',
$actual->getMessage(),
$previous->getMessage(),
);
$this->assertSame([], $this->log);
$this->assertSame([
Expand Down Expand Up @@ -862,7 +866,7 @@ public function it_is_reset_after_a_nested_unit_of_work_fails(): void
$this->manager->execute(fn () => throw new LogicException('Boom!'));
});
});
} catch (LogicException) {
} catch (AfterCommitCallbacksFailed) {
// expected
}

Expand Down Expand Up @@ -909,6 +913,23 @@ public function it_cannot_queue_a_before_commit_callback_once_the_unit_of_work_h
$this->manager->beforeCommit($this->record('before'));
}

/**
* Assert that the after commit callbacks failed with exactly one exception, and return that exception.
*/
private function assertSoleAfterCommitFailure(?AfterCommitCallbacksFailed $actual): Throwable
{
$this->assertInstanceOf(AfterCommitCallbacksFailed::class, $actual);
$this->assertInstanceOf(AfterCommitFailure::class, $actual);
$this->assertSame('1 after commit callback failed.', $actual->getMessage());

$exceptions = $actual->exceptions();

$this->assertCount(1, $exceptions);
$this->assertSame($exceptions[0], $actual->getPrevious());

return $exceptions[0];
}

/**
* Create a callback that records the provided entry in the log.
*
Expand Down
Loading