* @copyright 2026 Nowo.tech */ final class TransientFailureClassifier { /** * @return TransientFailureKind|null The kind of the first transient failure in the chain, or null when there is none */ public function classify(Throwable $throwable): ?TransientFailureKind { $cause = $this->transientCause($throwable); return $cause instanceof Throwable ? $this->classifyOne($cause) : null; } public function isTransient(Throwable $throwable): bool { return $this->transientCause($throwable) instanceof Throwable; } /** * @return Throwable|null The first exception of the chain (the throwable itself included) that is a transient failure */ public function transientCause(Throwable $throwable): ?Throwable { for ($current = $throwable; $current instanceof Throwable; $current = $current->getPrevious()) { if ($this->classifyOne($current) instanceof TransientFailureKind) { return $current; } } return null; } private function classifyOne(Throwable $throwable): ?TransientFailureKind { if ($throwable instanceof LockWaitTimeoutException) { return TransientFailureKind::LockWaitTimeout; } if ($throwable instanceof DriverExceptionInterface) { $kind = $this->fromCodes($throwable->getCode(), $throwable->getSQLState()); } elseif ($throwable instanceof PDOException) { $vendorCode = $throwable->errorInfo[1] ?? null; $sqlState = $throwable->errorInfo[0] ?? $throwable->getCode(); $kind = $this->fromCodes(is_int($vendorCode) ? $vendorCode : 0, is_string($sqlState) ? $sqlState : null); } else { $kind = null; } if ($kind instanceof TransientFailureKind) { return $kind; } if ($throwable instanceof DeadlockException) { return TransientFailureKind::Deadlock; } return $throwable instanceof RetryableException ? TransientFailureKind::Retryable : null; } private function fromCodes(int $vendorCode, ?string $sqlState): ?TransientFailureKind { return match (true) { $vendorCode === 1213, $sqlState === '40P01' => TransientFailureKind::Deadlock, $vendorCode === 1205, $sqlState === '55P03' => TransientFailureKind::LockWaitTimeout, $sqlState === '40001', $vendorCode === 1020 => TransientFailureKind::SerializationFailure, default => null, }; } }