From f484e11eb34b787e39e8c7a11ae1fc8a8ea1289c Mon Sep 17 00:00:00 2001 From: romanetar Date: Fri, 20 Nov 2026 16:59:27 +0100 Subject: [PATCH 1/4] fix(users): store email and bio changes of verified users A save that changed the email or set a bio on a user with spam_type Ham answered 201 but stored nothing except spam_type = None. User::preUpdate dispatches UserSpamStateUpdated while the entity manager is flushing; its listener opened a transaction of its own and flushed again, which cleared the pending change sets of the outer flush. - add ITransactionService::afterCommit(), which runs a closure once the outermost transaction is committed (immediately when there is none, discarded on rollback) - run the spam re-classification through afterCommit - dispatch UserEmailUpdated after the update transaction commits, so no verification email is queued for a change that was not stored - add tests for the admin and users/me routes and for the OAuth2 user API, starting from a Ham user with the middleware stack enabled --- app/Providers/EventServiceProvider.php | 20 +- app/Services/OpenId/UserService.php | 10 +- .../Utils/DoctrineTransactionService.php | 45 +++- app/libs/Utils/Db/ITransactionService.php | 9 + tests/OAuth2UserUpdateApiTest.php | 112 ++++++++ tests/UserUpdateSpamTypeTest.php | 252 ++++++++++++++++++ 6 files changed, 439 insertions(+), 9 deletions(-) create mode 100644 tests/UserUpdateSpamTypeTest.php diff --git a/app/Providers/EventServiceProvider.php b/app/Providers/EventServiceProvider.php index c28341330..5fb8fe6f4 100644 --- a/app/Providers/EventServiceProvider.php +++ b/app/Providers/EventServiceProvider.php @@ -28,6 +28,7 @@ use App\Services\Auth\IUserService; use Auth\Repositories\IUserRepository; use Auth\User; +use Utils\Db\ITransactionService; use Illuminate\Database\Events\MigrationsEnded; use Illuminate\Database\Events\MigrationsStarted; use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider; @@ -127,12 +128,19 @@ public function boot() Event::listen(UserSpamStateUpdated::class, function($event) { - $repository = App::make(IUserRepository::class); - $user = $repository->getById($event->getUserId()); - if(is_null($user)) return; - if(! $user instanceof User) return; - $user_service = App::make(IUserService::class); - $user_service->recalculateUserSpamType($user); + // this event is also fired from User::preUpdate, while the entity manager is flushing. + // The re-classification opens a transaction (and flushes) of its own, doing that in the middle + // of a flush wipes the pending change sets of the outer one, so it must wait until the + // active transaction (if any) is committed. + $tx_service = App::make(ITransactionService::class); + $tx_service->afterCommit(function() use ($event) { + $repository = App::make(IUserRepository::class); + $user = $repository->getById($event->getUserId()); + if(is_null($user)) return; + if(! $user instanceof User) return; + $user_service = App::make(IUserService::class); + $user_service->recalculateUserSpamType($user); + }); }); Event::listen(UserEmailUpdated::class, function($event) diff --git a/app/Services/OpenId/UserService.php b/app/Services/OpenId/UserService.php index cb5f56545..c5b3c55cb 100644 --- a/app/Services/OpenId/UserService.php +++ b/app/Services/OpenId/UserService.php @@ -295,8 +295,9 @@ public function create(array $payload): IEntity public function update(int $id, array $payload): IEntity { $password_changed = false; + $email_changed = false; - $user = $this->tx_service->transaction(function () use ($id, $payload, &$password_changed) { + $user = $this->tx_service->transaction(function () use ($id, $payload, &$password_changed, &$email_changed) { $user = $this->repository->getById($id); @@ -371,7 +372,7 @@ public function update(int $id, array $payload): IEntity if ($former_email != $user->getEmail()) { Log::warning(sprintf("UserService::update use id %s - email changed old %s - email new %s", $id, $former_email, $user->getEmail())); $user->clearEmailVerification(); - Event::dispatch(new UserEmailUpdated($user->getId())); + $email_changed = true; } if ($former_password != $user->getPassword()) { @@ -382,6 +383,11 @@ public function update(int $id, array $payload): IEntity return $user; }); + // the verification token and the email are generated once the new email is stored + if ($email_changed) { + Event::dispatch(new UserEmailUpdated($user->getId())); + } + if ($password_changed) { Session::regenerate(); Event::dispatch(new UserPasswordResetSuccessful($user->getId())); diff --git a/app/Services/Utils/DoctrineTransactionService.php b/app/Services/Utils/DoctrineTransactionService.php index ba6cafb47..cd749e6b6 100644 --- a/app/Services/Utils/DoctrineTransactionService.php +++ b/app/Services/Utils/DoctrineTransactionService.php @@ -34,6 +34,13 @@ final class DoctrineTransactionService implements ITransactionService const MaxRetries = 10; + /** + * Closures registered through afterCommit while a transaction is active, + * they run once the outermost transaction is committed. + * @var Closure[] + */ + private $after_commit_callbacks = []; + /** * DoctrineTransactionService constructor. * @param string $manager_name @@ -151,7 +158,8 @@ public function transaction(Closure $callback, int $isolationLevel = Transactio $done = true; } catch (Exception $ex) { - + // the work of this attempt is discarded, so are its post commit actions + $this->after_commit_callbacks = []; $retry++; $em->getConnection()->close(); $em->close(); @@ -182,6 +190,41 @@ public function transaction(Closure $callback, int $isolationLevel = Transactio } } + $this->runAfterCommitCallbacks(); + return $result; } + + /** + * @inheritDoc + */ + public function afterCommit(Closure $callback): void + { + $em = Registry::getManager($this->manager_name); + if ($em->isOpen() && $em->getConnection()->isTransactionActive()) { + $this->after_commit_callbacks[] = $callback; + return; + } + $callback(); + } + + /** + * Runs the pending post commit actions, only when the outermost transaction is over. + * The data is already committed at this point, so a failure here is logged and does not + * fail (nor retry) the transaction that produced it. + */ + private function runAfterCommitCallbacks(): void + { + $em = Registry::getManager($this->manager_name); + if ($em->isOpen() && $em->getConnection()->isTransactionActive()) return; + + while (count($this->after_commit_callbacks) > 0) { + $callback = array_shift($this->after_commit_callbacks); + try { + $callback(); + } catch (\Throwable $ex) { + Log::error($ex); + } + } + } } \ No newline at end of file diff --git a/app/libs/Utils/Db/ITransactionService.php b/app/libs/Utils/Db/ITransactionService.php index d555212ea..8fc54796f 100644 --- a/app/libs/Utils/Db/ITransactionService.php +++ b/app/libs/Utils/Db/ITransactionService.php @@ -25,4 +25,13 @@ interface ITransactionService { * @throws Exception */ public function transaction(Closure $callback); + + /** + * Runs a Closure once the outermost active transaction has been committed. + * If there is no active transaction the Closure runs immediately. + * If the transaction is rolled back the Closure is discarded. + * @param Closure $callback + * @return void + */ + public function afterCommit(Closure $callback): void; } \ No newline at end of file diff --git a/tests/OAuth2UserUpdateApiTest.php b/tests/OAuth2UserUpdateApiTest.php index 24e3094c1..ba9f6ba96 100644 --- a/tests/OAuth2UserUpdateApiTest.php +++ b/tests/OAuth2UserUpdateApiTest.php @@ -15,7 +15,11 @@ use App\libs\Auth\Models\IGroupSlugs; use App\libs\OAuth2\IUserScopes; use Auth\Group; +use App\libs\Auth\Factories\UserFactory; +use App\Mail\UserEmailVerificationRequest; use Auth\User; +use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Mail; use LaravelDoctrine\ORM\Facades\EntityManager; /** @@ -107,11 +111,119 @@ public function testUserUpdate() $this->assertTrue($response->first_name == $new_first_name); } + /** + * @return \stdClass + */ + private function getUserRow(int $id): \stdClass + { + $row = DB::table('users')->where('id', $id)->first(); + $this->assertNotNull($row); + return $row; + } + + /** + * @return array + */ + private function getJsonHeaders(): array + { + return [ + "HTTP_Authorization" => " Bearer " . $this->access_token, + "CONTENT_TYPE" => "application/json" + ]; + } + + /** + * @return User a user with a verified email, so its spam type is Ham + */ + private function buildVerifiedUser(): User + { + $suffix = strtolower(str_random(12)); + $user = UserFactory::build([ + 'first_name' => 'Ham', + 'last_name' => 'User', + 'email' => sprintf('ham.%s@test.com', $suffix), + 'password' => '1Qaz2wsx!', + 'active' => true, + 'email_verified' => true, + 'identifier' => 'ham.' . $suffix, + ]); + EntityManager::persist($user); + EntityManager::flush(); + $this->assertEquals(User::SpamTypeHam, $this->getUserRow($user->getId())->spam_type); + EntityManager::clear(); + // the requests read the user from the database, like in production + $this->be(EntityManager::getRepository(User::class)->findOneBy(['identifier' => 'sebastian.marcet']), 'web'); + return EntityManager::getRepository(User::class)->find($user->getId()); + } + + /** + * A verified user (spam type Ham) that changes the email or sets a bio must get it stored, and be + * re classified (spam type None). + */ + public function testUserUpdateEmailAndBioOfVerifiedUserIsStored() + { + $user = $this->buildVerifiedUser(); + $new_email = sprintf('new.%s@test.com', strtolower(str_random(12))); + + $response = $this->action + ( + "PUT", + "Api\\OAuth2\\OAuth2UserApiController@update", + ['id' => $user->getId()], + [], + [], + [], + $this->getJsonHeaders(), + json_encode(['first_name' => 'Renamed', 'email' => $new_email, 'bio' => 'a non empty bio']) + ); + + $this->assertResponseStatus(201); + + $row = $this->getUserRow($user->getId()); + $this->assertEquals('Renamed', $row->first_name); + $this->assertEquals($new_email, $row->email); + $this->assertEquals('a non empty bio', $row->bio); + $this->assertEquals(0, $row->email_verified); + $this->assertEquals(User::SpamTypeNone, $row->spam_type); + + Mail::assertQueued(UserEmailVerificationRequest::class, 1); + Mail::assertQueued(UserEmailVerificationRequest::class, function (UserEmailVerificationRequest $mail) use ($new_email) { + return $mail->user_email === $new_email; + }); + } + + /** + * PUT /api/v1/users/me, sent by a verified user. + */ + public function testUserUpdateMeBioOfVerifiedUserIsStored() + { + $me = EntityManager::getRepository(User::class)->findOneBy(['identifier' => 'sebastian.marcet']); + // the seeded user is verified, make sure it is classified as Ham + DB::table('users')->where('id', $me->getId())->update(['spam_type' => User::SpamTypeHam]); + EntityManager::clear(); + + $this->json + ( + "PUT", + "https://local.idp.com/api/v1/users/me", + ['first_name' => 'Renamed', 'bio' => 'a non empty bio'], + $this->getJsonHeaders() + ); + + $this->assertResponseStatus(201); + + $row = $this->getUserRow($me->getId()); + $this->assertEquals('Renamed', $row->first_name); + $this->assertEquals('a non empty bio', $row->bio); + $this->assertEquals(User::SpamTypeNone, $row->spam_type); + } + protected function getScopes() { return [ "openid", IUserScopes::Write, + IUserScopes::MeWrite, ]; } } diff --git a/tests/UserUpdateSpamTypeTest.php b/tests/UserUpdateSpamTypeTest.php new file mode 100644 index 000000000..b7b7fc51e --- /dev/null +++ b/tests/UserUpdateSpamTypeTest.php @@ -0,0 +1,252 @@ +admin = EntityManager::getRepository(User::class)->findOneBy(['identifier' => 'sebastian.marcet']); + $this->be($this->admin, 'web'); + } + + /** + * @return User a user with a verified email, so spam_type is Ham + */ + private function buildVerifiedUser(): User + { + $suffix = strtolower(str_random(12)); + + $user = UserFactory::build([ + 'first_name' => 'Ham', + 'last_name' => 'User', + 'email' => sprintf('ham.%s@test.com', $suffix), + 'password' => '1Qaz2wsx!', + 'active' => true, + 'email_verified' => true, + 'identifier' => 'ham.' . $suffix, + ]); + + EntityManager::persist($user); + EntityManager::flush(); + + $row = $this->getUserRow($user->getId()); + $this->assertEquals(User::SpamTypeHam, $row->spam_type, 'precondition: a verified user is Ham'); + $this->assertEquals(1, $row->email_verified, 'precondition: email is verified'); + + // from here on the requests must read the user from the database, like a real request does + EntityManager::clear(); + $this->be(EntityManager::getRepository(User::class)->find($this->admin->getId()), 'web'); + + return EntityManager::getRepository(User::class)->find($user->getId()); + } + + private function getUserRow(int $id): \stdClass + { + $row = DB::table('users')->where('id', $id)->first(); + $this->assertNotNull($row); + return $row; + } + + private function assertNoVerificationEmailQueued(): void + { + Mail::assertNotQueued(UserEmailVerificationRequest::class); + } + + // ------------------------------------------------------------------------- + // PUT admin/api/v1/users/{id} + // ------------------------------------------------------------------------- + + public function testAdminUpdateFirstNameAndEmailIsStored(): void + { + $user = $this->buildVerifiedUser(); + $new_email = sprintf('new.%s@test.com', strtolower(str_random(12))); + + $this->put('/admin/api/v1/users/' . $user->getId(), [ + 'first_name' => 'Renamed', + 'email' => $new_email, + ])->assertResponseStatus(201); + + $row = $this->getUserRow($user->getId()); + $this->assertEquals('Renamed', $row->first_name); + $this->assertEquals($new_email, $row->email); + $this->assertEquals(0, $row->email_verified); + // the re classification still happens + $this->assertEquals(User::SpamTypeNone, $row->spam_type); + } + + public function testAdminUpdateFirstNameAndBioIsStored(): void + { + $user = $this->buildVerifiedUser(); + + $this->put('/admin/api/v1/users/' . $user->getId(), [ + 'first_name' => 'Renamed', + 'bio' => 'a non empty bio', + ])->assertResponseStatus(201); + + $row = $this->getUserRow($user->getId()); + $this->assertEquals('Renamed', $row->first_name); + $this->assertEquals('a non empty bio', $row->bio); + $this->assertEquals(User::SpamTypeNone, $row->spam_type); + } + + public function testAdminUpdateWithoutSpamTypeTriggerKeepsSpamType(): void + { + $user = $this->buildVerifiedUser(); + + $this->put('/admin/api/v1/users/' . $user->getId(), [ + 'first_name' => 'Renamed', + ])->assertResponseStatus(201); + + $row = $this->getUserRow($user->getId()); + $this->assertEquals('Renamed', $row->first_name); + // neither the email nor the bio changed, so it is not re classified + $this->assertEquals(User::SpamTypeHam, $row->spam_type); + } + + public function testAdminUpdateEmailQueuesOneVerificationEmailToTheNewAddress(): void + { + $user = $this->buildVerifiedUser(); + $new_email = sprintf('new.%s@test.com', strtolower(str_random(12))); + + $this->put('/admin/api/v1/users/' . $user->getId(), [ + 'first_name' => 'Renamed', + 'email' => $new_email, + ])->assertResponseStatus(201); + + Mail::assertQueued(UserEmailVerificationRequest::class, 1); + Mail::assertQueued(UserEmailVerificationRequest::class, function (UserEmailVerificationRequest $mail) use ($new_email) { + return $mail->user_email === $new_email; + }); + + // the link of that email verifies the address that was stored + $mails = Mail::queued(UserEmailVerificationRequest::class); + $link = $mails->first()->verification_link; + $this->assertNotEmpty($link); + + $this->get($link); + + $row = $this->getUserRow($user->getId()); + $this->assertEquals($new_email, $row->email); + $this->assertEquals(1, $row->email_verified); + } + + public function testAdminUpdateRejectedQueuesNoVerificationEmail(): void + { + $user = $this->buildVerifiedUser(); + + // an email that belongs to another user is rejected with 412 + $this->put('/admin/api/v1/users/' . $user->getId(), [ + 'first_name' => 'Renamed', + 'email' => $this->admin->getEmail(), + ])->assertResponseStatus(412); + + $row = $this->getUserRow($user->getId()); + $this->assertEquals('Ham', $row->first_name); + $this->assertEquals($user->getEmail(), $row->email); + $this->assertEquals(User::SpamTypeHam, $row->spam_type); + $this->assertNoVerificationEmailQueued(); + } + + public function testAdminUpdateWithSpamTypeNoneStillStored(): void + { + // control case, this one worked before the fix + $user = $this->buildVerifiedUser(); + DB::table('users')->where('id', $user->getId())->update(['spam_type' => User::SpamTypeNone]); + EntityManager::clear(); + $this->be(EntityManager::getRepository(User::class)->find($this->admin->getId()), 'web'); + + $this->put('/admin/api/v1/users/' . $user->getId(), [ + 'first_name' => 'Renamed', + 'bio' => 'a non empty bio', + ])->assertResponseStatus(201); + + $row = $this->getUserRow($user->getId()); + $this->assertEquals('Renamed', $row->first_name); + $this->assertEquals('a non empty bio', $row->bio); + } + + // ------------------------------------------------------------------------- + // PUT admin/api/v1/users/me + // ------------------------------------------------------------------------- + + public function testMeUpdateFirstNameAndBioIsStored(): void + { + $user = $this->buildVerifiedUser(); + $this->be($user, 'web'); + + $this->put('/admin/api/v1/users/me', [ + 'first_name' => 'Renamed', + 'bio' => 'a non empty bio', + ])->assertResponseStatus(201); + + $row = $this->getUserRow($user->getId()); + $this->assertEquals('Renamed', $row->first_name); + $this->assertEquals('a non empty bio', $row->bio); + $this->assertEquals(User::SpamTypeNone, $row->spam_type); + } + + public function testMeUpdateFirstNameAndEmailIsStored(): void + { + $user = $this->buildVerifiedUser(); + $new_email = sprintf('new.%s@test.com', strtolower(str_random(12))); + $this->be($user, 'web'); + + $this->put('/admin/api/v1/users/me', [ + 'first_name' => 'Renamed', + 'email' => $new_email, + ])->assertResponseStatus(201); + + $row = $this->getUserRow($user->getId()); + $this->assertEquals('Renamed', $row->first_name); + $this->assertEquals($new_email, $row->email); + $this->assertEquals(0, $row->email_verified); + $this->assertEquals(User::SpamTypeNone, $row->spam_type); + + Mail::assertQueued(UserEmailVerificationRequest::class, 1); + Mail::assertQueued(UserEmailVerificationRequest::class, function (UserEmailVerificationRequest $mail) use ($new_email) { + return $mail->user_email === $new_email; + }); + } +} From eb07f6698698a7468f74382b7f6790d78c0c7899 Mon Sep 17 00:00:00 2001 From: romanetar Date: Fri, 20 Nov 2026 17:28:36 +0100 Subject: [PATCH 2/4] test(users): target the app url host in the users/me bearer test The access token audience is APP_URL, so a hardcoded local.idp.com host was rejected as invalid_token when APP_URL differs (CI uses localhost). --- tests/OAuth2UserUpdateApiTest.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/OAuth2UserUpdateApiTest.php b/tests/OAuth2UserUpdateApiTest.php index ba9f6ba96..1b9db6a79 100644 --- a/tests/OAuth2UserUpdateApiTest.php +++ b/tests/OAuth2UserUpdateApiTest.php @@ -205,7 +205,8 @@ public function testUserUpdateMeBioOfVerifiedUserIsStored() $this->json ( "PUT", - "https://local.idp.com/api/v1/users/me", + // the bearer token audience is the app url, the request must target that host + $this->current_realm . "/api/v1/users/me", ['first_name' => 'Renamed', 'bio' => 'a non empty bio'], $this->getJsonHeaders() ); From 33779ecaa019b0ee58df5b88f5670341f8752f5a Mon Sep 17 00:00:00 2001 From: romanetar Date: Fri, 20 Nov 2026 17:33:06 +0100 Subject: [PATCH 3/4] fix(users): keep password change effects when the verification email fails The email dispatch now runs after the update transaction commits, so a failure there escaped update() before Session::regenerate() and UserPasswordResetSuccessful, leaving a committed password change with sessions and grants untouched. Log the failure instead. --- app/Services/OpenId/UserService.php | 8 ++++++- tests/UserUpdateSpamTypeTest.php | 34 +++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/app/Services/OpenId/UserService.php b/app/Services/OpenId/UserService.php index c5b3c55cb..e7587914a 100644 --- a/app/Services/OpenId/UserService.php +++ b/app/Services/OpenId/UserService.php @@ -385,7 +385,13 @@ public function update(int $id, array $payload): IEntity // the verification token and the email are generated once the new email is stored if ($email_changed) { - Event::dispatch(new UserEmailUpdated($user->getId())); + // the email change is already committed, a failure queuing the verification email must not + // skip the password change effects below + try { + Event::dispatch(new UserEmailUpdated($user->getId())); + } catch (\Exception $ex) { + Log::warning($ex); + } } if ($password_changed) { diff --git a/tests/UserUpdateSpamTypeTest.php b/tests/UserUpdateSpamTypeTest.php index b7b7fc51e..0304b2e28 100644 --- a/tests/UserUpdateSpamTypeTest.php +++ b/tests/UserUpdateSpamTypeTest.php @@ -12,10 +12,13 @@ * limitations under the License. **/ +use App\Events\UserEmailUpdated; +use App\Events\UserPasswordResetSuccessful; use App\libs\Auth\Factories\UserFactory; use App\Mail\UserEmailVerificationRequest; use Auth\User; use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Mail; use LaravelDoctrine\ORM\Facades\EntityManager; @@ -249,4 +252,35 @@ public function testMeUpdateFirstNameAndEmailIsStored(): void return $mail->user_email === $new_email; }); } + + /** + * The email change is already committed when the verification email is dispatched, a failure there + * must not skip the password change effects. + */ + public function testAdminUpdateEmailDispatchFailureDoesNotSkipPasswordChangeEffects(): void + { + $user = $this->buildVerifiedUser(); + $new_email = sprintf('new.%s@test.com', strtolower(str_random(12))); + $old_hash = $this->getUserRow($user->getId())->password; + + Event::listen(UserEmailUpdated::class, function () { + throw new \RuntimeException('mail queue is down'); + }); + $password_effects = 0; + Event::listen(UserPasswordResetSuccessful::class, function () use (&$password_effects) { + $password_effects++; + }); + + $this->put('/admin/api/v1/users/' . $user->getId(), [ + 'email' => $new_email, + 'password' => '2Wsx3edc!', + 'password_confirmation' => '2Wsx3edc!', + ])->assertResponseStatus(201); + + $row = $this->getUserRow($user->getId()); + $this->assertEquals($new_email, $row->email); + $this->assertEquals(0, $row->email_verified); + $this->assertNotEquals($old_hash, $row->password); + $this->assertEquals(1, $password_effects); + } } From 082ce1dd010673aa2c9bb7a1c5524c1d72844bc4 Mon Sep 17 00:00:00 2001 From: romanetar Date: Fri, 20 Nov 2026 17:37:16 +0100 Subject: [PATCH 4/4] fix(tx): do not lose pending after-commit callbacks when one of them fails A callback that runs a transaction of its own and fails clears the shared callback queue, discarding the siblings of the committed batch. Detach the batch before running it. --- .../Utils/DoctrineTransactionService.php | 15 ++-- tests/DoctrineTransactionAfterCommitTest.php | 88 +++++++++++++++++++ 2 files changed, 98 insertions(+), 5 deletions(-) create mode 100644 tests/DoctrineTransactionAfterCommitTest.php diff --git a/app/Services/Utils/DoctrineTransactionService.php b/app/Services/Utils/DoctrineTransactionService.php index cd749e6b6..0d5508e40 100644 --- a/app/Services/Utils/DoctrineTransactionService.php +++ b/app/Services/Utils/DoctrineTransactionService.php @@ -219,11 +219,16 @@ private function runAfterCommitCallbacks(): void if ($em->isOpen() && $em->getConnection()->isTransactionActive()) return; while (count($this->after_commit_callbacks) > 0) { - $callback = array_shift($this->after_commit_callbacks); - try { - $callback(); - } catch (\Throwable $ex) { - Log::error($ex); + // detach the committed batch first: a callback that runs a transaction of its own and fails + // clears the shared queue, that must not discard the callbacks of this batch that are still pending + $batch = $this->after_commit_callbacks; + $this->after_commit_callbacks = []; + foreach ($batch as $callback) { + try { + $callback(); + } catch (\Throwable $ex) { + Log::error($ex); + } } } } diff --git a/tests/DoctrineTransactionAfterCommitTest.php b/tests/DoctrineTransactionAfterCommitTest.php new file mode 100644 index 000000000..dbcedb98c --- /dev/null +++ b/tests/DoctrineTransactionAfterCommitTest.php @@ -0,0 +1,88 @@ +app->make(ITransactionService::class); + } + + public function testRunsImmediatelyWhenNoTransactionIsActive(): void + { + $ran = false; + $this->txService()->afterCommit(function () use (&$ran) { $ran = true; }); + $this->assertTrue($ran); + } + + public function testRunsAfterTheOutermostTransactionCommits(): void + { + $tx = $this->txService(); + $events = []; + + $tx->transaction(function () use ($tx, &$events) { + $tx->afterCommit(function () use (&$events) { $events[] = 'callback'; }); + $tx->transaction(function () use (&$events) { $events[] = 'inner'; }); + $events[] = 'outer'; + }); + + $this->assertEquals(['inner', 'outer', 'callback'], $events); + } + + public function testIsDiscardedWhenTheTransactionFails(): void + { + $tx = $this->txService(); + $ran = false; + + try { + $tx->transaction(function () use ($tx, &$ran) { + $tx->afterCommit(function () use (&$ran) { $ran = true; }); + throw new \RuntimeException('boom'); + }); + $this->fail('the exception must be rethrown'); + } catch (\RuntimeException $ex) { + $this->assertEquals('boom', $ex->getMessage()); + } + + $this->assertFalse($ran); + } + + /** + * A callback that runs a transaction of its own and fails clears the shared queue, + * the other callbacks of the committed batch must still run. + */ + public function testFailingCallbackTransactionDoesNotDiscardSiblingCallbacks(): void + { + $tx = $this->txService(); + $ran = []; + + $tx->transaction(function () use ($tx, &$ran) { + $tx->afterCommit(function () use ($tx) { + $tx->transaction(function () { + throw new \RuntimeException('inner transaction fails'); + }); + }); + $tx->afterCommit(function () use (&$ran) { $ran[] = 'second'; }); + $tx->afterCommit(function () use (&$ran) { $ran[] = 'third'; }); + }); + + $this->assertEquals(['second', 'third'], $ran); + } +}