* @copyright 2026 Nowo.tech */ final readonly class DoctrineTransactionRunner implements TransactionRunnerInterface { private TransientFailureClassifier $classifier; private ConnectionRepairer $repairer; private function __construct( private ?Connection $connection, private ?EntityManagerInterface $entityManager, private ?ManagerRegistry $registry, private ?string $managerName, private ?int $retryAfterSeconds, private LoggerInterface $logger, ) { $this->classifier = new TransientFailureClassifier(); $this->repairer = new ConnectionRepairer(null, $logger); } /** * Runs DBAL-only units of work on one connection. */ public static function forConnection(Connection $connection, ?int $retryAfterSeconds = 1, ?LoggerInterface $logger = null): self { return new self($connection, null, null, null, $retryAfterSeconds, $logger ?? new NullLogger()); } /** * Runs ORM units of work: flushes the manager before the commit. After a failure the manager is closed and reset * through the registry (fetched from it on every call), or cleared when no registry is given. */ public static function forEntityManager( EntityManagerInterface $entityManager, ?ManagerRegistry $registry = null, ?string $managerName = null, ?int $retryAfterSeconds = 1, ?LoggerInterface $logger = null, ): self { return new self(null, $entityManager, $registry, $managerName, $retryAfterSeconds, $logger ?? new NullLogger()); } public function run(callable $operation): mixed { $manager = $this->manager(); $connection = $manager?->getConnection() ?? $this->connection; assert($connection instanceof Connection); $entryLevel = $connection->getTransactionNestingLevel(); $observer = new RunObserver(); // Entities managed before the run: one the run re-hydrates (refresh(), a proxy initialised) belongs to the caller. $before = $manager instanceof EntityManagerInterface ? $this->managedEntities($manager) : []; $manager?->getEventManager()->addEventListener([Events::postFlush, Events::postLoad], $observer); try { $connection->beginTransaction(); $result = $operation(); $manager?->flush(); $connection->commit(); return $result; } catch (Throwable $throwable) { $alreadyTransient = $throwable instanceof TransientStorageFailure; $transient = $alreadyTransient || $this->classifier->isTransient($throwable); SafeLog::log($this->logger, $transient ? 'notice' : 'debug', 'Transactional operation failed.', [ 'transient' => $transient, 'entry_level' => $entryLevel, 'has_manager' => $manager instanceof EntityManagerInterface, ] + SafeLog::throwable($throwable)); $this->repairer->afterFailure($connection, $entryLevel); if ($manager instanceof EntityManagerInterface) { $this->discardPendingChanges($manager, $throwable, $observer, $before); } if ($alreadyTransient || !$transient) { throw $throwable; } throw TransientStorageFailure::fromPrevious($throwable, $this->retryAfterSeconds); } finally { $manager?->getEventManager()->removeEventListener([Events::postFlush, Events::postLoad], $observer); } } /** * @param array $before The entities managed when the run started, by spl_object_id */ private function discardPendingChanges(EntityManagerInterface $manager, Throwable $failure, RunObserver $observer, array $before): void { if (!$manager->isOpen() || $this->isStorageFailure($failure)) { if ($this->registry instanceof ManagerRegistry) { SafeLog::log($this->logger, 'notice', 'Closing and resetting the entity manager after a storage failure.', [ 'manager' => $this->managerName, 'was_open' => $manager->isOpen(), ]); $manager->close(); $this->registry->resetManager($this->managerName); } elseif ($manager->isOpen()) { SafeLog::log($this->logger, 'notice', 'Clearing the entity manager after a storage failure (no registry to reset it).', [ 'manager' => $this->managerName, ]); $manager->clear(); } return; } // Domain failure, manager open. The run's transaction was rolled back, so the identity map must not keep // anything it saw: a flush inside the run, or a caller's entity re-hydrated inside it, makes the manager stale. if ($observer->flushed || array_intersect_key($observer->loaded, $before) !== []) { SafeLog::log($this->logger, 'debug', 'Clearing the entity manager: the run flushed or re-hydrated a managed entity.', [ 'flushed' => $observer->flushed, ]); $manager->clear(); return; } // Everything that entered the identity map during the run may hold rolled-back data (a row written through // DBAL, then found or referenced with getReference(), which fires no postLoad): forget it. foreach (array_diff_key($this->managedEntities($manager), $before) as $entity) { if ($manager->contains($entity)) { $manager->detach($entity); } } // A detach cascades along cascade-detach associations: if it reached a caller's entity, a partial detach would // silently drop that entity alone (its later edits lost), so clear instead. The same when changes are pending. foreach ($before as $entity) { if (!$manager->contains($entity)) { SafeLog::log($this->logger, 'debug', 'Clearing the entity manager: a detach reached a caller entity.', []); $manager->clear(); return; } } if ($this->hasPendingChanges($manager)) { SafeLog::log($this->logger, 'debug', 'Clearing the entity manager: changes were left pending.', []); $manager->clear(); } } /** * @return array The managed entities (proxies included), by spl_object_id */ private function managedEntities(EntityManagerInterface $manager): array { $entities = []; foreach ($manager->getUnitOfWork()->getIdentityMap() as $byId) { foreach ($byId as $entity) { $entities[spl_object_id($entity)] = $entity; } } return $entities; } private function isStorageFailure(Throwable $failure): bool { for ($current = $failure; $current instanceof Throwable; $current = $current->getPrevious()) { if ($current instanceof DbalException || $current instanceof DriverExceptionInterface || $current instanceof PDOException) { return true; } } return false; } /** * The cheap signals first (scheduled insertions, deletions and collection changes); only then * UnitOfWork::computeChangeSets(), which scans the whole identity map and, through cascade-persist associations, * persists new entities it reaches (their prePersist callbacks run, generated ids may be assigned). A unit of work * that cannot even compute its change sets counts as pending. */ private function hasPendingChanges(EntityManagerInterface $manager): bool { $unitOfWork = $manager->getUnitOfWork(); if ($this->hasScheduledWork($unitOfWork)) { return true; } try { $unitOfWork->computeChangeSets(); } catch (Throwable) { return true; } return $this->hasScheduledWork($unitOfWork); } private function hasScheduledWork(UnitOfWork $unitOfWork): bool { return $unitOfWork->getScheduledEntityInsertions() !== [] || $unitOfWork->getScheduledEntityUpdates() !== [] || $unitOfWork->getScheduledEntityDeletions() !== [] || $unitOfWork->getScheduledCollectionDeletions() !== [] || $unitOfWork->getScheduledCollectionUpdates() !== []; } private function manager(): ?EntityManagerInterface { if (!$this->registry instanceof ManagerRegistry) { return $this->entityManager; } $manager = $this->registry->getManager($this->managerName); return $manager instanceof EntityManagerInterface ? $manager : $this->entityManager; } }