diff --git a/README.md b/README.md index b1fed66..9195e87 100644 --- a/README.md +++ b/README.md @@ -80,9 +80,15 @@ The engine instance leaves it out of its next claims, so it can't starve the oth > [!WARNING] > This state is kept per engine instance. A process that makes a single call and exits runs into a failing subscription every time and starves the others, so workers have to loop within the process. Always check `successful()`, a repeating failure is otherwise only visible through the `SubscriberFailedToHandleEvent` and `CatchUpRunFailed` engine events. -### Stop workers before `reset()` +### `reset()` and `setup()` with running workers -`setup()` and `reset()` don't skip locked subscriptions, but they don't hold locks either. A worker can catch up a subscription while its `reset()` handler is running. +Workers don't have to be stopped. `reset()` waits for running catch-ups and sets the status `RESETTING`, which no catch-up matches, for all matching subscriptions. The reset functions then run without a lock, so they can use DDL like `TRUNCATE`, and each subscription goes to `BOOTING` at position 0 afterwards. + +- If a reset function fails, the subscription goes to `ERROR` and no worker continues on the partially cleared projection. Call `reset()` again to retry +- If a subscription is already `RESETTING`, another reset is running or has crashed. `reset()` skips it and reports an error. Once you know that the other process is gone, take over with `reset($criteria, force: true)`. This runs the reset function again +- `reset()` throws if it can't get the locks in time or runs into a deadlock with a blocking worker, which is possible on MySQL and MariaDB. Nothing has changed in that case and the call can be repeated + +`setup()` does not stop workers: Its functions run while events are being handled, so they have to stay compatible with the running code. Stop the workers for a setup that needs exclusive access. See [docs/decisions.md](./docs/decisions.md) for the reasoning. @@ -131,6 +137,11 @@ public function claimNext(SubscriptionCriteria $criteria): Subscription|null; It locks and returns the matching subscription with the lowest position that is not locked by another process, with ties broken by id, without waiting for locks. It must not lock any other subscription, and has to return the state at the time of the lock. +`SubscriptionStatus` has the new case `RESETTING`, code with an exhaustive `match` has to handle it. A failing reset function now moves the subscription to `ERROR`, it used to keep its status. + +> [!WARNING] +> Up to 1.x workers keep running during `setup()` and `reset()`, which can handle events twice or write back an old position. On 1.x stop all workers for both. If workers were running during one of those calls, `reset()` and replay the affected subscriptions. + > [!WARNING] > Up to 1.x a deadlock inside a subscriber handler on MySQL or MariaDB could persist positions without the events they stand for, for all subscriptions of that run. This can't be detected afterwards. If such deadlocks occurred, `reset()` and replay the affected subscriptions. diff --git a/docs/decisions.md b/docs/decisions.md index 6874fd4..5dc5f19 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -116,7 +116,7 @@ Several workers should be able to call the engine on the same set of subscriptio | 14 | Retrying them | The list is cleared for the criteria of a call, if the claim found nothing or a claimed active subscription had no events, or if nothing else is left to claim | The rest has no work, so the failed subscription gets one retry per cycle and a temporary error recovers by itself. `ERROR` is no option: It requires a `reset()` and a full replay | | 15 | Set-aside and `hasPendingEvents` | Set-aside subscriptions don't count as pending | Otherwise `while ($result->hasPendingEvents)` would never end | | 16 | Exceptions that still escape | From `beginTransaction()` and `claimNext()`, as no subscription is involved, and from listeners after the commit, as the batch is persisted | There is nothing to set aside, and an unavailable database must stay visible | -| 17 | `setup()`, `reset()`, discovery | Keep blocking | Discovery would treat a locked row as missing, and `add()` would fail with a duplicate key. `setup()` and `reset()` would silently miss subscriptions | +| 17 | `setup()`, `reset()`, discovery | Don't skip locked rows | Discovery would treat a locked row as missing, and `add()` would fail with a duplicate key. `setup()` and `reset()` would silently miss subscriptions. See [The reset() race](#the-reset-race-target-20) for how they use locks now | | 18 | Recursion guard | Unchanged, also for the new methods | A nested call on the same connection sees the lock of the outer run as free. The guard throws for `ids === null` and overlapping ids, so `claimNext()` can't return a subscription that is being processed | | 19 | Processed subscription on the result | Not part of `ProcessedResult` | `CatchUpStarted` and `CatchUpFinished` already carry it, and no caller logic needs it | | 20 | SQLite | Serial: `LIMIT 1` with the same ordering, without `FOR UPDATE` | `BEGIN EXCLUSIVE` already makes a second worker wait before it claims anything. Each event is still handled once, only the parallelism is lost | @@ -136,6 +136,45 @@ Several workers should be able to call the engine on the same set of subscriptio ### Open points -- `setup()` and `reset()` call `findByCriteriaForUpdate()` outside of a transaction, so the lock is released immediately and a worker can catch up while a `reset()` handler is running. This race already exists, but always-running workers make it more likely. A transaction is no simple fix, as DDL in handlers commits implicitly on MySQL. Until then: Stop workers before `reset()`. - A persisted failure counter that moves a subscription to `ERROR` after N failed runs would also cover short-lived processes. It requires a new column, a new field on `Subscription`, and a choice of N. It can be added later without conflicting with the set-aside. - The `read()` filter/query follow-up: With filtered subscriptions, a position can stay behind `lastPosition()` although no matching event is left, so `hasPendingEvents` would stay `true`. + +## The reset() race (target: 2.0) + +### Context + +`setup()` and `reset()` called `findByCriteriaForUpdate()` outside of a transaction, so the lock was released right away and workers kept running during the handlers. Both races were reproduced: + +- **`reset()`:** A worker catches up during the handler. With a subscription `ACTIVE` at position 2 and 5 events, the projection ends up with `[3,4,5,1,2,3,4,5]`: Events 3 to 5 are handled twice. +- **`setup()`:** A worker commits during the handler of a `BOOTING` subscription and the stale position is written back. The projection ends up with `[1,2,3,1,2,3,4,5]`. + +Holding a transaction during the handler is no option. `TRUNCATE` and DDL commit implicitly on MySQL and MariaDB, the store then fails with "The database has ended the transaction". + +### Decisions + +| # | Topic | Decision | Why | +|---|-------|----------|-----| +| 1 | Keeping workers out of `reset()` | A status fence: A short transaction waits for the row locks and sets `SubscriptionStatus::RESETTING`, which no catch-up matches. The handlers run without a lock, then the subscription goes to `BOOTING` at position 0 | Waiting for the lock also waits for in-flight runs. Handlers can use DDL. The store contract stays unchanged, a status is no schema change | +| 2 | Fixing `setup()` | The handlers keep running without lock and fence. The status change happens in a short transaction on a freshly read row | A fence would stop all workers during every `setup()`. Setup handlers have to stay compatible with running event handlers | +| 3 | Scope | 2.0 only, no backport to 1.x. The upgrade notes warn about 1.x | The new status could break consumers with an exhaustive `match` | +| 4 | Scope of the fence | One transaction for all matching subscriptions that have a subscriber. If a lock can't be acquired: Roll back, rethrow, nothing changed. Subscriptions without subscriber keep `SubscriberNotFound` and don't change | All workers have stopped before the first handler runs, which protects handlers that clear a table shared by several subscriptions | +| 5 | Failing reset handler | The subscription goes to `ERROR`, with an unchanged position and the status before the fence as `previousStatus`. The others continue, and the result is failed | Keeping the previous status, as before, lets workers continue on a half-cleared projection. `ERROR` is ignored by catch-ups and `setup()`, and `reset()` retries it | +| 6 | Already `RESETTING` | `reset()` does not run the handler. It dispatches `ResetAlreadyInProgress` at warning level and reports an `Error`, the others continue. `reset($criteria, force: true)` takes over | Another reset is running or one has crashed, and the engine can't tell which. Proceeding would let a second handler clear rows of a boot that the first reset has started. Any timeout based on `last_saved_at` is wrong for some long handler and depends on clocks | +| 7 | Exception escaping the final write | The exception escapes. That subscription and the remaining ones of the call stay `RESETTING` | The database may be gone. `force: true` recovers, and the handlers run again | +| 8 | Reads in `setup()` | Discovery and the main list use `findByCriteria()` | Outside of a transaction the lock had no effect, they only waited for running catch-ups | +| 9 | Transition in `setup()` | Per subscription: Lock the row if it is still `NEW`, `BOOTING` or `ACTIVE`, and decide by that fresh state. `NEW` goes to `BOOTING`. With `FROM_NOW`, `NEW` and `BOOTING` go to `ACTIVE` at `lastPosition()`. `BOOTING` with `FROM_BEGINNING` and `ACTIVE` are not written. Any other status is left alone. An exception rolls back and is rethrown | A position written by a worker can't regress, and the fence of a concurrent `reset()` isn't overwritten | +| 10 | Failing setup handler, detaching | Same short transaction: `ERROR` or `DETACHED` on the fresh row, only if it still matches | A failing handler must not write a stale position either | +| 11 | Recursion guard | `setup()` and `reset()` throw `RecursiveCatchUpException` if called during a catch-up with `ids === null` or overlapping ids. The name stays, a second class isn't worth it | On the same connection the fence wouldn't wait for the lock of the outer run and its commit wouldn't end the outer transaction. The outer run would then overwrite `RESETTING` with `ACTIVE`. A catch-up called from a reset handler needs no guard, it finds nothing because of the fence | +| 12 | Engine events | `SubscriberWasReset` reports the status from before the fence. Events of the fence are dispatched after its commit | The change from `ACTIVE` to `BOOTING` is what the log should say. A listener must not be able to roll back the fence | +| 13 | Tests | Engine tests that run a worker inside the handler, two-connection tests for lock waits, and worker processes on all databases running `reset()` with a `TRUNCATE` handler | Implicit commits and the lock behavior of a status change can't be observed in memory | + +### Known consequences + +- **New status value.** Code with an exhaustive `match` on `SubscriptionStatus` has to handle `RESETTING`. Stores with a string column need no change. +- **The fence can deadlock with a blocking worker on MySQL and MariaDB.** The worker holds a record of the `status` index and waits for the primary key, the fence holds the primary key and needs that index record for its `UPDATE`. Reproduced on MariaDB 11.4 in 2 of 6 test runs with 4 resets each, not on MySQL 8.4 or PostgreSQL 17. Whichever side is rolled back has changed nothing: `reset()` throws and can be repeated, a catch-up repeats its batch. Workers using `claimNext()` hold no such index record. +- **A long catch-up delays the fence.** `reset()` waits for running batches, and rows that are already locked wait with it. Bounded runs shorten that. +- **A crashed `reset()` stays visible.** The subscription stays `RESETTING` and receives no events until someone calls `reset($criteria, force: true)`. Calling that while the other reset is still running recreates the race. +- **`force: true` runs the handler again.** Reset handlers have to tolerate running twice. +- **Handlers of one call run in sequence.** All subscriptions of the call stay fenced until their handler is done. +- **Setup handlers run while workers are active.** A handler that needs exclusive access requires stopped workers. +- **Concurrent discovery can fail.** Two simultaneous `setup()` calls can both `add()` the same new subscription, the second one fails with a duplicate key. That is loud, a retry fixes it and no data is damaged. A fix requires an upsert in the store contract. diff --git a/src/Engine/EngineEvent/ResetAlreadyInProgress.php b/src/Engine/EngineEvent/ResetAlreadyInProgress.php new file mode 100644 index 0000000..0922a80 --- /dev/null +++ b/src/Engine/EngineEvent/ResetAlreadyInProgress.php @@ -0,0 +1,28 @@ + + */ +final readonly class ResetAlreadyInProgress implements EngineEvent +{ + public function __construct( + public Subscription $subscription, + ) { + } + + public function logLevel(): int + { + return LOG_WARNING; + } + + public function __toString(): string + { + return sprintf('Subscription "%s" is already being reset, or a previous reset has crashed. Skipping it, use the "force" flag to take over', $this->subscription->id->value); + } +} diff --git a/src/Subscription/SubscriptionStatus.php b/src/Subscription/SubscriptionStatus.php index 88eb3e2..2d12126 100644 --- a/src/Subscription/SubscriptionStatus.php +++ b/src/Subscription/SubscriptionStatus.php @@ -30,7 +30,12 @@ enum SubscriptionStatus : string case DETACHED = 'DETACHED'; /** - * Subscribers that are run into an error during catchup or setup + * Subscribers that are run into an error during catchup, setup or reset */ case ERROR = 'ERROR'; + + /** + * Subscribers whose reset function is running: Catch-ups and setup ignore them. If a reset has crashed, the subscription stays in this status until it is reset with the "force" flag + */ + case RESETTING = 'RESETTING'; } diff --git a/src/SubscriptionEngine.php b/src/SubscriptionEngine.php index d2d777d..7380220 100644 --- a/src/SubscriptionEngine.php +++ b/src/SubscriptionEngine.php @@ -17,6 +17,7 @@ use Wwwision\SubscriptionEngine\Engine\EngineEvent\FailedToSetupSubscriber; use Wwwision\SubscriptionEngine\Engine\EngineEvent\NoResetResetFunctionDefined; use Wwwision\SubscriptionEngine\Engine\EngineEvent\NoSubscriptionsFound; +use Wwwision\SubscriptionEngine\Engine\EngineEvent\ResetAlreadyInProgress; use Wwwision\SubscriptionEngine\Engine\EngineEvent\ResetStarted; use Wwwision\SubscriptionEngine\Engine\EngineEvent\SetupStarted; use Wwwision\SubscriptionEngine\Engine\EngineEvent\SubscriberFailedToHandleEvent; @@ -94,16 +95,13 @@ public function setup(SubscriptionEngineCriteria|null $criteria = null): Result { $criteria ??= SubscriptionEngineCriteria::noConstraints(); $this->assertKnownSubscriptionIds($criteria); + $subscriptionCriteria = SubscriptionCriteria::forEngineCriteriaAndStatus($criteria, self::statusesToSetUp()); + $this->assertNoRecursiveCall($subscriptionCriteria); $this->dispatchEngineEvent(new SetupStarted()); $this->subscriptionStore->setup(); $this->discoverNewSubscriptions(); - $subscriptionCriteria = SubscriptionCriteria::forEngineCriteriaAndStatus($criteria, SubscriptionStatusFilter::fromArray([ - SubscriptionStatus::NEW, - SubscriptionStatus::BOOTING, - SubscriptionStatus::ACTIVE - ])); - $subscriptions = $this->subscriptionStore->findByCriteriaForUpdate($subscriptionCriteria); + $subscriptions = $this->subscriptionStore->findByCriteria($subscriptionCriteria); if ($subscriptions->isEmpty()) { $this->dispatchEngineEvent(new NoSubscriptionsFound($subscriptionCriteria)); return Result::success(); @@ -148,20 +146,26 @@ public function bootNext(SubscriptionEngineCriteria|null $criteria = null, int|n return $this->catchUpNext($criteria ?? SubscriptionEngineCriteria::noConstraints(), SubscriptionStatus::BOOTING, $limit); } - public function reset(SubscriptionEngineCriteria|null $criteria = null): Result + /** + * Waits for running catch-ups and keeps new ones out with the status {@see SubscriptionStatus::RESETTING}, while the reset functions run without a lock + * + * @param bool $force Whether to take over subscriptions that are already {@see SubscriptionStatus::RESETTING}. Only use this if the process that started the reset is gone + */ + public function reset(SubscriptionEngineCriteria|null $criteria = null, bool $force = false): Result { $criteria ??= SubscriptionEngineCriteria::noConstraints(); $this->assertKnownSubscriptionIds($criteria); - $this->dispatchEngineEvent(new ResetStarted()); $subscriptionCriteria = SubscriptionCriteria::forEngineCriteriaAndStatus($criteria, SubscriptionStatusFilter::any()); - $subscriptions = $this->subscriptionStore->findByCriteriaForUpdate($subscriptionCriteria); + $this->assertNoRecursiveCall($subscriptionCriteria); + $this->dispatchEngineEvent(new ResetStarted()); + $subscriptions = $this->fenceSubscriptions($subscriptionCriteria, $force); if ($subscriptions->isEmpty()) { $this->dispatchEngineEvent(new NoSubscriptionsFound($subscriptionCriteria)); return Result::success(); } $errors = []; foreach ($subscriptions as $subscription) { - $error = $this->resetSubscription($subscription); + $error = $this->resetSubscription($subscription, $force); if ($error !== null) { $errors[] = $error; } @@ -214,7 +218,7 @@ private function assertKnownSubscriptionIds(SubscriptionEngineCriteria $criteria */ private function discoverNewSubscriptions(): void { - $subscriptions = $this->subscriptionStore->findByCriteriaForUpdate(SubscriptionCriteria::noConstraints()); + $subscriptions = $this->subscriptionStore->findByCriteria(SubscriptionCriteria::noConstraints()); foreach ($this->subscribers as $subscriber) { if ($subscriptions->contain($subscriber->id)) { continue; @@ -233,15 +237,26 @@ private function discoverNewSubscriptions(): void /** * Set up the subscription by retrieving the corresponding subscriber and calling the setUp method on its handler * If the setup fails, the subscription will be in the {@see SubscriptionStatus::ERROR} state and a corresponding {@see Error} is returned + * + * The handler runs without a lock, so that it can use DDL. A worker can change the subscription in the meantime, so the transition is decided by its fresh state */ private function setupSubscription(Subscription $subscription): ?Error { if (!$this->subscribers->contain($subscription->id)) { // mark detached subscriptions as we cannot set up $this->dispatchEngineEvent(new SubscriberNotFound($subscription)); - $subscription = $subscription->with(status: SubscriptionStatus::DETACHED); - $this->subscriptionStore->update($subscription); - $this->dispatchEngineEvent(new SubscriptionDetached($subscription)); + $detached = $this->transactional(function () use ($subscription) { + $freshSubscription = $this->findSubscriptionToSetUpForUpdate($subscription->id); + if ($freshSubscription === null) { + return null; + } + $detached = $freshSubscription->with(status: SubscriptionStatus::DETACHED); + $this->subscriptionStore->update($detached); + return $detached; + }); + if ($detached !== null) { + $this->dispatchEngineEvent(new SubscriptionDetached($detached)); + } return null; } @@ -251,31 +266,90 @@ private function setupSubscription(Subscription $subscription): ?Error ($subscriber->setup)(); } catch (Throwable $e) { $this->dispatchEngineEvent(new FailedToSetupSubscriber($subscription, $e)); - $this->subscriptionStore->update($subscription->withError(SubscriptionError::fromPreviousStatusAndException($subscription->status, $e))); + $this->transactional(function () use ($subscription, $e) { + $freshSubscription = $this->findSubscriptionToSetUpForUpdate($subscription->id); + if ($freshSubscription !== null) { + $this->subscriptionStore->update($freshSubscription->withError(SubscriptionError::fromPreviousStatusAndException($freshSubscription->status, $e))); + } + }); return Error::create($subscription->id, $e->getMessage(), $e, null); } } - if ($subscription->status === SubscriptionStatus::ACTIVE) { - $this->dispatchEngineEvent(new ActiveSubscriptionSetup($subscription)); + $freshSubscription = $this->transactional(function () use ($subscription) { + $freshSubscription = $this->findSubscriptionToSetUpForUpdate($subscription->id); + if ($freshSubscription === null || $freshSubscription->status === SubscriptionStatus::ACTIVE) { + return $freshSubscription; + } + if ($freshSubscription->runMode === RunMode::FROM_NOW) { + $this->subscriptionStore->update($freshSubscription->with(status: SubscriptionStatus::ACTIVE, position: $this->eventStoreAdapter->lastPosition())); + } elseif ($freshSubscription->status === SubscriptionStatus::NEW) { + $this->subscriptionStore->update($freshSubscription->with(status: SubscriptionStatus::BOOTING)); + } + return $freshSubscription; + }); + if ($freshSubscription === null) { return null; } - if ($subscription->runMode === RunMode::FROM_NOW) { - $this->subscriptionStore->update($subscription->with(status: SubscriptionStatus::ACTIVE, position: $this->eventStoreAdapter->lastPosition())); - $this->dispatchEngineEvent(new SubscriberWasSetup($subscription, SubscriptionStatus::ACTIVE, $subscription->status)); + if ($freshSubscription->status === SubscriptionStatus::ACTIVE) { + $this->dispatchEngineEvent(new ActiveSubscriptionSetup($freshSubscription)); return null; } - $this->subscriptionStore->update($subscription->with(status: SubscriptionStatus::BOOTING)); - $this->dispatchEngineEvent(new SubscriberWasSetup($subscription, SubscriptionStatus::BOOTING, $subscription->status)); + $this->dispatchEngineEvent(new SubscriberWasSetup($freshSubscription, $freshSubscription->runMode === RunMode::FROM_NOW ? SubscriptionStatus::ACTIVE : SubscriptionStatus::BOOTING, $freshSubscription->status)); return null; } - private function resetSubscription(Subscription $subscription): ?Error + private static function statusesToSetUp(): SubscriptionStatusFilter + { + return SubscriptionStatusFilter::fromArray([ + SubscriptionStatus::NEW, + SubscriptionStatus::BOOTING, + SubscriptionStatus::ACTIVE, + ]); + } + + /** + * @return Subscription|null The current state of the subscription, or NULL if it must not be set up anymore, for example because a reset has started in the meantime + */ + private function findSubscriptionToSetUpForUpdate(SubscriptionId $subscriptionId): Subscription|null + { + $subscriptions = $this->subscriptionStore->findByCriteriaForUpdate(SubscriptionCriteria::create(SubscriptionIds::fromArray([$subscriptionId]), self::statusesToSetUp())); + return $subscriptions->contain($subscriptionId) ? $subscriptions->get($subscriptionId) : null; + } + + /** + * Waits for the locks of all matching subscriptions and sets the status that no catch-up matches, in one transaction: Once this returns, none of them is being processed anymore + * + * @return Subscriptions The state of the subscriptions before this call + */ + private function fenceSubscriptions(SubscriptionCriteria $subscriptionCriteria, bool $force): Subscriptions + { + return $this->transactional(function () use ($subscriptionCriteria, $force) { + $subscriptions = $this->subscriptionStore->findByCriteriaForUpdate($subscriptionCriteria); + foreach ($subscriptions as $subscription) { + if (!$this->subscribers->contain($subscription->id) || (!$force && $subscription->status === SubscriptionStatus::RESETTING)) { + continue; + } + $this->subscriptionStore->update($subscription->with(status: SubscriptionStatus::RESETTING)); + } + return $subscriptions; + }); + } + + /** + * @param Subscription $subscription The state before {@see self::fenceSubscriptions()} + */ + private function resetSubscription(Subscription $subscription, bool $force): ?Error { if (!$this->subscribers->contain($subscription->id)) { $this->dispatchEngineEvent(new SubscriberNotFound($subscription)); return null; } + if (!$force && $subscription->status === SubscriptionStatus::RESETTING) { + $event = new ResetAlreadyInProgress($subscription); + $this->dispatchEngineEvent($event); + return Error::create($subscription->id, (string)$event, null, null); + } $subscriber = $this->subscribers->get($subscription->id); if ($subscriber->reset === null) { $this->dispatchEngineEvent(new NoResetResetFunctionDefined($subscription)); @@ -284,6 +358,8 @@ private function resetSubscription(Subscription $subscription): ?Error ($subscriber->reset)(); } catch (Throwable $e) { $this->dispatchEngineEvent(new FailedToResetSubscriber($subscription, $e)); + // the projection may be partially cleared, so no catch-up must continue on it + $this->subscriptionStore->update($subscription->withError(SubscriptionError::fromPreviousStatusAndException($subscription->status, $e))); return Error::create($subscription->id, $e->getMessage(), $e, null); } } @@ -292,6 +368,24 @@ private function resetSubscription(Subscription $subscription): ?Error return null; } + /** + * @template T + * @param callable(): T $callback + * @return T + */ + private function transactional(callable $callback): mixed + { + $this->subscriptionStore->beginTransaction(); + try { + $result = $callback(); + $this->subscriptionStore->commit(); + return $result; + } catch (Throwable $e) { + $this->rollbackTransaction(); + throw $e; + } + } + private function catchUpSubscriptions(SubscriptionEngineCriteria $criteria, SubscriptionStatusFilter $status, int|null $limit): ProcessedResult { $subscriptionCriteria = $this->prepareCatchUp($criteria, $status, $limit); @@ -469,14 +563,25 @@ private function prepareCatchUp(SubscriptionEngineCriteria $criteria, Subscripti $this->dispatchEngineEvent(new CatchUpInitiated($criteria, $status)); $subscriptionCriteria = SubscriptionCriteria::forEngineCriteriaAndStatus($criteria, $status); - if (!$this->processingSubscriptions->isEmpty()) { - if ($subscriptionCriteria->ids === null || !$subscriptionCriteria->ids->intersection($this->processingSubscriptions)->isEmpty()) { - throw RecursiveCatchUpException::forSubscriptionIds($this->processingSubscriptions, $subscriptionCriteria->ids); - } - } + $this->assertNoRecursiveCall($subscriptionCriteria); return $subscriptionCriteria; } + /** + * On the same connection, a lock of the running catch-up looks free. Its commit would also overwrite whatever a nested call has changed + * + * @throws RecursiveCatchUpException + */ + private function assertNoRecursiveCall(SubscriptionCriteria $subscriptionCriteria): void + { + if ($this->processingSubscriptions->isEmpty()) { + return; + } + if ($subscriptionCriteria->ids === null || !$subscriptionCriteria->ids->intersection($this->processingSubscriptions)->isEmpty()) { + throw RecursiveCatchUpException::forSubscriptionIds($this->processingSubscriptions, $subscriptionCriteria->ids); + } + } + /** * Passes the events to the given subscriptions and persists their new state, without ending the transaction * diff --git a/tests/Mocks/InMemorySubscriptionStore.php b/tests/Mocks/InMemorySubscriptionStore.php index a27a029..dd1e229 100644 --- a/tests/Mocks/InMemorySubscriptionStore.php +++ b/tests/Mocks/InMemorySubscriptionStore.php @@ -54,6 +54,9 @@ public function findByCriteria(SubscriptionCriteria $criteria): Subscriptions public function findByCriteriaForUpdate(SubscriptionCriteria $criteria): Subscriptions { + if ($this->transactionSnapshots === []) { + throw new \LogicException('A lock outside of a transaction is released right away'); + } return $this->filterByCriteria($criteria); } diff --git a/tests/PHPUnit/Engine/SubscriptionEngineTest.php b/tests/PHPUnit/Engine/SubscriptionEngineTest.php index 78532e9..436665e 100644 --- a/tests/PHPUnit/Engine/SubscriptionEngineTest.php +++ b/tests/PHPUnit/Engine/SubscriptionEngineTest.php @@ -476,7 +476,7 @@ public function test_reset_does_not_update_subscriptions_if_none_match(): void ); $this->assertEmittedEngineEvents( 'ResetStarted: Start to setup', - 'NoSubscriptionsFound: No subscriptions found for criteria: {"ids":["s3"],"status":["NEW","BOOTING","ACTIVE","DETACHED","ERROR"]}' + 'NoSubscriptionsFound: No subscriptions found for criteria: {"ids":["s3"],"status":["NEW","BOOTING","ACTIVE","DETACHED","ERROR","RESETTING"]}' ); self::assertTrue($result->successful()); self::assertFalse($this->subscriptionStore->_hasPendingChanges(), 'Subscription store has pending changes'); @@ -639,9 +639,9 @@ public function test_reset_handles_errors_in_reset_function(): void ); $result = $subscriptionEngine->reset(); - $this->assertSubscriptions( - ['id' => 's1', 'status' => 'ACTIVE', 'position' => 123, 'error' => null], - ); + self::assertSame(SubscriptionStatus::ERROR, $this->subscriptionStore->findByCriteria(SubscriptionCriteria::noConstraints())->get(SubscriptionId::fromString('s1'))->status); + self::assertSame(SubscriptionStatus::ACTIVE, $this->subscriptionStore->findByCriteria(SubscriptionCriteria::noConstraints())->get(SubscriptionId::fromString('s1'))->error?->previousStatus); + self::assertSame(123, $this->subscriptionStore->findByCriteria(SubscriptionCriteria::noConstraints())->get(SubscriptionId::fromString('s1'))->position->value); $this->assertEmittedEngineEvents( 'ResetStarted: Start to setup', 'FailedToResetSubscriber: Subscriber for "s1" has an error in the reset method: Exception from s1 reset function', @@ -649,8 +649,338 @@ public function test_reset_handles_errors_in_reset_function(): void self::assertSame('"s1": Exception from s1 reset function', $result->errors->getClampedMessage()); } - // --------------------- + public function test_reset_keeps_workers_out_while_its_handler_is_running(): void + { + $this->eventStore->append(1); + $this->eventStore->append(1); + $this->eventStore->append(1); + $this->subscriptionStore->_setSubscriptions(self::subscriptionAt('s1', SubscriptionStatus::ACTIVE, 2)); + $handled = []; + $handler = function (MockEvent $event) use (&$handled) { + $handled[] = $event->position->value; + }; + $worker = $this->subscriptionEngine(Subscriber::create(id: 's1', handler: $handler)); + $results = []; + $transactionActiveInHandler = null; + $engine = $this->subscriptionEngine(Subscriber::create(id: 's1', handler: $handler, reset: function () use ($worker, &$results, &$transactionActiveInHandler) { + $transactionActiveInHandler = $this->subscriptionStore->_isTransactionActive(); + $results[] = $worker->catchUpActive(); + $results[] = $worker->catchUpNextActive(); + $results[] = $worker->boot(); + $results[] = $worker->bootNext(); + })); + + $result = $engine->reset(); + + self::assertTrue($result->successful()); + self::assertFalse($transactionActiveInHandler, 'handlers must be able to use DDL'); + self::assertSame([], $handled); + self::assertSame([0, 0, 0, 0], array_map(static fn ($r) => $r->numberOfProcessedEvents, $results)); + $this->assertSubscriptions(['id' => 's1', 'status' => 'BOOTING', 'position' => 0, 'error' => null]); + } + + public function test_reset_fences_all_subscriptions_before_the_first_handler_runs(): void + { + $this->subscriptionStore->_setSubscriptions(self::subscriptionAt('s1', SubscriptionStatus::ACTIVE, 1), self::subscriptionAt('s2', SubscriptionStatus::BOOTING, 1), self::subscriptionAt('s3', SubscriptionStatus::ACTIVE, 1)); + $statusInHandler = []; + $engine = $this->subscriptionEngine( + Subscriber::create(id: 's1', handler: fn () => null, reset: function () use (&$statusInHandler) { + $statusInHandler = array_map(static fn (Subscription $s) => $s->status->value, iterator_to_array($this->subscriptionStore->findByCriteria(SubscriptionCriteria::noConstraints()), false)); + }), + Subscriber::create(id: 's2', handler: fn () => null), + ); + + $engine->reset(); + + self::assertSame(['RESETTING', 'RESETTING', 'ACTIVE'], $statusInHandler, 's3 has no subscriber and must not be fenced'); + $this->assertSubscriptions( + ['id' => 's1', 'status' => 'BOOTING', 'position' => 0, 'error' => null], + ['id' => 's2', 'status' => 'BOOTING', 'position' => 0, 'error' => null], + ['id' => 's3', 'status' => 'ACTIVE', 'position' => 1, 'error' => null], + ); + } + + public function test_reset_changes_nothing_if_the_fence_fails(): void + { + $this->subscriptionStore->_setSubscriptions(self::subscriptionAt('s1', SubscriptionStatus::ACTIVE, 1), self::subscriptionAt('s2', SubscriptionStatus::ACTIVE, 2)); + $this->subscriptionStore->_failOnUpdateOf('s2'); + $handlerCalled = false; + $engine = $this->subscriptionEngine( + Subscriber::create(id: 's1', handler: fn () => null, reset: function () use (&$handlerCalled) { + $handlerCalled = true; + }), + Subscriber::create(id: 's2', handler: fn () => null), + ); + + try { + $engine->reset(); + self::fail('Expected the exception to escape'); + } catch (\RuntimeException $e) { + self::assertSame('Update of s2 failed', $e->getMessage()); + } + self::assertFalse($handlerCalled); + self::assertFalse($this->subscriptionStore->_isTransactionActive()); + $this->assertSubscriptions( + ['id' => 's1', 'status' => 'ACTIVE', 'position' => 1, 'error' => null], + ['id' => 's2', 'status' => 'ACTIVE', 'position' => 2, 'error' => null], + ); + } + + public function test_reset_continues_with_other_subscriptions_if_a_handler_fails(): void + { + $this->subscriptionStore->_setSubscriptions(self::subscriptionAt('s1', SubscriptionStatus::ACTIVE, 1), self::subscriptionAt('s2', SubscriptionStatus::ACTIVE, 2)); + $engine = $this->subscriptionEngine( + Subscriber::create(id: 's1', handler: fn () => null, reset: fn () => throw new \RuntimeException('Exception from s1 reset function')), + Subscriber::create(id: 's2', handler: fn () => null), + ); + + $result = $engine->reset(); + + self::assertFalse($result->successful()); + $subscriptions = $this->subscriptionStore->findByCriteria(SubscriptionCriteria::noConstraints()); + self::assertSame(SubscriptionStatus::ERROR, $subscriptions->get(SubscriptionId::fromString('s1'))->status); + self::assertSame(SubscriptionStatus::BOOTING, $subscriptions->get(SubscriptionId::fromString('s2'))->status); + + // a retry recovers from ERROR without force + $retried = $this->subscriptionEngine(Subscriber::create(id: 's1', handler: fn () => null), Subscriber::create(id: 's2', handler: fn () => null))->reset(); + self::assertTrue($retried->successful()); + self::assertSame(SubscriptionStatus::BOOTING, $this->subscriptionStore->findByCriteria(SubscriptionCriteria::noConstraints())->get(SubscriptionId::fromString('s1'))->status); + } + + public function test_reset_refuses_a_subscription_that_is_already_resetting(): void + { + $this->subscriptionStore->_setSubscriptions(self::subscriptionAt('s1', SubscriptionStatus::RESETTING, 3), self::subscriptionAt('s2', SubscriptionStatus::ACTIVE, 2)); + $handlerCalled = false; + $engine = $this->subscriptionEngine( + Subscriber::create(id: 's1', handler: fn () => null, reset: function () use (&$handlerCalled) { + $handlerCalled = true; + }), + Subscriber::create(id: 's2', handler: fn () => null, reset: fn () => null), + ); + + $result = $engine->reset(); + + self::assertFalse($handlerCalled); + self::assertFalse($result->successful()); + self::assertStringContainsString('"s1"', $result->errors->getClampedMessage()); + $this->assertSubscriptions( + ['id' => 's1', 'status' => 'RESETTING', 'position' => 3, 'error' => null], + ['id' => 's2', 'status' => 'BOOTING', 'position' => 0, 'error' => null], + ); + $this->assertEmittedEngineEvents( + 'ResetStarted: Start to setup', + 'ResetAlreadyInProgress: Subscription "s1" is already being reset, or a previous reset has crashed. Skipping it, use the "force" flag to take over', + 'SubscriberWasReset: Subscriber for "s2" has been reset, changing status from ACTIVE to BOOTING', + ); + } + + public function test_reset_with_force_takes_over_a_subscription_that_is_resetting(): void + { + $this->subscriptionStore->_setSubscriptions(self::subscriptionAt('s1', SubscriptionStatus::RESETTING, 3)); + $handlerCalled = false; + $engine = $this->subscriptionEngine(Subscriber::create(id: 's1', handler: fn () => null, reset: function () use (&$handlerCalled) { + $handlerCalled = true; + })); + + $result = $engine->reset(force: true); + + self::assertTrue($handlerCalled); + self::assertTrue($result->successful()); + $this->assertSubscriptions(['id' => 's1', 'status' => 'BOOTING', 'position' => 0, 'error' => null]); + } + + public function test_reset_leaves_subscriptions_fenced_if_the_final_write_fails_and_force_recovers(): void + { + $this->subscriptionStore->_setSubscriptions(self::subscriptionAt('s1', SubscriptionStatus::ACTIVE, 1), self::subscriptionAt('s2', SubscriptionStatus::ACTIVE, 2)); + $engine = $this->subscriptionEngine( + Subscriber::create(id: 's1', handler: fn () => null, reset: function () { + $this->subscriptionStore->_failOnUpdateOf('s1'); + }), + Subscriber::create(id: 's2', handler: fn () => null), + ); + + try { + $engine->reset(); + self::fail('Expected the exception to escape'); + } catch (\RuntimeException $e) { + self::assertSame('Update of s1 failed', $e->getMessage()); + } + $this->assertSubscriptions( + ['id' => 's1', 'status' => 'RESETTING', 'position' => 1, 'error' => null], + ['id' => 's2', 'status' => 'RESETTING', 'position' => 2, 'error' => null], + ); + + $this->subscriptionStore->_failOnUpdateOf(); + self::assertTrue($this->subscriptionEngine(Subscriber::create(id: 's1', handler: fn () => null), Subscriber::create(id: 's2', handler: fn () => null))->reset(force: true)->successful()); + $this->assertSubscriptions( + ['id' => 's1', 'status' => 'BOOTING', 'position' => 0, 'error' => null], + ['id' => 's2', 'status' => 'BOOTING', 'position' => 0, 'error' => null], + ); + } + + public function test_setup_does_not_regress_the_position_written_by_a_worker_during_its_handler(): void + { + $this->eventStore->append(1); + $this->eventStore->append(1); + $this->eventStore->append(1); + $this->subscriptionStore->_setSubscriptions(Subscription::create(id: 's1', runMode: RunMode::FROM_BEGINNING, status: SubscriptionStatus::BOOTING)); + $worker = $this->subscriptionEngine(Subscriber::create(id: 's1', handler: fn () => null)); + $transactionActiveInHandler = null; + $engine = $this->subscriptionEngine(Subscriber::create(id: 's1', handler: fn () => null, setup: function () use ($worker, &$transactionActiveInHandler) { + $transactionActiveInHandler = $this->subscriptionStore->_isTransactionActive(); + $worker->boot(limit: 2); + })); + + $result = $engine->setup(); + + self::assertTrue($result->successful()); + self::assertFalse($transactionActiveInHandler); + $this->assertSubscriptions(['id' => 's1', 'status' => 'BOOTING', 'position' => 2, 'error' => null]); + } + + public function test_setup_does_not_downgrade_a_subscription_that_a_worker_activated_during_its_handler(): void + { + $this->eventStore->append(1); + $this->subscriptionStore->_setSubscriptions(Subscription::create(id: 's1', runMode: RunMode::FROM_BEGINNING, status: SubscriptionStatus::BOOTING)); + $worker = $this->subscriptionEngine(Subscriber::create(id: 's1', handler: fn () => null)); + $engine = $this->subscriptionEngine(Subscriber::create(id: 's1', handler: fn () => null, setup: fn () => $worker->boot())); + + $engine->setup(); + + $this->assertSubscriptions(['id' => 's1', 'status' => 'ACTIVE', 'position' => 1, 'error' => null]); + } + + public function test_setup_does_not_overwrite_the_fence_of_a_concurrent_reset(): void + { + $this->subscriptionStore->_setSubscriptions(self::subscriptionAt('s1', SubscriptionStatus::BOOTING, 2)); + $engine = $this->subscriptionEngine(Subscriber::create(id: 's1', handler: fn () => null, setup: function () { + $this->subscriptionStore->_setSubscriptions(self::subscriptionAt('s1', SubscriptionStatus::RESETTING, 2)); + })); + + self::assertTrue($engine->setup()->successful()); + + $this->assertSubscriptions(['id' => 's1', 'status' => 'RESETTING', 'position' => 2, 'error' => null]); + } + + public function test_setup_ignores_resetting_subscriptions(): void + { + $this->subscriptionStore->_setSubscriptions(self::subscriptionAt('s1', SubscriptionStatus::RESETTING, 2)); + $handlerCalled = false; + $engine = $this->subscriptionEngine(Subscriber::create(id: 's1', handler: fn () => null, setup: function () use (&$handlerCalled) { + $handlerCalled = true; + })); + + $engine->setup(); + + self::assertFalse($handlerCalled); + $this->assertSubscriptions(['id' => 's1', 'status' => 'RESETTING', 'position' => 2, 'error' => null]); + } + + public function test_setup_writes_a_failing_handler_on_the_fresh_subscription(): void + { + $this->subscriptionStore->_setSubscriptions(self::subscriptionAt('s1', SubscriptionStatus::BOOTING, 0)); + $worker = $this->subscriptionEngine(Subscriber::create(id: 's1', handler: fn () => null)); + $this->eventStore->append(1); + $this->eventStore->append(1); + $engine = $this->subscriptionEngine(Subscriber::create(id: 's1', handler: fn () => null, setup: function () use ($worker) { + $worker->boot(limit: 1); + throw new \RuntimeException('Exception from s1 setup function'); + })); + + self::assertFalse($engine->setup()->successful()); + + $subscription = $this->subscriptionStore->findByCriteria(SubscriptionCriteria::noConstraints())->get(SubscriptionId::fromString('s1')); + self::assertSame(SubscriptionStatus::ERROR, $subscription->status); + self::assertSame(1, $subscription->position->value); + } + + public function test_setup_does_not_overwrite_a_fence_with_a_failing_handler(): void + { + $this->subscriptionStore->_setSubscriptions(self::subscriptionAt('s1', SubscriptionStatus::BOOTING, 2)); + $engine = $this->subscriptionEngine(Subscriber::create(id: 's1', handler: fn () => null, setup: function () { + $this->subscriptionStore->_setSubscriptions(self::subscriptionAt('s1', SubscriptionStatus::RESETTING, 2)); + throw new \RuntimeException('Exception from s1 setup function'); + })); + + self::assertFalse($engine->setup()->successful()); + + $this->assertSubscriptions(['id' => 's1', 'status' => 'RESETTING', 'position' => 2, 'error' => null]); + } + + public function test_setup_rolls_back_and_rethrows_if_the_transition_fails(): void + { + $this->subscriptionStore->_setSubscriptions(Subscription::create(id: 's1', runMode: RunMode::FROM_BEGINNING, status: SubscriptionStatus::NEW)); + $this->subscriptionStore->_failOnUpdateOf('s1'); + $engine = $this->subscriptionEngine(Subscriber::create(id: 's1', handler: fn () => null)); + + try { + $engine->setup(); + self::fail('Expected the exception to escape'); + } catch (\RuntimeException $e) { + self::assertSame('Update of s1 failed', $e->getMessage()); + } + + self::assertFalse($this->subscriptionStore->_isTransactionActive()); + self::assertTrue($this->subscriptionStore->_wasRollbackCalled()); + } + + /** + * @return iterable|null}> + */ + public static function recursiveSetupAndResetCalls(): iterable + { + yield 'setup without criteria' => ['setup', null]; + yield 'setup with overlapping criteria' => ['setup', ['s1']]; + yield 'reset without criteria' => ['reset', null]; + yield 'reset with overlapping criteria' => ['reset', ['s1']]; + } + + /** + * @param array|null $ids + */ + #[DataProvider('recursiveSetupAndResetCalls')] + public function test_setup_and_reset_throw_if_called_recursively_for_the_subscription_being_processed(string $method, array|null $ids): void + { + $this->eventStore->append(1); + $this->subscriptionStore->_setSubscriptions(self::subscriptionAt('s1', SubscriptionStatus::ACTIVE, 0)); + $engine = null; + $caught = null; + $engine = $this->subscriptionEngine(Subscriber::create(id: 's1', handler: function () use (&$engine, &$caught, $method, $ids) { + try { + $engine->{$method}($ids !== null ? SubscriptionEngineCriteria::create($ids) : null); + } catch (RecursiveCatchUpException $e) { + $caught = $e; + } + })); + + $engine->catchUpActive(); + + self::assertNotNull($caught); + $this->assertSubscriptions(['id' => 's1', 'status' => 'ACTIVE', 'position' => 1, 'error' => null]); + } + + public function test_reset_is_allowed_recursively_for_other_subscriptions(): void + { + $this->eventStore->append(1); + $this->subscriptionStore->_setSubscriptions(self::subscriptionAt('s1', SubscriptionStatus::ACTIVE, 0), self::subscriptionAt('s2', SubscriptionStatus::ERROR, 0)); + $engine = null; + $engine = $this->subscriptionEngine( + Subscriber::create(id: 's1', handler: function () use (&$engine) { + $engine->reset(SubscriptionEngineCriteria::create(['s2'])); + }), + Subscriber::create(id: 's2', handler: fn () => null), + ); + + self::assertTrue($engine->catchUpActive(SubscriptionEngineCriteria::create(['s1']))->successful()); + + $this->assertSubscriptions( + ['id' => 's1', 'status' => 'ACTIVE', 'position' => 1, 'error' => null], + ['id' => 's2', 'status' => 'BOOTING', 'position' => 0, 'error' => null], + ); + } + + // --------------------- public static function engineMethods(): iterable { @@ -1771,7 +2101,7 @@ private function assertEmittedEngineEvents(string ...$expectedEvents): void private function assertSubscriptions(array ...$subscriptions): void { - self::assertSame($subscriptions, $this->subscriptionStore->findByCriteriaForUpdate(SubscriptionCriteria::noConstraints())->map(static fn(Subscription $subscription) => [ + self::assertSame($subscriptions, $this->subscriptionStore->findByCriteria(SubscriptionCriteria::noConstraints())->map(static fn(Subscription $subscription) => [ 'id' => $subscription->id->value, 'status' => $subscription->status->value, 'position' => $subscription->position->value,