mirror of
https://github.com/rommapp/romm.git
synced 2026-11-28 17:48:31 +01:00
* fix(db): bump client token and device last-used timestamps without a prior read update_last_used() and update_last_seen_debounced() read the row with session.get() and then updated it in the same transaction. When two requests with the same Client API Token ran concurrently and both passed the debounce check, the second UPDATE hit MariaDB error 1020 (Record has changed since last read), so a read-only GET returned HTTP 500. Make each a single conditional UPDATE that only touches the row when the debounce window has passed. Fixes #5379 Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> * test(db): code-review fixes for last-used race tests Reuse the executed_statements fixture, scope race listeners to sync_engine, add the device race test, drop an unused fixture, and apply trunk fmt. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(db): simplify pass on last-used race fix Share the race hook as tests/db_race_stubs.run_before_first, look tokens up by id in tests, trim duplicated docstrings, and state the handler comment as current behaviour. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(db): humanizer pass on last-used handler comments Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(db): run MariaDB and MySQL sessions at READ COMMITTED MariaDB 11.6+ turns on innodb_snapshot_isolation, so at REPEATABLE READ any transaction that reads a row and then writes it fails with error 1020 ("Record has changed since last read") when another transaction committed to that row in between. READ COMMITTED, PostgreSQL's default, takes a fresh snapshot per statement and removes the whole class of failures. A server logging binlog_format=STATEMENT refuses InnoDB writes below REPEATABLE READ, so its sessions keep the default and log a warning once. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * perf(auth): skip last-used and last-active writes inside the debounce window Client-token auth bumped the token, the device and the user on every request, the user with an undebounced UPDATE plus a re-SELECT. The token's loaded last_used_at now gates the token and device bumps, and set_last_active checks the loaded last_active and bumps through a debounced conditional UPDATE, so a request inside the window writes nothing and takes no row lock. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com> Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
186 lines
5.5 KiB
Python
186 lines
5.5 KiB
Python
from collections.abc import Sequence
|
|
from datetime import datetime, timedelta, timezone
|
|
from typing import Any
|
|
|
|
from sqlalchemy import delete, or_, select, update
|
|
from sqlalchemy.orm import Session
|
|
|
|
from decorators.database import INJECTED_SESSION, begin_session
|
|
from models.device import Device, SyncMode
|
|
|
|
from .base_handler import DBBaseHandler
|
|
|
|
LAST_SEEN_DEBOUNCE = timedelta(minutes=5)
|
|
|
|
|
|
class DBDevicesHandler(DBBaseHandler):
|
|
@begin_session
|
|
def add_device(
|
|
self,
|
|
device: Device,
|
|
session: Session = INJECTED_SESSION,
|
|
) -> Device:
|
|
return session.merge(device)
|
|
|
|
@begin_session
|
|
def get_device(
|
|
self,
|
|
device_id: str,
|
|
user_id: int,
|
|
session: Session = INJECTED_SESSION,
|
|
) -> Device | None:
|
|
return session.scalar(
|
|
select(Device).filter_by(id=device_id, user_id=user_id).limit(1)
|
|
)
|
|
|
|
@begin_session
|
|
def get_device_by_fingerprint(
|
|
self,
|
|
user_id: int,
|
|
mac_address: str | None = None,
|
|
hostname: str | None = None,
|
|
ip_address: str | None = None,
|
|
platform: str | None = None,
|
|
session: Session = INJECTED_SESSION,
|
|
) -> Device | None:
|
|
if mac_address:
|
|
device = session.scalar(
|
|
select(Device)
|
|
.filter_by(user_id=user_id, mac_address=mac_address)
|
|
.limit(1)
|
|
)
|
|
if device:
|
|
return device
|
|
|
|
if ip_address and platform:
|
|
return session.scalar(
|
|
select(Device)
|
|
.filter_by(user_id=user_id, ip_address=ip_address, platform=platform)
|
|
.limit(1)
|
|
)
|
|
|
|
if hostname and platform:
|
|
return session.scalar(
|
|
select(Device)
|
|
.filter_by(user_id=user_id, hostname=hostname, platform=platform)
|
|
.limit(1)
|
|
)
|
|
|
|
return None
|
|
|
|
@begin_session
|
|
def get_device_by_id(
|
|
self,
|
|
device_id: str,
|
|
session: Session = INJECTED_SESSION,
|
|
) -> Device | None:
|
|
"""Get a device by ID without user filtering (for server-side operations)."""
|
|
return session.scalar(select(Device).filter_by(id=device_id).limit(1))
|
|
|
|
@begin_session
|
|
def get_device_by_client_identifier(
|
|
self,
|
|
user_id: int,
|
|
client_device_identifier: str,
|
|
session: Session = INJECTED_SESSION,
|
|
) -> Device | None:
|
|
"""Find a device by its client-supplied stable identifier, scoped to a user."""
|
|
if not client_device_identifier:
|
|
return None
|
|
return session.scalar(
|
|
select(Device)
|
|
.filter_by(
|
|
user_id=user_id,
|
|
client_device_identifier=client_device_identifier,
|
|
)
|
|
.limit(1)
|
|
)
|
|
|
|
@begin_session
|
|
def get_devices(
|
|
self,
|
|
user_id: int,
|
|
session: Session = INJECTED_SESSION,
|
|
) -> Sequence[Device]:
|
|
return session.scalars(select(Device).filter_by(user_id=user_id)).all()
|
|
|
|
@begin_session
|
|
def get_all_devices_by_sync_mode(
|
|
self,
|
|
sync_mode: SyncMode,
|
|
session: Session = INJECTED_SESSION,
|
|
) -> Sequence[Device]:
|
|
"""Get all devices with a specific sync mode (across all users)."""
|
|
return session.scalars(select(Device).filter_by(sync_mode=sync_mode)).all()
|
|
|
|
@begin_session
|
|
def update_device(
|
|
self,
|
|
device_id: str,
|
|
user_id: int,
|
|
data: dict[str, Any],
|
|
session: Session = INJECTED_SESSION,
|
|
) -> Device | None:
|
|
session.execute(
|
|
update(Device)
|
|
.where(Device.id == device_id, Device.user_id == user_id)
|
|
.values(**data)
|
|
.execution_options(synchronize_session="evaluate")
|
|
)
|
|
return session.scalar(
|
|
select(Device).filter_by(id=device_id, user_id=user_id).limit(1)
|
|
)
|
|
|
|
@begin_session
|
|
def update_last_seen(
|
|
self,
|
|
device_id: str,
|
|
user_id: int,
|
|
session: Session = INJECTED_SESSION,
|
|
) -> None:
|
|
session.execute(
|
|
update(Device)
|
|
.where(Device.id == device_id, Device.user_id == user_id)
|
|
.values(last_seen=datetime.now(timezone.utc))
|
|
.execution_options(synchronize_session="evaluate")
|
|
)
|
|
|
|
@begin_session
|
|
def update_last_seen_debounced(
|
|
self,
|
|
device_id: str,
|
|
session: Session = INJECTED_SESSION,
|
|
) -> None:
|
|
"""Bump last_seen on the device, skipping if updated within the debounce window.
|
|
|
|
Intended for the auth hot path -- called on every authenticated client-token
|
|
request. Mirrors the debounce used by ClientToken.update_last_used.
|
|
"""
|
|
now = datetime.now(timezone.utc)
|
|
# Debounced in the WHERE clause, so concurrent bumps have no earlier read to race.
|
|
session.execute(
|
|
update(Device)
|
|
.where(
|
|
Device.id == device_id,
|
|
or_(
|
|
Device.last_seen.is_(None),
|
|
Device.last_seen < now - LAST_SEEN_DEBOUNCE,
|
|
),
|
|
)
|
|
.values(last_seen=now)
|
|
.execution_options(synchronize_session=False)
|
|
)
|
|
|
|
@begin_session
|
|
def delete_device(
|
|
self,
|
|
device_id: str,
|
|
user_id: int,
|
|
session: Session = INJECTED_SESSION,
|
|
) -> None:
|
|
session.execute(
|
|
delete(Device)
|
|
.where(Device.id == device_id, Device.user_id == user_id)
|
|
.execution_options(synchronize_session="evaluate")
|
|
)
|