feat: compensate failed uploads and clean stale pending attachments
- upload: delete the stored object when ready fails before COMMIT or the pending row is gone (503 instead of 500); unknown COMMIT outcome keeps it - cleaner service (python -m src.cleaner): stale pending rows older than grace (900 s, must exceed 17 s live-upload bound) under FOR UPDATE SKIP LOCKED, object before row, own S3 user with read/delete only - shared session_scope for API and cleaner; early_stop process name - partial index on pending attachments, CREATE INDEX CONCURRENTLY - s3-bootstrap: cleaner user, policy and checks; make env_setup appends missing template variables to an existing .env - failure checks: cleaner on the failure stand, id-list hook actions, five new and three updated tests; driver upload-consistency - sync upload-consistency deltas into main specs (storage-consistency) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+13
-30
@@ -5,12 +5,11 @@
|
||||
шаг, кэш и хранилище объектов (`src/infra/s3/instance.py`).
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import binascii
|
||||
import re
|
||||
from collections.abc import AsyncIterator
|
||||
from contextlib import asynccontextmanager
|
||||
from contextlib import AbstractAsyncContextManager
|
||||
from dataclasses import dataclass
|
||||
from typing import Annotated
|
||||
|
||||
@@ -29,9 +28,10 @@ from src.core.services import (
|
||||
UserService,
|
||||
)
|
||||
from src.infra.cache.instance import cache
|
||||
from src.infra.db import is_db_unavailable, ping
|
||||
from src.infra.db import ping
|
||||
from src.infra.db.scope import session_scope
|
||||
from src.infra.db.session import engine, session_factory
|
||||
from src.infra.logger import AbstractLogger, current_user_id, get_logger
|
||||
from src.infra.logger import current_user_id
|
||||
from src.infra.s3.instance import object_storage
|
||||
from src.schemas import dataclasses
|
||||
from src.utils.constants import (
|
||||
@@ -44,35 +44,18 @@ from src.utils.constants import (
|
||||
USERNAME_PATTERN,
|
||||
)
|
||||
|
||||
logger: AbstractLogger = get_logger().bind(module="api_dependencies")
|
||||
|
||||
def db_session_scope() -> AbstractAsyncContextManager[AsyncSession]:
|
||||
"""Сессия БД процесса API на один шаг; commit делает сервис.
|
||||
|
||||
@asynccontextmanager
|
||||
async def db_session_scope() -> AsyncIterator[AsyncSession]:
|
||||
"""Сессия БД на один шаг; commit делает сервис.
|
||||
|
||||
Незакоммиченное при выходе откатывается. Работа с БД внутри
|
||||
ограничена `[database] request_timeout_seconds`: зависший Postgres не
|
||||
держит запрос бесконечно. Недоступность БД (`is_db_unavailable`) —
|
||||
503 `unavailable`, а соединение не возвращается в пул: его состояние
|
||||
неизвестно, а откат на зависшем сервере повис бы.
|
||||
`session_scope` (`src/infra/db/scope.py`) с фабрикой процесса API и
|
||||
сроком `[database] request_timeout_seconds`: незакоммиченное
|
||||
откатывается, отказ БД — 503 `unavailable`.
|
||||
"""
|
||||
async with session_factory() as db_session:
|
||||
try:
|
||||
async with asyncio.timeout(
|
||||
settings.database.request_timeout_seconds,
|
||||
):
|
||||
yield db_session
|
||||
except Exception as e:
|
||||
if not is_db_unavailable(e):
|
||||
raise
|
||||
await db_session.invalidate()
|
||||
logger.warning(
|
||||
"Database is unavailable",
|
||||
error_type=type(e).__name__,
|
||||
error=str(e),
|
||||
)
|
||||
raise exceptions.ServiceUnavailable from e
|
||||
return session_scope(
|
||||
session_factory,
|
||||
timeout_seconds=settings.database.request_timeout_seconds,
|
||||
)
|
||||
|
||||
|
||||
async def get_db_session() -> AsyncIterator[AsyncSession]:
|
||||
|
||||
Reference in New Issue
Block a user