forked from mtusi2026/mtusi2026lab4
refactoring
This commit is contained in:
+13
-9
@@ -9,6 +9,7 @@ import warnings
|
||||
from fastapi import APIRouter, Depends, Query, Request, Response
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
from starlette.requests import ClientDisconnect
|
||||
|
||||
from .errors import ApiError
|
||||
from .models import Attachment
|
||||
@@ -81,15 +82,18 @@ async def upload(chat_id: UUID, request: Request, filename: str = Query(...),
|
||||
await run_in_threadpool(inspect_image, file, content_type, s3.settings.max_pixels)
|
||||
attachment_id = uuid4()
|
||||
key = f"originals/{attachment_id}"
|
||||
await s3.put(key, file, size, content_type)
|
||||
# Disabled by default. Used only by the failure-injection test to
|
||||
# model a process crash after S3 accepts the object and before DB.
|
||||
if os.environ.get("UPLOAD_FAULT_AFTER_S3_PUT") == "1":
|
||||
raise ApiError(503, "unavailable", "Инъецирован отказ после S3 PUT")
|
||||
return await store.create_attachment(
|
||||
attachment_id, chat_id, user["id"], filename, content_type,
|
||||
size, digest.hexdigest(), key,
|
||||
)
|
||||
async with store.attachment_transaction() as connection:
|
||||
await s3.put(key, file, size, content_type)
|
||||
# Disabled by default; models a crash after PUT, before INSERT.
|
||||
if os.environ.get("UPLOAD_FAULT_AFTER_S3_PUT") == "1":
|
||||
raise ApiError(503, "unavailable", "Инъецирован отказ после S3 PUT")
|
||||
attachment = await store.create_attachment(
|
||||
attachment_id, chat_id, user["id"], filename, content_type,
|
||||
size, digest.hexdigest(), key, connection=connection,
|
||||
)
|
||||
return attachment # Transaction has committed before 201.
|
||||
except ClientDisconnect:
|
||||
raise ApiError(400, "invalid_request", "Загрузка прервана") from None
|
||||
except TimeoutError:
|
||||
raise ApiError(503, "unavailable", "Время загрузки истекло") from None
|
||||
|
||||
|
||||
+19
-5
@@ -20,14 +20,23 @@ async def run(args) -> dict:
|
||||
settings = load_settings()
|
||||
db = PostgresStore(settings.database_url)
|
||||
s3 = S3Store(S3Settings.load())
|
||||
await db.connect()
|
||||
try:
|
||||
await db.connect()
|
||||
async with db.attachment_transaction(maintenance=True):
|
||||
return await scan(args, db, s3)
|
||||
finally:
|
||||
s3.client.close()
|
||||
await db.close()
|
||||
|
||||
|
||||
async def scan(args, db, s3) -> dict:
|
||||
# Age is measured at scan start, not after a potentially slow inventory.
|
||||
cutoff = datetime.now(timezone.utc) - timedelta(seconds=args.grace_seconds)
|
||||
started = perf_counter()
|
||||
objects, s3_pages = await s3.list_with_pages("originals/")
|
||||
listed_at = perf_counter()
|
||||
metadata = await db.attachment_keys()
|
||||
metadata_at = perf_counter()
|
||||
cutoff = datetime.now(timezone.utc) - timedelta(seconds=args.grace_seconds)
|
||||
orphan = sorted(key for key, modified in objects.items()
|
||||
if key not in metadata and modified <= cutoff)
|
||||
fresh = sorted(key for key, modified in objects.items()
|
||||
@@ -35,8 +44,11 @@ async def run(args) -> dict:
|
||||
missing = sorted({str(attachment_id): key for key, attachment_id in metadata.items()
|
||||
if key not in objects}.items())
|
||||
deleted = []
|
||||
selected = set(args.object_key) if args.object_key else None
|
||||
if args.apply:
|
||||
for key in orphan:
|
||||
if selected is not None and key not in selected:
|
||||
continue
|
||||
await s3.delete(key)
|
||||
deleted.append(key)
|
||||
finished = perf_counter()
|
||||
@@ -49,6 +61,7 @@ async def run(args) -> dict:
|
||||
"fresh_unreferenced": fresh,
|
||||
"missing_objects": [{"attachment_id": item[0], "object_key": item[1]} for item in missing],
|
||||
"deleted": deleted,
|
||||
"selected_keys": sorted(selected) if selected is not None else None,
|
||||
"scan_metrics": {
|
||||
"s3_list_pages": s3_pages,
|
||||
"s3_list_seconds": round(listed_at - started, 6),
|
||||
@@ -56,18 +69,19 @@ async def run(args) -> dict:
|
||||
"total_seconds": round(finished - started, 6),
|
||||
},
|
||||
}
|
||||
finally:
|
||||
s3.client.close()
|
||||
await db.close()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--apply", action="store_true", help="delete only aged orphan objects")
|
||||
parser.add_argument("--grace-seconds", type=int, default=3600)
|
||||
parser.add_argument("--object-key", action="append", default=[],
|
||||
help="restrict apply to these exact keys; repeatable, inventory stays complete")
|
||||
args = parser.parse_args()
|
||||
if not 0 <= args.grace_seconds <= 7 * 24 * 3600:
|
||||
parser.error("--grace-seconds must be 0..604800")
|
||||
if any(not key.startswith("originals/") for key in args.object_key):
|
||||
parser.error("--object-key must start with originals/")
|
||||
print(json.dumps(asyncio.run(run(args)), ensure_ascii=False, sort_keys=True))
|
||||
|
||||
|
||||
|
||||
+22
-4
@@ -1,4 +1,5 @@
|
||||
from datetime import datetime
|
||||
from contextlib import asynccontextmanager
|
||||
from hashlib import sha256
|
||||
import json
|
||||
from pathlib import Path
|
||||
@@ -15,7 +16,7 @@ from ..errors import ApiError
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
MIGRATIONS = ROOT / "migrations"
|
||||
PASSWORD_HASHER = PasswordHasher()
|
||||
DB_ERRORS = (asyncpg.PostgresError, asyncpg.InterfaceError, OSError)
|
||||
DB_ERRORS = (asyncpg.PostgresError, asyncpg.InterfaceError, OSError, TimeoutError)
|
||||
|
||||
|
||||
class PostgresStore:
|
||||
@@ -301,10 +302,27 @@ class PostgresStore:
|
||||
return [self._message(row) for row in rows]
|
||||
|
||||
|
||||
async def create_attachment(self, attachment_id, chat_id, owner_id, filename,
|
||||
content_type, size_bytes, digest, object_key) -> dict:
|
||||
@asynccontextmanager
|
||||
async def attachment_transaction(self, *, maintenance=False):
|
||||
"""Shared writer / exclusive reconciler lock across all API replicas.
|
||||
|
||||
Writers hold the transaction from before PUT through metadata COMMIT.
|
||||
Maintenance holds the exclusive lock through inventory and deletion.
|
||||
All attachment writers must participate in this protocol.
|
||||
"""
|
||||
try:
|
||||
row = await self.pool.fetchrow(
|
||||
async with self.pool.acquire() as connection, connection.transaction():
|
||||
await connection.execute("SET LOCAL lock_timeout = '5s'")
|
||||
lock = "pg_advisory_xact_lock" if maintenance else "pg_advisory_xact_lock_shared"
|
||||
await connection.execute(f"SELECT {lock}(41004, 1)")
|
||||
yield connection
|
||||
except DB_ERRORS as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
|
||||
async def create_attachment(self, attachment_id, chat_id, owner_id, filename,
|
||||
content_type, size_bytes, digest, object_key, *, connection=None) -> dict:
|
||||
try:
|
||||
row = await (connection or self.pool).fetchrow(
|
||||
"INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key) "
|
||||
"VALUES ($1,$2,$3,$4,$5,$6,$7,$8) RETURNING *",
|
||||
attachment_id, chat_id, owner_id, filename, content_type, size_bytes, digest, object_key,
|
||||
|
||||
Reference in New Issue
Block a user