|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Workflow\V2\Support; |
| 6 | + |
| 7 | +use Illuminate\Database\Eloquent\Model; |
| 8 | +use Illuminate\Database\QueryException; |
| 9 | +use LogicException; |
| 10 | +use Throwable; |
| 11 | + |
| 12 | +/** |
| 13 | + * Wraps a per-row updateOrCreate with retry on unique-key violations so the |
| 14 | + * timeline / wait / timer / lineage / summary projectors stay correct when |
| 15 | + * two workers race the same projection row. |
| 16 | + * |
| 17 | + * The race shape (#438): updateOrCreate is firstOrNew + save. Two concurrent |
| 18 | + * callers both observe no row, both INSERT, and the loser hits SQLSTATE 23000 |
| 19 | + * (MySQL/SQLite) or 23505 (Postgres) on the projection's primary or unique |
| 20 | + * key. On retry, firstOrNew sees the row the winning side just wrote and the |
| 21 | + * second call falls through to UPDATE, which has no analogous race because |
| 22 | + * UPDATE does not collide on existing primary keys. |
| 23 | + * |
| 24 | + * Sibling DELETE-side races for these projectors are handled by |
| 25 | + * {@see StaleProjectionCleanup} (#425). |
| 26 | + */ |
| 27 | +final class IdempotentProjectionUpsert |
| 28 | +{ |
| 29 | + private const MAX_ATTEMPTS = 5; |
| 30 | + |
| 31 | + /** |
| 32 | + * @template TModel of Model |
| 33 | + * @param class-string<TModel> $model |
| 34 | + * @param array<string, mixed> $key |
| 35 | + * @param array<string, mixed> $values |
| 36 | + * @return TModel |
| 37 | + */ |
| 38 | + public static function upsert(string $model, array $key, array $values): Model |
| 39 | + { |
| 40 | + for ($attempt = 1; $attempt <= self::MAX_ATTEMPTS; $attempt++) { |
| 41 | + try { |
| 42 | + /** @var TModel $row */ |
| 43 | + $row = $model::query()->updateOrCreate($key, $values); |
| 44 | + |
| 45 | + return $row; |
| 46 | + } catch (QueryException $e) { |
| 47 | + if (! self::isUniqueViolation($e) || $attempt === self::MAX_ATTEMPTS) { |
| 48 | + throw $e; |
| 49 | + } |
| 50 | + |
| 51 | + usleep(self::backoffMicroseconds($attempt)); |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + throw new LogicException('IdempotentProjectionUpsert exhausted attempts without resolving.'); |
| 56 | + } |
| 57 | + |
| 58 | + private static function isUniqueViolation(Throwable $e): bool |
| 59 | + { |
| 60 | + $errorInfo = $e instanceof QueryException ? ($e->errorInfo ?? null) : null; |
| 61 | + $sqlState = is_array($errorInfo) ? (string) ($errorInfo[0] ?? '') : ''; |
| 62 | + $driverCode = is_array($errorInfo) ? (int) ($errorInfo[1] ?? 0) : 0; |
| 63 | + |
| 64 | + // 23505 is the Postgres-specific unique_violation SQLSTATE; it never |
| 65 | + // overlaps with other constraint failures so we can short-circuit. |
| 66 | + if ($sqlState === '23505') { |
| 67 | + return true; |
| 68 | + } |
| 69 | + |
| 70 | + // 23000 is the generic integrity-constraint family (MySQL, SQLite, |
| 71 | + // SQL Server). Narrow to driver codes that mean "duplicate key" so we |
| 72 | + // don't retry e.g. foreign-key or NOT NULL violations that won't clear |
| 73 | + // on the next pass. |
| 74 | + if ($sqlState === '23000') { |
| 75 | + // MySQL 1062 = ER_DUP_ENTRY |
| 76 | + // SQLite 19 = SQLITE_CONSTRAINT (covers UNIQUE; message-disambiguated below) |
| 77 | + // SQL Server 2627 = unique-constraint violation; 2601 = duplicate index key |
| 78 | + if ($driverCode === 1062 || $driverCode === 2627 || $driverCode === 2601) { |
| 79 | + return true; |
| 80 | + } |
| 81 | + |
| 82 | + $message = strtolower($e->getMessage()); |
| 83 | + |
| 84 | + return str_contains($message, 'duplicate entry') |
| 85 | + || str_contains($message, 'unique constraint failed') |
| 86 | + || str_contains($message, 'duplicate key'); |
| 87 | + } |
| 88 | + |
| 89 | + return false; |
| 90 | + } |
| 91 | + |
| 92 | + private static function backoffMicroseconds(int $attempt): int |
| 93 | + { |
| 94 | + // 2ms, 4ms, 8ms, 16ms (capped) with small jitter to break ties between |
| 95 | + // racing retriers. |
| 96 | + $base = min(16_000, 2_000 * (1 << ($attempt - 1))); |
| 97 | + |
| 98 | + return $base + random_int(0, 1_000); |
| 99 | + } |
| 100 | +} |
0 commit comments