diff --git a/cloud/src/Repository/Pdo/PdoEventRepository.php b/cloud/src/Repository/Pdo/PdoEventRepository.php index 431428c..ee95049 100644 --- a/cloud/src/Repository/Pdo/PdoEventRepository.php +++ b/cloud/src/Repository/Pdo/PdoEventRepository.php @@ -42,7 +42,7 @@ final class PdoEventRepository implements EventRepository $st = $this->pdo->prepare( 'SELECT ' . self::SELECT_COLUMNS . ' FROM events WHERE severity = ? - ORDER BY occurred_at DESC LIMIT ?' + ORDER BY occurred_at DESC, event_id DESC LIMIT ?' ); $st->bindValue(1, $severity, PDO::PARAM_STR); $st->bindValue(2, $limit, PDO::PARAM_INT); @@ -50,7 +50,7 @@ final class PdoEventRepository implements EventRepository $st = $this->pdo->prepare( 'SELECT ' . self::SELECT_COLUMNS . ' FROM events - ORDER BY occurred_at DESC LIMIT ?' + ORDER BY occurred_at DESC, event_id DESC LIMIT ?' ); $st->bindValue(1, $limit, PDO::PARAM_INT); } diff --git a/cloud/src/Repository/Pdo/PdoZoneRepository.php b/cloud/src/Repository/Pdo/PdoZoneRepository.php index fd34878..ea18d53 100644 --- a/cloud/src/Repository/Pdo/PdoZoneRepository.php +++ b/cloud/src/Repository/Pdo/PdoZoneRepository.php @@ -64,7 +64,12 @@ final class PdoZoneRepository implements ZoneRepository * before the UPDATE (rather than trusting UPDATE's rowCount()) because * MySQL reports "changed rows", not "matched rows" -- a no-op update * (identical level/polygon resubmitted) would otherwise report 0 affected - * rows and be indistinguishable from an ownership mismatch. + * rows and be indistinguishable from an ownership mismatch. The UPDATE's + * rowCount() is still checked afterwards (0 there is unambiguous, since + * we already know the row existed a moment ago) to catch the narrow race + * where the zone is deleted between the ownership check and the UPDATE -- + * without this, save() would return success for a zone that no longer + * exists. */ private function updateOwned( string $zoneId, @@ -86,6 +91,19 @@ final class PdoZoneRepository implements ZoneRepository WHERE zone_id = ? AND device_id = ? AND camera_id = ?' ); $st->execute([$level, $polygonJson, time(), $zoneId, $deviceId, $cameraId]); + if ($st->rowCount() === 0) { + // Ambiguous on its own: MySQL's rowCount() reports "changed" rows, + // not "matched" rows, so 0 here could mean either (a) a genuine + // no-op update (identical level/polygon resubmitted -- not an + // error) or (b) the zone was deleted between the ownership check + // above and this UPDATE. Disambiguate with a targeted existence + // check instead of assuming either case. + $stillExists = $this->pdo->prepare('SELECT 1 FROM zones WHERE zone_id = ? LIMIT 1'); + $stillExists->execute([$zoneId]); + if ($stillExists->fetchColumn() === false) { + throw new RuntimeException('zone was deleted concurrently'); + } + } return $zoneId; } }