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
25 changes: 25 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:<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
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
Expand Down
74 changes: 68 additions & 6 deletions docs/guide/application/units-of-work.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:<execution>/<event>:<attempt>`. 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.
110 changes: 90 additions & 20 deletions src/Application/UnitOfWork/UnitOfWorkManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,28 +19,67 @@
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,
private readonly ?ExceptionReporter $reporter = null,
) {
}

/**
* 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) {
Expand All @@ -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
Expand Down Expand Up @@ -97,37 +145,53 @@ 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) {
$this->afterCommit[] = $callback;
return;
}

if ($this->draining) {
$this->queue[] = $callback;
return;
}

throw new ApplicationException('Cannot queue an after commit callback when not executing a unit of work.');
}

Expand All @@ -139,24 +203,30 @@ 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) {
$exceptions[] = $ex;
}
}

$this->draining = false;

if (count($exceptions) === 1) {
throw $exceptions[0];
}
Expand Down
27 changes: 24 additions & 3 deletions src/Testing/FakeUnitOfWork.php
Original file line number Diff line number Diff line change
Expand Up @@ -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:<execution>/<event>:<attempt>`, where the event is `attempt`, `commit` or
* `rollback`, and the attempt is the attempt number within that execution.
*
* @var list<string>
*/
public array $sequence = [];
Expand Down Expand Up @@ -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);

Expand Down
Loading