Кэш списка бакета, БД без блокировки event loop, один процесс на БД
Производительность и масштабирование, пункты 8–10 ревью (docs/changes/019): - кэш списка бакета и связей файлов с копиями (BACKUPS_CACHE_TTL, 60 с): sync_rows только при реальном чтении бакета; сброс после бэкапа и удаления, счётчик поколений против гонки; refresh=1 и «Обновить список»; - обработчики API/UI без await — обычные функции (пул потоков FastAPI), запуск задач остаётся async; запись статуса, задачи и sync_rows — через asyncio.to_thread; SQLite: WAL, synchronous=NORMAL, busy_timeout; - файловая блокировка <файл БД>.lock: второй процесс на той же БД не стартует; раздел «Ограничения» в README. Тесты: 24 из 24. Стенд (порт 8001): кэш 0,014 с против 0,138 с, второй uvicorn на боевой БД отклонён блокировкой, боевые данные не изменены. Ручная проверка UI пользователем на момент коммита не подтверждена. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
123b5abdfc
commit
ba8ac7be71
17 files changed
+395
-110
No files matched your search
+20
-19
@@ -110,7 +110,7 @@ class BatchChannelIn(BatchIn):
|
||||
# --- устройства ---
|
||||
|
||||
@router.get("/devices", response_model=list[DeviceOut])
|
||||
async def list_devices(
|
||||
def list_devices(
|
||||
group: str = "", # "" — все, "none" — без группы, иначе ID группы (grp_…)
|
||||
q: str = "",
|
||||
status: Literal["", "online", "offline"] = "",
|
||||
@@ -124,44 +124,44 @@ async def list_devices(
|
||||
# --- группы ---
|
||||
|
||||
@router.get("/groups", response_model=list[GroupOut])
|
||||
async def list_groups():
|
||||
def list_groups():
|
||||
return groups.list_groups()
|
||||
|
||||
|
||||
@router.post("/groups", response_model=GroupOut, status_code=201)
|
||||
async def create_group(body: GroupIn):
|
||||
def create_group(body: GroupIn):
|
||||
g = groups.create_group(body.name)
|
||||
return GroupOut(id=g.id, name=g.name)
|
||||
|
||||
|
||||
@router.patch("/groups/{group_id}", response_model=GroupOut)
|
||||
async def rename_group(group_id: str, body: GroupIn):
|
||||
def rename_group(group_id: str, body: GroupIn):
|
||||
groups.rename_group(group_id, body.name)
|
||||
return next(g for g in groups.list_groups() if g["id"] == group_id)
|
||||
|
||||
|
||||
@router.delete("/groups/{group_id}", status_code=204)
|
||||
async def delete_group(group_id: str):
|
||||
def delete_group(group_id: str):
|
||||
groups.delete_group(group_id)
|
||||
|
||||
|
||||
@router.post("/devices", response_model=DeviceOut, status_code=201)
|
||||
async def create_device(body: DeviceIn):
|
||||
def create_device(body: DeviceIn):
|
||||
return DeviceOut.of(devices.create_device(**body.model_dump()))
|
||||
|
||||
|
||||
@router.get("/devices/{device_id}", response_model=DeviceOut)
|
||||
async def get_device(device_id: str):
|
||||
def get_device(device_id: str):
|
||||
return DeviceOut.of(devices.get_device(device_id))
|
||||
|
||||
|
||||
@router.patch("/devices/{device_id}", response_model=DeviceOut)
|
||||
async def patch_device(device_id: str, body: DevicePatch):
|
||||
def patch_device(device_id: str, body: DevicePatch):
|
||||
return DeviceOut.of(devices.update_device(device_id, **body.model_dump(exclude_unset=True)))
|
||||
|
||||
|
||||
@router.delete("/devices/{device_id}", status_code=204)
|
||||
async def delete_device(device_id: str):
|
||||
def delete_device(device_id: str):
|
||||
devices.delete_device(device_id)
|
||||
|
||||
|
||||
@@ -224,13 +224,14 @@ async def list_backups(
|
||||
date_from: date | None = None,
|
||||
date_to: date | None = None,
|
||||
q: str = "",
|
||||
refresh: bool = False, # принудительно перечитать бакет, минуя кэш (BACKUPS_CACHE_TTL)
|
||||
):
|
||||
name = devices.get_device(device_id).name if device_id else ""
|
||||
return await backups.list_backups(name, group, kind, date_from, date_to, q)
|
||||
return await backups.list_backups(name, group, kind, date_from, date_to, q, refresh=refresh)
|
||||
|
||||
|
||||
@router.get("/backups/download")
|
||||
async def download_backup(key: str):
|
||||
def download_backup(key: str):
|
||||
if not s3.key_allowed(key):
|
||||
raise ValueError("Недопустимый ключ")
|
||||
return RedirectResponse(s3.presign_get(key))
|
||||
@@ -282,22 +283,22 @@ class JournalSettingsIn(BaseModel):
|
||||
|
||||
|
||||
@router.get("/events/settings")
|
||||
async def get_journal_settings():
|
||||
def get_journal_settings():
|
||||
"""Настройки ротации журнала и сводка (число записей, самая старая запись)."""
|
||||
return {**settings.journal(), **events.stats()}
|
||||
|
||||
|
||||
@router.put("/events/settings")
|
||||
async def put_journal_settings(body: JournalSettingsIn):
|
||||
def put_journal_settings(body: JournalSettingsIn):
|
||||
"""Сохраняет настройки ротации и сразу применяет ротацию. Очистки журнала через API нет — она выполняется
|
||||
только в UI через окно с вводом пароля пользователя."""
|
||||
return {**settings.save_journal(body.retention_days, body.max_rows), **events.stats()}
|
||||
|
||||
|
||||
@router.get("/events", response_model=list[EventOut])
|
||||
async def list_events(entity_id: str | None = None, type: str | None = None, device_id: str | None = None,
|
||||
job_id: str | None = None, actor: str | None = None, date_from: date | None = None,
|
||||
date_to: date | None = None, q: str | None = None, before: str | None = None, limit: int = 100):
|
||||
def list_events(entity_id: str | None = None, type: str | None = None, device_id: str | None = None,
|
||||
job_id: str | None = None, actor: str | None = None, date_from: date | None = None,
|
||||
date_to: date | None = None, q: str | None = None, before: str | None = None, limit: int = 100):
|
||||
"""Журнал событий, новые сверху. type — точный тип (device.created) или группа (device, job, backup);
|
||||
actor — ui, api, poller, system или anonymous. Постранично: before=<ID последней записи предыдущей страницы>."""
|
||||
return events.list_events(entity_id=entity_id, type_=type, device_id=device_id, job_id=job_id, actor=actor,
|
||||
@@ -305,7 +306,7 @@ async def list_events(entity_id: str | None = None, type: str | None = None, dev
|
||||
|
||||
|
||||
@router.get("/events/{event_id}", response_model=EventOut)
|
||||
async def get_event(event_id: str):
|
||||
def get_event(event_id: str):
|
||||
ids.check(event_id, "evt")
|
||||
return events.get_event(event_id)
|
||||
|
||||
@@ -313,10 +314,10 @@ async def get_event(event_id: str):
|
||||
# --- задачи ---
|
||||
|
||||
@router.get("/jobs", response_model=list[JobOut])
|
||||
async def list_jobs():
|
||||
def list_jobs():
|
||||
return jobs.list_jobs()
|
||||
|
||||
|
||||
@router.get("/jobs/{job_id}", response_model=JobOut)
|
||||
async def get_job(job_id: str):
|
||||
def get_job(job_id: str):
|
||||
return jobs.get_job(job_id)
|
||||
Reference in new issue
Block a user