A free open source IT asset/license management system
Handle timeouts/deadlocks for hasCalendarEvents trait
snipeea2139359903
diff --git a/app/Models/Traits/HasCalendarEvents.php b/app/Models/Traits/HasCalendarEvents.phpindex e014c99f31..ea9d763cb6 100644--- a/app/Models/Traits/HasCalendarEvents.php+++ b/app/Models/Traits/HasCalendarEvents.php@@ -245,26 +245,72 @@ trait HasCalendarEvents$companyId = $this->calendarEventCompanyId();// Single-statement upsert instead of SELECT-then-INSERT/UPDATE.- // Compiles to INSERT ... ON DUPLICATE KEY UPDATE on MySQL+ // Compiles to INSERT ... ON DUPLICATE KEY UPDATE on MySQL. The+ // AssetsController and other write paths wrap source saves in+ // DB::transaction, so this upsert fires inside the enclosing+ // transaction and the gap locks it takes on the composite+ // unique index persist until commit. Under concurrent writes+ // on the same index gap (parallel API calls, scheduled syncs,+ // reconcile commands, observer cascades) InnoDB can deadlock+ // on the lock-check step. The retry wrapper absorbs SQLSTATE+ // 40001 and replays the single idempotent statement so the+ // outer API caller does not see the deadlock.$now = now();- CalendarEvent::upsert(- [- [- 'source_type' => static::class,- 'source_id' => $this->getKey(),- 'source_field' => $field,- 'event_type' => $eventType,- 'start' => $this->normalizeCalendarEventDate($start),- 'end' => $this->normalizeCalendarEventDate($end),- 'company_id' => $companyId,- 'deleted_at' => null,- 'created_at' => $now,- 'updated_at' => $now,- ]- ],- ['source_type', 'source_id', 'source_field'],- ['event_type', 'start', 'end', 'company_id', 'deleted_at', 'updated_at']- );+ $this->upsertCalendarEventWithDeadlockRetry([+ 'source_type' => static::class,+ 'source_id' => $this->getKey(),+ 'source_field' => $field,+ 'event_type' => $eventType,+ 'start' => $this->normalizeCalendarEventDate($start),+ 'end' => $this->normalizeCalendarEventDate($end),+ 'company_id' => $companyId,+ 'deleted_at' => null,+ 'created_at' => $now,+ 'updated_at' => $now,+ ]);+ }++ /**+ * Run the calendar_events upsert, retrying on InnoDB deadlock+ * (SQLSTATE 40001). The upsert is idempotent (same input values+ * produce the same row) so a retry after a lost-the-lock-race+ * deadlock is always safe. Bounded at three attempts with short+ * waits because the enclosing transaction is holding other locks+ * too and the caller is a sync write path, not a background job.+ *+ * @param array<string, mixed> $row+ */+ private function upsertCalendarEventWithDeadlockRetry(array $row): void+ {+ $attempts = 0;+ $maxAttempts = 3;++ while (true) {+ try {+ CalendarEvent::upsert(+ [$row],+ ['source_type', 'source_id', 'source_field'],+ ['event_type', 'start', 'end', 'company_id', 'deleted_at', 'updated_at']+ );++ return;+ } catch (\Illuminate\Database\QueryException $e) {+ $attempts++;++ // SQLSTATE 40001 is the "serialization+ // failure" code both MySQL and Postgres surface for+ // deadlock / lock-order abort.+ if ($e->getCode() !== '40001' || $attempts >= $maxAttempts) {+ throw $e;+ }++ // 10ms, 40ms, 160ms. Short enough that an API write+ // path still responds inside a request timeout, long+ // enough that the colliding transaction has a chance+ // to commit between retries.+ usleep(10000 * (4 ** ($attempts - 1)));+ }+ }}/**