forked from mtusi2026/mtusi2026lab4
выполнение ЛР4 на 4
- S3: SeaweedFS 4.51 (MinIO-образы недоступны), приватный bucket, отдельные ограниченные ключи API, служебные порты закрыты; идемпотентный s3-init с проверкой приватности и прогревом записи - вложения: потоковая загрузка PNG/JPEG, лимиты 10 MiB / 40 Мпикс, тип по содержимому, проверка filename, скачивание только участникам - согласованность PG/S3: pending -> PUT -> ready, компенсация, sweeper с grace и dry-run; attachment_ids в сообщениях, FK по чату - back-pressure на S3 PUT после найденного OOM SeaweedFS - тесты student-tests, evidence, REPORT.md, DEMO.md
This commit is contained in:
+113
@@ -0,0 +1,113 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import binascii
|
||||
import hashlib
|
||||
import secrets
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional, Tuple
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import InvalidHashError, VerificationError
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
|
||||
from app import config
|
||||
from app.cache import REVOKED, SessionCache
|
||||
from app.errors import BASIC_CHALLENGE, ApiError, unauthorized
|
||||
from app.storage import Store, fmt_ts, user_row
|
||||
|
||||
_hasher = PasswordHasher()
|
||||
_hash_slots = asyncio.Semaphore(config.PASSWORD_HASH_CONCURRENCY)
|
||||
_DUMMY_HASH = _hasher.hash("dummy-password-for-timing")
|
||||
|
||||
|
||||
async def hash_password(password: str) -> str:
|
||||
async with _hash_slots:
|
||||
return await run_in_threadpool(_hasher.hash, password)
|
||||
|
||||
|
||||
async def verify_password(password_hash: str, password: str) -> bool:
|
||||
def verify() -> bool:
|
||||
try:
|
||||
return _hasher.verify(password_hash, password)
|
||||
except (VerificationError, InvalidHashError):
|
||||
return False
|
||||
|
||||
async with _hash_slots:
|
||||
return await run_in_threadpool(verify)
|
||||
|
||||
|
||||
def token_digest(token: str) -> bytes:
|
||||
return hashlib.sha256(token.encode("ascii")).digest()
|
||||
|
||||
|
||||
def parse_basic(header: Optional[str]) -> Tuple[str, str]:
|
||||
bad = unauthorized("invalid credentials", BASIC_CHALLENGE)
|
||||
if not header:
|
||||
raise bad
|
||||
scheme, _, value = header.partition(" ")
|
||||
if scheme.lower() != "basic" or not value.strip():
|
||||
raise bad
|
||||
try:
|
||||
decoded = base64.b64decode(value.strip(), validate=True).decode("utf-8")
|
||||
except (binascii.Error, UnicodeDecodeError):
|
||||
raise bad from None
|
||||
username, sep, password = decoded.partition(":")
|
||||
if not sep or not username.isascii() or not 12 <= len(password) <= 128:
|
||||
raise bad
|
||||
return username, password
|
||||
|
||||
|
||||
def parse_bearer(header: Optional[str]) -> str:
|
||||
if not header:
|
||||
raise unauthorized("bearer token required")
|
||||
scheme, _, token = header.partition(" ")
|
||||
token = token.strip()
|
||||
if scheme.lower() != "bearer" or not token or not token.isascii() or len(token) > 256:
|
||||
raise unauthorized("bearer token required")
|
||||
return token
|
||||
|
||||
|
||||
async def login(store: Store, header: Optional[str]) -> dict:
|
||||
username, password = parse_basic(header)
|
||||
row = await store.get_credentials(username)
|
||||
if row is None:
|
||||
await verify_password(_DUMMY_HASH, password)
|
||||
raise unauthorized("invalid credentials", BASIC_CHALLENGE)
|
||||
if not await verify_password(row["password_hash"], password):
|
||||
raise unauthorized("invalid credentials", BASIC_CHALLENGE)
|
||||
token = secrets.token_urlsafe(32)
|
||||
expires_at = await store.create_session(token_digest(token), row["id"], config.SESSION_TTL_SECONDS)
|
||||
return {"token": token, "token_type": "Bearer", "expires_at": fmt_ts(expires_at), "user": user_row(row)}
|
||||
|
||||
|
||||
async def authenticate(store: Store, cache: SessionCache, header: Optional[str]) -> dict:
|
||||
digest = token_digest(parse_bearer(header))
|
||||
cached = await cache.get(digest)
|
||||
if cached == REVOKED:
|
||||
raise unauthorized("session expired or revoked")
|
||||
if isinstance(cached, dict):
|
||||
expires_at = datetime.fromisoformat(cached["expires_at"].replace("Z", "+00:00"))
|
||||
if expires_at > datetime.now(timezone.utc):
|
||||
return cached["user"]
|
||||
raise unauthorized("session expired or revoked")
|
||||
|
||||
row = await store.find_session(digest)
|
||||
if row is None:
|
||||
raise unauthorized("session expired or revoked")
|
||||
user = user_row(row)
|
||||
remaining = int((row["expires_at"] - datetime.now(timezone.utc)).total_seconds())
|
||||
await cache.put(digest, {"user": user, "expires_at": fmt_ts(row["expires_at"])}, remaining)
|
||||
return user
|
||||
|
||||
|
||||
async def logout(store: Store, cache: SessionCache, header: Optional[str]) -> None:
|
||||
await authenticate(store, cache, header)
|
||||
digest = token_digest(parse_bearer(header))
|
||||
expires_at = await store.revoke_session(digest)
|
||||
if expires_at is None:
|
||||
raise unauthorized("session expired or revoked")
|
||||
remaining = int((expires_at - datetime.now(timezone.utc)).total_seconds()) + 1
|
||||
if not await cache.revoke(digest, remaining):
|
||||
raise ApiError(503, "unavailable", "logout not confirmed by session cache, retry later")
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
from typing import Dict, Optional, Set, Union
|
||||
|
||||
import redis.asyncio as redis
|
||||
from redis.exceptions import RedisError
|
||||
|
||||
from app import config
|
||||
|
||||
logger = logging.getLogger("messenger.cache")
|
||||
|
||||
REVOKED = "revoked"
|
||||
|
||||
|
||||
class SessionCache:
|
||||
def __init__(self, url: Optional[str]):
|
||||
self._client: Optional[redis.Redis] = None
|
||||
self._down_until = 0.0
|
||||
self._pending_revokes: Dict[bytes, float] = {}
|
||||
self._retry_tasks: Set[asyncio.Task] = set()
|
||||
if url:
|
||||
pool = redis.BlockingConnectionPool.from_url(
|
||||
url,
|
||||
max_connections=config.CACHE_POOL_MAX,
|
||||
timeout=config.CACHE_TIMEOUT,
|
||||
socket_timeout=config.CACHE_TIMEOUT,
|
||||
socket_connect_timeout=config.CACHE_TIMEOUT,
|
||||
decode_responses=True,
|
||||
)
|
||||
self._client = redis.Redis(connection_pool=pool)
|
||||
|
||||
@property
|
||||
def enabled(self) -> bool:
|
||||
return self._client is not None
|
||||
|
||||
def _usable(self) -> bool:
|
||||
return self._client is not None and time.monotonic() >= self._down_until
|
||||
|
||||
def _failed(self, op: str, exc: Exception) -> None:
|
||||
self._down_until = time.monotonic() + config.CACHE_RETRY_AFTER
|
||||
logger.warning("cache %s failed (%s); bypassing cache for %.0fs", op, type(exc).__name__, config.CACHE_RETRY_AFTER)
|
||||
|
||||
@staticmethod
|
||||
def _key(token_hash: bytes) -> str:
|
||||
return "session:" + token_hash.hex()
|
||||
|
||||
def _revoke_pending(self, token_hash: bytes) -> bool:
|
||||
deadline = self._pending_revokes.get(token_hash)
|
||||
if deadline is None:
|
||||
return False
|
||||
if time.monotonic() >= deadline:
|
||||
self._pending_revokes.pop(token_hash, None)
|
||||
return False
|
||||
return True
|
||||
|
||||
async def get(self, token_hash: bytes) -> Union[dict, str, None]:
|
||||
if not self._usable() or self._revoke_pending(token_hash):
|
||||
return None
|
||||
try:
|
||||
raw = await self._client.get(self._key(token_hash))
|
||||
except (RedisError, OSError) as exc:
|
||||
self._failed("get", exc)
|
||||
return None
|
||||
if raw is None or raw == REVOKED:
|
||||
return raw
|
||||
try:
|
||||
return json.loads(raw)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
async def put(self, token_hash: bytes, entry: dict, ttl_seconds: int) -> None:
|
||||
ttl = min(ttl_seconds, config.SESSION_CACHE_MAX_SECONDS)
|
||||
if ttl <= 0 or not self._usable():
|
||||
return
|
||||
try:
|
||||
await self._client.set(self._key(token_hash), json.dumps(entry), ex=ttl, nx=True)
|
||||
except (RedisError, OSError) as exc:
|
||||
self._failed("set", exc)
|
||||
|
||||
async def _write_tombstone(self, token_hash: bytes, ttl_seconds: int) -> bool:
|
||||
try:
|
||||
await self._client.set(self._key(token_hash), REVOKED, ex=max(1, min(ttl_seconds, config.SESSION_CACHE_MAX_SECONDS)))
|
||||
return True
|
||||
except (RedisError, OSError) as exc:
|
||||
self._failed("revoke", exc)
|
||||
return False
|
||||
|
||||
async def revoke(self, token_hash: bytes, ttl_seconds: int) -> bool:
|
||||
if self._client is None:
|
||||
return True
|
||||
if await self._write_tombstone(token_hash, ttl_seconds):
|
||||
return True
|
||||
deadline = time.monotonic() + config.SESSION_CACHE_MAX_SECONDS + 1
|
||||
self._pending_revokes[token_hash] = deadline
|
||||
task = asyncio.create_task(self._retry_revoke(token_hash, ttl_seconds, deadline))
|
||||
self._retry_tasks.add(task)
|
||||
task.add_done_callback(self._retry_tasks.discard)
|
||||
return False
|
||||
|
||||
async def _retry_revoke(self, token_hash: bytes, ttl_seconds: int, deadline: float) -> None:
|
||||
while time.monotonic() < deadline:
|
||||
await asyncio.sleep(1)
|
||||
remaining = int(deadline - time.monotonic())
|
||||
if remaining > 0 and await self._write_tombstone(token_hash, min(ttl_seconds, remaining)):
|
||||
logger.info("revocation tombstone written after cache recovery")
|
||||
break
|
||||
self._pending_revokes.pop(token_hash, None)
|
||||
|
||||
async def ping(self) -> bool:
|
||||
if self._client is None:
|
||||
return False
|
||||
try:
|
||||
return bool(await self._client.ping())
|
||||
except (RedisError, OSError):
|
||||
return False
|
||||
|
||||
async def close(self) -> None:
|
||||
for task in list(self._retry_tasks):
|
||||
task.cancel()
|
||||
if self._client is not None:
|
||||
await self._client.aclose()
|
||||
@@ -0,0 +1,69 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import secrets
|
||||
from typing import Optional
|
||||
|
||||
|
||||
def _secret(name: str) -> Optional[str]:
|
||||
value = os.environ.get(name)
|
||||
if value:
|
||||
return value.strip()
|
||||
path = os.environ.get(name + "_FILE")
|
||||
if path and os.path.exists(path):
|
||||
with open(path, encoding="utf-8") as fh:
|
||||
return fh.read().strip() or None
|
||||
return None
|
||||
|
||||
|
||||
def _int(name: str, default: int) -> int:
|
||||
return int(os.environ.get(name, default))
|
||||
|
||||
|
||||
def _float(name: str, default: float) -> float:
|
||||
return float(os.environ.get(name, default))
|
||||
|
||||
|
||||
DATABASE_URL = _secret("DATABASE_URL")
|
||||
CACHE_URL = _secret("CACHE_URL")
|
||||
|
||||
S3_ENDPOINT = os.environ.get("S3_ENDPOINT", "http://s3:8333")
|
||||
S3_REGION = os.environ.get("S3_REGION", "us-east-1")
|
||||
S3_BUCKET = os.environ.get("S3_BUCKET", "messenger-attachments")
|
||||
S3_ACCESS_KEY_ID = _secret("S3_ACCESS_KEY_ID")
|
||||
S3_SECRET_ACCESS_KEY = _secret("S3_SECRET_ACCESS_KEY")
|
||||
S3_CONNECT_TIMEOUT = _float("S3_CONNECT_TIMEOUT", 2)
|
||||
S3_READ_TIMEOUT = _float("S3_READ_TIMEOUT", 5)
|
||||
S3_POOL_MAX = _int("S3_POOL_MAX", 20)
|
||||
# Without this cap 20 parallel 10 MiB PUTs drove SeaweedFS (512M limit) into an OOM kill.
|
||||
S3_PUT_CONCURRENCY = _int("S3_PUT_CONCURRENCY", 4)
|
||||
|
||||
SESSION_TTL_SECONDS = _int("SESSION_TTL_SECONDS", 3600)
|
||||
SESSION_CACHE_MAX_SECONDS = _int("SESSION_CACHE_MAX_SECONDS", 300)
|
||||
|
||||
DB_POOL_MAX = _int("DB_POOL_MAX", 10)
|
||||
DB_CONNECT_TIMEOUT = _float("DB_CONNECT_TIMEOUT", 3)
|
||||
DB_ACQUIRE_TIMEOUT = _float("DB_ACQUIRE_TIMEOUT", 3)
|
||||
DB_COMMAND_TIMEOUT = _float("DB_COMMAND_TIMEOUT", 5)
|
||||
|
||||
CACHE_TIMEOUT = _float("CACHE_TIMEOUT", 0.3)
|
||||
CACHE_POOL_MAX = _int("CACHE_POOL_MAX", 20)
|
||||
CACHE_RETRY_AFTER = _float("CACHE_RETRY_AFTER", 5)
|
||||
|
||||
PASSWORD_HASH_CONCURRENCY = _int("PASSWORD_HASH_CONCURRENCY", 4)
|
||||
|
||||
IDEMPOTENCY_TTL_SECONDS = _int("IDEMPOTENCY_TTL_SECONDS", 86400)
|
||||
|
||||
MAX_UPLOAD_BYTES = _int("MAX_UPLOAD_BYTES", 10 * 1024 * 1024)
|
||||
MAX_IMAGE_PIXELS = _int("MAX_IMAGE_PIXELS", 40_000_000)
|
||||
UPLOAD_SPOOL_BYTES = _int("UPLOAD_SPOOL_BYTES", 1024 * 1024)
|
||||
UPLOAD_TMP_DIR = os.environ.get("UPLOAD_TMP_DIR") or None
|
||||
UPLOAD_TIMEOUT_SECONDS = _float("UPLOAD_TIMEOUT_SECONDS", 60)
|
||||
UPLOAD_CONCURRENCY = _int("UPLOAD_CONCURRENCY", 16)
|
||||
DECODE_CONCURRENCY = _int("DECODE_CONCURRENCY", 1)
|
||||
|
||||
ORPHAN_GRACE_SECONDS = _int("ORPHAN_GRACE_SECONDS", 900)
|
||||
SWEEP_INTERVAL_SECONDS = _int("SWEEP_INTERVAL_SECONDS", 60)
|
||||
|
||||
INSTANCE_ID = "api-" + secrets.token_hex(4)
|
||||
INSTANCE_ID_FILE = os.environ.get("INSTANCE_ID_FILE", "/tmp/instance-id")
|
||||
@@ -0,0 +1,31 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Dict, Optional
|
||||
|
||||
BEARER_CHALLENGE = 'Bearer realm="messenger"'
|
||||
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
|
||||
|
||||
|
||||
class ApiError(Exception):
|
||||
def __init__(self, status_code: int, code: str, message: str, headers: Optional[Dict[str, str]] = None):
|
||||
super().__init__(message)
|
||||
self.status_code = status_code
|
||||
self.code = code
|
||||
self.message = message
|
||||
self.headers = headers or {}
|
||||
|
||||
|
||||
def unauthorized(message: str, challenge: str = BEARER_CHALLENGE) -> ApiError:
|
||||
return ApiError(401, "unauthorized", message, {"WWW-Authenticate": challenge})
|
||||
|
||||
|
||||
def unavailable() -> ApiError:
|
||||
return ApiError(503, "unavailable", "service temporarily unavailable")
|
||||
|
||||
|
||||
def payload_too_large(message: str) -> ApiError:
|
||||
return ApiError(413, "payload_too_large", message)
|
||||
|
||||
|
||||
def unsupported_media_type(message: str) -> ApiError:
|
||||
return ApiError(415, "unsupported_media_type", message)
|
||||
@@ -0,0 +1,84 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import unicodedata
|
||||
import warnings
|
||||
from typing import BinaryIO, Optional, Tuple
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from app import config
|
||||
from app.errors import ApiError, payload_too_large, unsupported_media_type
|
||||
|
||||
# Pillow itself refuses > 2x this value; our own check below rejects anything above it before decoding.
|
||||
Image.MAX_IMAGE_PIXELS = config.MAX_IMAGE_PIXELS
|
||||
Image.LOAD_TRUNCATED_IMAGES = False
|
||||
|
||||
PNG_MAGIC = b"\x89PNG\r\n\x1a\n"
|
||||
JPEG_MAGIC = b"\xff\xd8\xff"
|
||||
FORMATS = {"image/png": "PNG", "image/jpeg": "JPEG"}
|
||||
SNIFF_BYTES = 8
|
||||
|
||||
# Bidi overrides/isolates make "gpj.exe" look like "exe.jpg"; reject them together with control characters.
|
||||
_BIDI_CONTROLS = set("")
|
||||
|
||||
|
||||
def validate_filename(name: Optional[str]) -> str:
|
||||
bad = ApiError(400, "invalid_request", "filename must be 1-255 characters without path separators or control characters")
|
||||
if name is None or not 1 <= len(name) <= 255 or not name.strip() or name in (".", ".."):
|
||||
raise bad
|
||||
for ch in name:
|
||||
if ch in "/\\" or ch in _BIDI_CONTROLS or unicodedata.category(ch) in ("Cc", "Zl", "Zp"):
|
||||
raise bad
|
||||
return name
|
||||
|
||||
|
||||
def declared_type(header: Optional[str]) -> str:
|
||||
media = (header or "").split(";", 1)[0].strip().lower()
|
||||
if media not in FORMATS:
|
||||
raise unsupported_media_type("Content-Type must be image/png or image/jpeg")
|
||||
return media
|
||||
|
||||
|
||||
def sniff(head: bytes) -> Optional[str]:
|
||||
if head.startswith(PNG_MAGIC):
|
||||
return "image/png"
|
||||
if head.startswith(JPEG_MAGIC):
|
||||
return "image/jpeg"
|
||||
return None
|
||||
|
||||
|
||||
def _open(fp: BinaryIO, fmt: str) -> Image.Image:
|
||||
fp.seek(0)
|
||||
return Image.open(fp, formats=[fmt])
|
||||
|
||||
|
||||
def inspect(fp: BinaryIO, content_type: str) -> Tuple[int, int]:
|
||||
"""Check pixel count from the header, then fully decode to reject corrupted files.
|
||||
|
||||
Runs in a worker thread under a semaphore: decoding is the only step whose memory grows with pixels.
|
||||
"""
|
||||
fmt = FORMATS[content_type]
|
||||
corrupt = unsupported_media_type("file is not a valid " + fmt + " image")
|
||||
try:
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("error", Image.DecompressionBombWarning)
|
||||
with _open(fp, fmt) as im:
|
||||
width, height = im.size
|
||||
if width < 1 or height < 1:
|
||||
raise corrupt
|
||||
if width * height > config.MAX_IMAGE_PIXELS:
|
||||
raise payload_too_large("image exceeds %d pixels" % config.MAX_IMAGE_PIXELS)
|
||||
if fmt == "PNG":
|
||||
im.verify() # chunk CRCs; the object is unusable afterwards
|
||||
with _open(fp, fmt) as im:
|
||||
if fmt == "JPEG":
|
||||
# DCT scaling still walks the whole entropy-coded stream but allocates 1/64 of the pixels.
|
||||
im.draft(None, (max(1, width // 8), max(1, height // 8)))
|
||||
im.load()
|
||||
except ApiError:
|
||||
raise
|
||||
except (Image.DecompressionBombError, Image.DecompressionBombWarning):
|
||||
raise payload_too_large("image exceeds %d pixels" % config.MAX_IMAGE_PIXELS) from None
|
||||
except (OSError, SyntaxError, ValueError, EOFError, MemoryError):
|
||||
raise corrupt from None
|
||||
return width, height
|
||||
+374
@@ -0,0 +1,374 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import tempfile
|
||||
import uuid
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import Optional
|
||||
|
||||
import asyncpg
|
||||
from fastapi import Depends, FastAPI, Header, Query, Request, Response
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse, StreamingResponse
|
||||
from starlette.background import BackgroundTask
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
from starlette.requests import ClientDisconnect
|
||||
|
||||
from app import auth, config, images
|
||||
from app.cache import SessionCache
|
||||
from app.errors import ApiError, payload_too_large, unsupported_media_type
|
||||
from app.models import (Attachment, Chat, ChatPage, CreateChat, CreateMessage, CreateUser, Health, Message, MessagePage,
|
||||
Session, User)
|
||||
from app.objects import ObjectStore, S3Unavailable, storage_unavailable
|
||||
from app.storage import Store, attachment_row
|
||||
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger("messenger")
|
||||
|
||||
store = Store()
|
||||
cache = SessionCache(config.CACHE_URL)
|
||||
objects = ObjectStore()
|
||||
upload_slots = asyncio.Semaphore(config.UPLOAD_CONCURRENCY)
|
||||
decode_slots = asyncio.Semaphore(config.DECODE_CONCURRENCY)
|
||||
s3_put_slots = asyncio.Semaphore(config.S3_PUT_CONCURRENCY)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app: FastAPI):
|
||||
if not config.DATABASE_URL:
|
||||
raise RuntimeError("DATABASE_URL or DATABASE_URL_FILE is required")
|
||||
if not (config.S3_ACCESS_KEY_ID and config.S3_SECRET_ACCESS_KEY):
|
||||
raise RuntimeError("S3_ACCESS_KEY_ID(_FILE) and S3_SECRET_ACCESS_KEY(_FILE) are required")
|
||||
await store.open()
|
||||
logger.info("session cache: %s", "valkey" if cache.enabled else "disabled")
|
||||
logger.info("object storage: %s bucket=%s", config.S3_ENDPOINT, config.S3_BUCKET)
|
||||
try:
|
||||
with open(config.INSTANCE_ID_FILE, "w", encoding="ascii") as fh:
|
||||
fh.write(config.INSTANCE_ID + "\n")
|
||||
except OSError:
|
||||
logger.warning("cannot write %s", config.INSTANCE_ID_FILE)
|
||||
logger.info("instance id: %s", config.INSTANCE_ID)
|
||||
yield
|
||||
await cache.close()
|
||||
await store.close()
|
||||
|
||||
|
||||
app = FastAPI(title="MTUSI Messenger — lab4", lifespan=lifespan)
|
||||
|
||||
IDEMPOTENCY_KEY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
|
||||
|
||||
|
||||
DB_UNAVAILABLE = (
|
||||
OSError,
|
||||
asyncpg.PostgresConnectionError,
|
||||
asyncpg.InterfaceError,
|
||||
asyncpg.TooManyConnectionsError,
|
||||
asyncpg.exceptions.OperatorInterventionError,
|
||||
asyncpg.exceptions.QueryCanceledError,
|
||||
)
|
||||
|
||||
|
||||
def error_body(code: str, message: str, request_id: str) -> dict:
|
||||
return {"error": {"code": code, "message": message, "request_id": request_id}}
|
||||
|
||||
|
||||
def error_response(request: Request, status: int, code: str, message: str, headers: Optional[dict] = None) -> JSONResponse:
|
||||
request_id = getattr(request.state, "request_id", "")
|
||||
return JSONResponse(status_code=status, content=error_body(code, message, request_id), headers=headers)
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def request_id_middleware(request: Request, call_next):
|
||||
request_id = uuid.uuid4().hex
|
||||
request.state.request_id = request_id
|
||||
try:
|
||||
response = await call_next(request)
|
||||
except Exception:
|
||||
logger.exception("unhandled error for request_id=%s", request_id)
|
||||
response = JSONResponse(status_code=500, content=error_body("internal_error", "internal error", request_id))
|
||||
response.headers["X-Request-Id"] = request_id
|
||||
response.headers["X-Instance-Id"] = config.INSTANCE_ID
|
||||
return response
|
||||
|
||||
|
||||
@app.exception_handler(ApiError)
|
||||
async def api_error_handler(request: Request, exc: ApiError):
|
||||
return error_response(request, exc.status_code, exc.code, exc.message, exc.headers)
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_error_handler(request: Request, exc: RequestValidationError):
|
||||
return error_response(request, 400, "invalid_request", "request failed validation")
|
||||
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
|
||||
code = {404: "not_found", 405: "invalid_request", 413: "payload_too_large", 415: "unsupported_media_type"}.get(
|
||||
exc.status_code, "invalid_request")
|
||||
message = exc.detail if isinstance(exc.detail, str) else "request failed"
|
||||
return error_response(request, exc.status_code, code, message)
|
||||
|
||||
|
||||
async def db_unavailable_handler(request: Request, exc: Exception):
|
||||
logger.warning("database unavailable for request_id=%s: %s", request.state.request_id, type(exc).__name__)
|
||||
return error_response(request, 503, "unavailable", "service temporarily unavailable")
|
||||
|
||||
|
||||
for _exc in DB_UNAVAILABLE:
|
||||
app.add_exception_handler(_exc, db_unavailable_handler)
|
||||
|
||||
|
||||
@app.exception_handler(S3Unavailable)
|
||||
async def s3_unavailable_handler(request: Request, exc: S3Unavailable):
|
||||
err = storage_unavailable()
|
||||
return error_response(request, err.status_code, err.code, err.message)
|
||||
|
||||
|
||||
async def current_user(request: Request) -> dict:
|
||||
return await auth.authenticate(store, cache, request.headers.get("Authorization"))
|
||||
|
||||
|
||||
def parse_uuid(value: str, field: str) -> uuid.UUID:
|
||||
try:
|
||||
return uuid.UUID(value)
|
||||
except ValueError:
|
||||
raise ApiError(400, "invalid_request", f"{field} is not a valid UUID") from None
|
||||
|
||||
|
||||
def not_found() -> ApiError:
|
||||
return ApiError(404, "not_found", "chat not found")
|
||||
|
||||
|
||||
@app.get("/health/live", response_model=Health)
|
||||
async def liveness():
|
||||
return Health()
|
||||
|
||||
|
||||
@app.get("/health/ready", response_model=Health)
|
||||
async def readiness():
|
||||
try:
|
||||
await store.ping()
|
||||
except DB_UNAVAILABLE:
|
||||
raise ApiError(503, "unavailable", "database is not available") from None
|
||||
return Health()
|
||||
|
||||
|
||||
@app.post("/api/v1/users", response_model=User, status_code=201)
|
||||
async def register_user(body: CreateUser):
|
||||
if not body.display_name.strip() or not body.password.strip():
|
||||
raise ApiError(400, "invalid_request", "display_name and password must not be blank")
|
||||
password_hash = await auth.hash_password(body.password)
|
||||
return await store.create_user(body.username, body.display_name, password_hash)
|
||||
|
||||
|
||||
@app.get("/api/v1/users/me", response_model=User)
|
||||
async def current_user_endpoint(user: dict = Depends(current_user)):
|
||||
return user
|
||||
|
||||
|
||||
@app.post("/api/v1/auth/sessions", response_model=Session, status_code=201)
|
||||
async def create_session(request: Request):
|
||||
return await auth.login(store, request.headers.get("Authorization"))
|
||||
|
||||
|
||||
@app.delete("/api/v1/auth/sessions/current", status_code=204)
|
||||
async def delete_session(request: Request):
|
||||
await auth.logout(store, cache, request.headers.get("Authorization"))
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
@app.post("/api/v1/chats", response_model=Chat, status_code=201)
|
||||
async def create_chat(body: CreateChat, user: dict = Depends(current_user)):
|
||||
if not body.title.strip():
|
||||
raise ApiError(400, "invalid_request", "title must not be blank")
|
||||
if len(set(body.member_ids)) != len(body.member_ids):
|
||||
raise ApiError(400, "invalid_request", "member_ids must not contain duplicates")
|
||||
if uuid.UUID(user["id"]) not in body.member_ids:
|
||||
raise ApiError(400, "invalid_request", "caller must be a member of the chat")
|
||||
return await store.create_chat(body.title, list(body.member_ids))
|
||||
|
||||
|
||||
@app.get("/api/v1/chats", response_model=ChatPage)
|
||||
async def list_chats(
|
||||
user: dict = Depends(current_user),
|
||||
limit: int = Query(default=50, ge=1, le=100),
|
||||
cursor: Optional[str] = Query(default=None, min_length=1),
|
||||
):
|
||||
return await store.list_chats(uuid.UUID(user["id"]), limit, cursor)
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}", response_model=Chat)
|
||||
async def get_chat(chat_id: str, user: dict = Depends(current_user)):
|
||||
chat = await store.get_chat_for_member(parse_uuid(chat_id, "chat_id"), uuid.UUID(user["id"]))
|
||||
if chat is None:
|
||||
raise not_found()
|
||||
return chat
|
||||
|
||||
|
||||
@app.post("/api/v1/chats/{chat_id}/messages", response_model=Message, status_code=201)
|
||||
async def create_message(
|
||||
chat_id: str,
|
||||
body: CreateMessage,
|
||||
user: dict = Depends(current_user),
|
||||
idempotency_key: Optional[str] = Header(default=None, alias="Idempotency-Key"),
|
||||
):
|
||||
chat_uuid = parse_uuid(chat_id, "chat_id")
|
||||
if idempotency_key is None or not IDEMPOTENCY_KEY_RE.fullmatch(idempotency_key):
|
||||
raise ApiError(400, "invalid_request", "Idempotency-Key header is required: [A-Za-z0-9._:-]{1,128}")
|
||||
if len(set(body.attachment_ids)) != len(body.attachment_ids):
|
||||
raise ApiError(400, "invalid_request", "attachment_ids must be unique")
|
||||
if not body.text.strip() and not body.attachment_ids:
|
||||
if not await store.is_member(chat_uuid, uuid.UUID(user["id"])):
|
||||
raise not_found()
|
||||
raise ApiError(400, "invalid_request", "text must not be blank without attachments")
|
||||
canonical = json.dumps(body.model_dump(mode="json"), sort_keys=True, separators=(",", ":"), ensure_ascii=False)
|
||||
request_hash = hashlib.sha256(canonical.encode("utf-8")).digest()
|
||||
message = await store.create_message(
|
||||
chat_uuid, uuid.UUID(user["id"]), body.text, list(body.attachment_ids), idempotency_key, request_hash)
|
||||
if message is None:
|
||||
raise not_found()
|
||||
return message
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}/messages", response_model=MessagePage)
|
||||
async def list_messages(
|
||||
chat_id: str,
|
||||
user: dict = Depends(current_user),
|
||||
limit: int = Query(default=50, ge=1, le=100),
|
||||
cursor: Optional[str] = Query(default=None, min_length=1),
|
||||
):
|
||||
chat_uuid = parse_uuid(chat_id, "chat_id")
|
||||
if not await store.is_member(chat_uuid, uuid.UUID(user["id"])):
|
||||
raise not_found()
|
||||
return await store.list_messages(chat_uuid, limit, cursor)
|
||||
|
||||
|
||||
VARIANTS = {"original", "thumbnail", "crop", "optimized"}
|
||||
|
||||
|
||||
async def receive_body(request: Request, spool) -> tuple:
|
||||
"""Stream the body into a spooled temp file: RAM holds at most UPLOAD_SPOOL_BYTES per upload."""
|
||||
digest = hashlib.sha256()
|
||||
size = 0
|
||||
head = b""
|
||||
async for chunk in request.stream():
|
||||
size += len(chunk)
|
||||
if size > config.MAX_UPLOAD_BYTES:
|
||||
raise payload_too_large("file exceeds %d bytes" % config.MAX_UPLOAD_BYTES)
|
||||
if len(head) < images.SNIFF_BYTES:
|
||||
head += chunk[:images.SNIFF_BYTES - len(head)]
|
||||
digest.update(chunk)
|
||||
spool.write(chunk)
|
||||
return size, digest.hexdigest(), head
|
||||
|
||||
|
||||
@app.post("/api/v1/chats/{chat_id}/attachments", response_model=Attachment, status_code=201)
|
||||
async def upload_attachment(
|
||||
chat_id: str,
|
||||
request: Request,
|
||||
user: dict = Depends(current_user),
|
||||
filename: Optional[str] = Query(default=None),
|
||||
):
|
||||
chat_uuid = parse_uuid(chat_id, "chat_id")
|
||||
owner_id = uuid.UUID(user["id"])
|
||||
if not await store.is_member(chat_uuid, owner_id):
|
||||
raise not_found()
|
||||
filename = images.validate_filename(filename)
|
||||
declared = images.declared_type(request.headers.get("Content-Type"))
|
||||
length = request.headers.get("Content-Length")
|
||||
if length is not None:
|
||||
if not length.isdigit():
|
||||
raise ApiError(400, "invalid_request", "invalid Content-Length")
|
||||
if int(length) > config.MAX_UPLOAD_BYTES:
|
||||
raise payload_too_large("file exceeds %d bytes" % config.MAX_UPLOAD_BYTES)
|
||||
|
||||
async with upload_slots:
|
||||
spool = tempfile.SpooledTemporaryFile(max_size=config.UPLOAD_SPOOL_BYTES, dir=config.UPLOAD_TMP_DIR)
|
||||
try:
|
||||
try:
|
||||
size, sha256, head = await asyncio.wait_for(receive_body(request, spool), config.UPLOAD_TIMEOUT_SECONDS)
|
||||
except asyncio.TimeoutError:
|
||||
raise ApiError(400, "invalid_request", "upload was not completed in time") from None
|
||||
except ClientDisconnect:
|
||||
logger.info("upload aborted by client after partial body; nothing stored")
|
||||
raise ApiError(400, "invalid_request", "upload interrupted") from None
|
||||
if size == 0:
|
||||
raise unsupported_media_type("empty body is not an image")
|
||||
detected = images.sniff(head)
|
||||
if detected is None:
|
||||
raise unsupported_media_type("content is neither PNG nor JPEG")
|
||||
if detected != declared:
|
||||
raise unsupported_media_type("content does not match Content-Type " + declared)
|
||||
async with decode_slots:
|
||||
width, height = await run_in_threadpool(images.inspect, spool, detected)
|
||||
|
||||
attachment_id = uuid.uuid4()
|
||||
key = ObjectStore.new_key(uuid.uuid4())
|
||||
# 1) intent row (invisible) -> 2) S3 PUT -> 3) mark ready. A crash leaves a pending row for the sweeper.
|
||||
if not await store.create_pending_attachment(
|
||||
attachment_id, chat_uuid, owner_id, filename, detected, size, sha256, width, height, key,
|
||||
):
|
||||
raise not_found()
|
||||
try:
|
||||
async with s3_put_slots:
|
||||
await objects.put(key, spool, size, detected, sha256)
|
||||
except S3Unavailable:
|
||||
await objects.delete_quietly(key)
|
||||
await store.delete_pending_attachment(attachment_id)
|
||||
raise
|
||||
try:
|
||||
ready = await store.mark_attachment_ready(attachment_id)
|
||||
except DB_UNAVAILABLE:
|
||||
await objects.delete_quietly(key)
|
||||
raise
|
||||
if ready is None:
|
||||
await objects.delete_quietly(key)
|
||||
raise storage_unavailable()
|
||||
return ready
|
||||
finally:
|
||||
spool.close()
|
||||
|
||||
|
||||
async def readable_attachment(attachment_id: str, user: dict):
|
||||
row = await store.get_attachment_for_member(parse_uuid(attachment_id, "attachment_id"), uuid.UUID(user["id"]))
|
||||
if row is None:
|
||||
raise ApiError(404, "not_found", "attachment not found")
|
||||
return row
|
||||
|
||||
|
||||
@app.get("/api/v1/attachments/{attachment_id}", response_model=Attachment)
|
||||
async def get_attachment(attachment_id: str, user: dict = Depends(current_user)):
|
||||
return attachment_row(await readable_attachment(attachment_id, user))
|
||||
|
||||
|
||||
@app.get("/api/v1/attachments/{attachment_id}/content")
|
||||
async def download_attachment(
|
||||
attachment_id: str,
|
||||
user: dict = Depends(current_user),
|
||||
variant: str = Query(default="original"),
|
||||
):
|
||||
if variant not in VARIANTS:
|
||||
raise ApiError(400, "invalid_request", "unknown variant")
|
||||
row = await readable_attachment(attachment_id, user)
|
||||
if variant != "original":
|
||||
raise ApiError(404, "not_found", "variant not found")
|
||||
chunks, length, close = await objects.open(row["object_key"])
|
||||
if length != row["size_bytes"]:
|
||||
close()
|
||||
logger.error("object size differs from metadata for attachment %s", row["id"])
|
||||
raise storage_unavailable()
|
||||
return StreamingResponse(
|
||||
chunks,
|
||||
media_type=row["content_type"],
|
||||
headers={
|
||||
"Content-Length": str(length),
|
||||
"Cache-Control": "private, no-store",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
},
|
||||
background=BackgroundTask(close),
|
||||
)
|
||||
@@ -0,0 +1,63 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import asyncpg
|
||||
|
||||
from app import config
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
|
||||
logger = logging.getLogger("migrate")
|
||||
|
||||
MIGRATIONS_DIR = Path(__file__).resolve().parents[1] / "migrations"
|
||||
LOCK_ID = 2026_0002
|
||||
|
||||
|
||||
async def connect_with_retry(attempts: int = 30) -> asyncpg.Connection:
|
||||
for attempt in range(1, attempts + 1):
|
||||
try:
|
||||
return await asyncpg.connect(config.DATABASE_URL, timeout=config.DB_CONNECT_TIMEOUT)
|
||||
except (OSError, asyncpg.PostgresError, asyncpg.InterfaceError) as exc:
|
||||
logger.warning("database not reachable (attempt %d/%d): %s", attempt, attempts, type(exc).__name__)
|
||||
await asyncio.sleep(1)
|
||||
raise SystemExit("database is not reachable")
|
||||
|
||||
|
||||
async def migrate() -> int:
|
||||
if not config.DATABASE_URL:
|
||||
raise SystemExit("DATABASE_URL or DATABASE_URL_FILE is required")
|
||||
conn = await connect_with_retry()
|
||||
applied_now = 0
|
||||
try:
|
||||
await conn.execute("SELECT pg_advisory_lock($1)", LOCK_ID)
|
||||
await conn.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version text PRIMARY KEY,
|
||||
applied_at timestamptz NOT NULL DEFAULT now()
|
||||
)
|
||||
"""
|
||||
)
|
||||
done = {r["version"] for r in await conn.fetch("SELECT version FROM schema_migrations")}
|
||||
for path in sorted(MIGRATIONS_DIR.glob("*.sql")):
|
||||
version = path.stem
|
||||
if version in done:
|
||||
continue
|
||||
logger.info("applying %s", version)
|
||||
async with conn.transaction():
|
||||
await conn.execute(path.read_text(encoding="utf-8"))
|
||||
await conn.execute("INSERT INTO schema_migrations (version) VALUES ($1)", version)
|
||||
applied_now += 1
|
||||
logger.info("migrations up to date: %d applied now, %d before", applied_now, len(done))
|
||||
finally:
|
||||
await conn.execute("SELECT pg_advisory_unlock($1)", LOCK_ID)
|
||||
await conn.close()
|
||||
return applied_now
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(migrate())
|
||||
sys.exit(0)
|
||||
@@ -0,0 +1,98 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from typing import List, Optional
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
USERNAME_PATTERN = r"^[a-z0-9_]{3,32}$"
|
||||
|
||||
|
||||
class CreateUser(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
username: str = Field(pattern=USERNAME_PATTERN)
|
||||
display_name: str = Field(min_length=1, max_length=100)
|
||||
password: str = Field(min_length=12, max_length=128)
|
||||
|
||||
|
||||
class User(BaseModel):
|
||||
id: uuid.UUID
|
||||
username: str
|
||||
display_name: str
|
||||
created_at: str
|
||||
|
||||
|
||||
class CreateChat(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
title: str = Field(min_length=1, max_length=100)
|
||||
member_ids: List[uuid.UUID] = Field(min_length=1, max_length=100)
|
||||
|
||||
|
||||
class Chat(BaseModel):
|
||||
id: uuid.UUID
|
||||
title: str
|
||||
member_ids: List[uuid.UUID]
|
||||
created_at: str
|
||||
|
||||
|
||||
class ChatPage(BaseModel):
|
||||
items: List[Chat]
|
||||
next_cursor: Optional[str] = None
|
||||
|
||||
|
||||
class CreateMessage(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
text: str = Field(max_length=4000)
|
||||
attachment_ids: List[uuid.UUID] = Field(default_factory=list, max_length=10)
|
||||
|
||||
|
||||
class Message(BaseModel):
|
||||
id: uuid.UUID
|
||||
chat_id: uuid.UUID
|
||||
sender_id: uuid.UUID
|
||||
text: str
|
||||
created_at: str
|
||||
attachment_ids: List[uuid.UUID]
|
||||
|
||||
|
||||
class MessagePage(BaseModel):
|
||||
items: List[Message]
|
||||
next_cursor: Optional[str] = None
|
||||
|
||||
|
||||
class Session(BaseModel):
|
||||
token: str
|
||||
token_type: str = "Bearer"
|
||||
expires_at: str
|
||||
user: User
|
||||
|
||||
|
||||
class Variant(BaseModel):
|
||||
name: str
|
||||
content_type: str
|
||||
size_bytes: int
|
||||
width: int
|
||||
height: int
|
||||
sha256: str
|
||||
|
||||
|
||||
class Attachment(BaseModel):
|
||||
id: uuid.UUID
|
||||
chat_id: uuid.UUID
|
||||
owner_id: uuid.UUID
|
||||
filename: str
|
||||
content_type: str
|
||||
size_bytes: int
|
||||
sha256: str
|
||||
status: str
|
||||
variants: List[Variant]
|
||||
error_code: Optional[str]
|
||||
created_at: str
|
||||
updated_at: str
|
||||
|
||||
|
||||
class Health(BaseModel):
|
||||
status: str = "ok"
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from typing import BinaryIO, Callable, Iterator, List, Optional, Tuple
|
||||
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
|
||||
from app import config
|
||||
from app.errors import ApiError
|
||||
|
||||
logger = logging.getLogger("messenger.s3")
|
||||
|
||||
ORIGINALS_PREFIX = "originals/"
|
||||
DOWNLOAD_CHUNK = 64 * 1024
|
||||
|
||||
|
||||
class S3Unavailable(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def _client(access_key: Optional[str], secret_key: Optional[str]):
|
||||
cfg = Config(
|
||||
signature_version="s3v4",
|
||||
s3={"addressing_style": "path"},
|
||||
connect_timeout=config.S3_CONNECT_TIMEOUT,
|
||||
read_timeout=config.S3_READ_TIMEOUT,
|
||||
retries={"max_attempts": 1, "mode": "standard"},
|
||||
max_pool_connections=config.S3_POOL_MAX,
|
||||
request_checksum_calculation="when_required",
|
||||
response_checksum_validation="when_required",
|
||||
)
|
||||
return boto3.session.Session().client(
|
||||
"s3",
|
||||
endpoint_url=config.S3_ENDPOINT,
|
||||
region_name=config.S3_REGION,
|
||||
aws_access_key_id=access_key,
|
||||
aws_secret_access_key=secret_key,
|
||||
config=cfg,
|
||||
)
|
||||
|
||||
|
||||
def _code(exc: ClientError) -> str:
|
||||
return exc.response.get("Error", {}).get("Code", "")
|
||||
|
||||
|
||||
class ObjectStore:
|
||||
"""Synchronous boto3 client; async wrappers run it in the threadpool."""
|
||||
|
||||
def __init__(self, access_key: Optional[str] = None, secret_key: Optional[str] = None):
|
||||
self.bucket = config.S3_BUCKET
|
||||
self._s3 = _client(access_key or config.S3_ACCESS_KEY_ID, secret_key or config.S3_SECRET_ACCESS_KEY)
|
||||
|
||||
@staticmethod
|
||||
def new_key(attachment_id) -> str:
|
||||
return ORIGINALS_PREFIX + attachment_id.hex
|
||||
|
||||
def _put(self, key: str, fileobj: BinaryIO, size: int, content_type: str, sha256_hex: str) -> None:
|
||||
fileobj.seek(0)
|
||||
try:
|
||||
self._s3.put_object(
|
||||
Bucket=self.bucket,
|
||||
Key=key,
|
||||
Body=fileobj,
|
||||
ContentLength=size,
|
||||
ContentType=content_type,
|
||||
ChecksumSHA256=base64.b64encode(bytes.fromhex(sha256_hex)).decode("ascii"),
|
||||
)
|
||||
except (BotoCoreError, ClientError) as exc:
|
||||
logger.warning("s3 put failed: %s %s", type(exc).__name__, _code(exc) if isinstance(exc, ClientError) else "")
|
||||
raise S3Unavailable() from None
|
||||
|
||||
async def put(self, key: str, fileobj: BinaryIO, size: int, content_type: str, sha256_hex: str) -> None:
|
||||
await run_in_threadpool(self._put, key, fileobj, size, content_type, sha256_hex)
|
||||
|
||||
def _open(self, key: str):
|
||||
try:
|
||||
return self._s3.get_object(Bucket=self.bucket, Key=key)
|
||||
except ClientError as exc:
|
||||
logger.error("s3 get failed for existing metadata: %s", _code(exc))
|
||||
raise S3Unavailable() from None
|
||||
except BotoCoreError as exc:
|
||||
logger.warning("s3 get failed: %s", type(exc).__name__)
|
||||
raise S3Unavailable() from None
|
||||
|
||||
async def open(self, key: str) -> Tuple[Iterator[bytes], int, Callable[[], None]]:
|
||||
obj = await run_in_threadpool(self._open, key)
|
||||
body = obj["Body"]
|
||||
return body.iter_chunks(DOWNLOAD_CHUNK), int(obj["ContentLength"]), body.close
|
||||
|
||||
def delete_sync(self, key: str) -> None:
|
||||
try:
|
||||
self._s3.delete_object(Bucket=self.bucket, Key=key)
|
||||
except (BotoCoreError, ClientError) as exc:
|
||||
raise S3Unavailable() from exc
|
||||
|
||||
async def delete_quietly(self, key: str) -> bool:
|
||||
try:
|
||||
await run_in_threadpool(self.delete_sync, key)
|
||||
return True
|
||||
except S3Unavailable:
|
||||
logger.warning("compensating delete failed; sweeper will retry later")
|
||||
return False
|
||||
|
||||
def list_originals(self) -> Iterator[Tuple[str, datetime]]:
|
||||
paginator = self._s3.get_paginator("list_objects_v2")
|
||||
try:
|
||||
for page in paginator.paginate(Bucket=self.bucket, Prefix=ORIGINALS_PREFIX, PaginationConfig={"PageSize": 1000}):
|
||||
for item in page.get("Contents", []):
|
||||
yield item["Key"], item["LastModified"]
|
||||
except (BotoCoreError, ClientError) as exc:
|
||||
raise S3Unavailable() from exc
|
||||
|
||||
def delete_many(self, keys: List[str]) -> int:
|
||||
deleted = 0
|
||||
for i in range(0, len(keys), 1000):
|
||||
batch = keys[i:i + 1000]
|
||||
try:
|
||||
out = self._s3.delete_objects(Bucket=self.bucket, Delete={"Objects": [{"Key": k} for k in batch], "Quiet": True})
|
||||
except (BotoCoreError, ClientError) as exc:
|
||||
raise S3Unavailable() from exc
|
||||
deleted += len(batch) - len(out.get("Errors", []))
|
||||
return deleted
|
||||
|
||||
def bucket_exists(self) -> bool:
|
||||
try:
|
||||
self._s3.head_bucket(Bucket=self.bucket)
|
||||
return True
|
||||
except ClientError as exc:
|
||||
if _code(exc) in ("404", "NoSuchBucket", "NotFound"):
|
||||
return False
|
||||
raise S3Unavailable() from exc
|
||||
except BotoCoreError as exc:
|
||||
raise S3Unavailable() from exc
|
||||
|
||||
def create_bucket(self) -> bool:
|
||||
try:
|
||||
self._s3.create_bucket(Bucket=self.bucket)
|
||||
return True
|
||||
except ClientError as exc:
|
||||
if _code(exc) in ("BucketAlreadyOwnedByYou", "BucketAlreadyExists"):
|
||||
return False
|
||||
raise
|
||||
|
||||
|
||||
def storage_unavailable() -> ApiError:
|
||||
return ApiError(503, "unavailable", "attachment storage temporarily unavailable")
|
||||
@@ -0,0 +1,76 @@
|
||||
"""Idempotent bucket bootstrap with the admin identity (the API identity cannot create buckets).
|
||||
|
||||
Checks afterwards that anonymous access to the bucket is denied, and warms up the write path: after a
|
||||
SeaweedFS restart the first PUT waits ~2.5 s for the volume topology, which a client with a short timeout
|
||||
would see as a failed upload. The API starts only after this one-shot service exits 0.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
|
||||
from app import config
|
||||
from app.config import _secret
|
||||
from app.objects import ObjectStore, S3Unavailable
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
|
||||
logger = logging.getLogger("s3-bootstrap")
|
||||
|
||||
|
||||
def anonymous_status(path: str) -> int:
|
||||
try:
|
||||
with urllib.request.urlopen(config.S3_ENDPOINT.rstrip("/") + path, timeout=3) as r:
|
||||
return r.status
|
||||
except urllib.error.HTTPError as exc:
|
||||
return exc.code
|
||||
|
||||
|
||||
def main() -> int:
|
||||
admin = ObjectStore(_secret("S3_ADMIN_ACCESS_KEY_ID"), _secret("S3_ADMIN_SECRET_ACCESS_KEY"))
|
||||
for attempt in range(1, 31):
|
||||
try:
|
||||
created = admin.create_bucket()
|
||||
break
|
||||
except (BotoCoreError, ClientError, S3Unavailable) as exc:
|
||||
logger.warning("s3 not ready (attempt %d/30): %s", attempt, type(exc).__name__)
|
||||
time.sleep(1)
|
||||
else:
|
||||
return 1
|
||||
logger.info("bucket %s %s", config.S3_BUCKET, "created" if created else "already exists")
|
||||
|
||||
for path in ("/" + config.S3_BUCKET, "/" + config.S3_BUCKET + "/originals/probe"):
|
||||
status = anonymous_status(path)
|
||||
if status not in (401, 403):
|
||||
logger.error("anonymous request %s returned %d: bucket is NOT private", path, status)
|
||||
return 1
|
||||
logger.info("anonymous list/get denied: bucket is private")
|
||||
|
||||
probe = "health/bootstrap-probe" # outside originals/, so the sweeper never looks at it
|
||||
for attempt in range(1, 31):
|
||||
started = time.monotonic()
|
||||
try:
|
||||
admin._s3.put_object(Bucket=admin.bucket, Key=probe, Body=io.BytesIO(b"probe"))
|
||||
admin._s3.get_object(Bucket=admin.bucket, Key=probe)["Body"].read()
|
||||
admin._s3.delete_object(Bucket=admin.bucket, Key=probe)
|
||||
except (BotoCoreError, ClientError) as exc:
|
||||
logger.warning("write probe failed (attempt %d/30): %s", attempt, type(exc).__name__)
|
||||
time.sleep(1)
|
||||
continue
|
||||
elapsed = time.monotonic() - started
|
||||
if elapsed < 0.5:
|
||||
logger.info("write path warm: put/get/delete probe %.3fs", elapsed)
|
||||
return 0
|
||||
logger.info("write probe slow (%.2fs), repeating", elapsed)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
os.umask(0o077)
|
||||
sys.exit(main())
|
||||
+407
@@ -0,0 +1,407 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from typing import List, Optional, Tuple
|
||||
|
||||
import asyncpg
|
||||
|
||||
from app import config
|
||||
from app.errors import ApiError
|
||||
|
||||
|
||||
def fmt_ts(value: datetime) -> str:
|
||||
return value.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
|
||||
|
||||
|
||||
def user_row(row: asyncpg.Record) -> dict:
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"username": row["username"],
|
||||
"display_name": row["display_name"],
|
||||
"created_at": fmt_ts(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
def chat_row(row: asyncpg.Record) -> dict:
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"title": row["title"],
|
||||
"member_ids": [str(m) for m in row["member_ids"]],
|
||||
"created_at": fmt_ts(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
def message_row(row: asyncpg.Record, attachment_ids: Optional[List[uuid.UUID]] = None) -> dict:
|
||||
if attachment_ids is None:
|
||||
attachment_ids = row["attachment_ids"]
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"chat_id": str(row["chat_id"]),
|
||||
"sender_id": str(row["sender_id"]),
|
||||
"text": row["text"],
|
||||
"created_at": fmt_ts(row["created_at"]),
|
||||
"attachment_ids": [str(a) for a in attachment_ids],
|
||||
}
|
||||
|
||||
|
||||
def attachment_row(row: asyncpg.Record) -> dict:
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"chat_id": str(row["chat_id"]),
|
||||
"owner_id": str(row["owner_id"]),
|
||||
"filename": row["filename"],
|
||||
"content_type": row["content_type"],
|
||||
"size_bytes": row["size_bytes"],
|
||||
"sha256": row["sha256"],
|
||||
"status": row["status"],
|
||||
"variants": [],
|
||||
"error_code": None,
|
||||
"created_at": fmt_ts(row["created_at"]),
|
||||
"updated_at": fmt_ts(row["updated_at"]),
|
||||
}
|
||||
|
||||
|
||||
ATTACHMENT_COLUMNS = "id, chat_id, owner_id, filename, content_type, size_bytes, sha256, status, object_key, created_at, updated_at"
|
||||
|
||||
|
||||
def encode_cursor(resource: str, created_at: str, item_id: str) -> str:
|
||||
payload = json.dumps({"r": resource, "t": created_at, "i": item_id}, separators=(",", ":"))
|
||||
return base64.urlsafe_b64encode(payload.encode("utf-8")).decode("ascii").rstrip("=")
|
||||
|
||||
|
||||
def decode_cursor(resource: str, cursor: str) -> Tuple[datetime, uuid.UUID]:
|
||||
try:
|
||||
padded = cursor + "=" * (-len(cursor) % 4)
|
||||
payload = json.loads(base64.urlsafe_b64decode(padded.encode("ascii")).decode("utf-8"))
|
||||
if payload.get("r") != resource:
|
||||
raise ValueError("cursor belongs to a different resource")
|
||||
created_at = datetime.fromisoformat(payload["t"].replace("Z", "+00:00"))
|
||||
if created_at.tzinfo is None:
|
||||
raise ValueError("cursor time has no timezone")
|
||||
return created_at, uuid.UUID(payload["i"])
|
||||
except Exception as exc:
|
||||
raise ApiError(400, "invalid_request", "invalid cursor") from exc
|
||||
|
||||
|
||||
def page_of(items: List[dict], resource: str, limit: int) -> dict:
|
||||
page = items[:limit]
|
||||
next_cursor = None
|
||||
if len(items) > limit:
|
||||
last = page[-1]
|
||||
next_cursor = encode_cursor(resource, last["created_at"], last["id"])
|
||||
return {"items": page, "next_cursor": next_cursor}
|
||||
|
||||
|
||||
class Store:
|
||||
def __init__(self):
|
||||
self.pool: Optional[asyncpg.Pool] = None
|
||||
|
||||
async def open(self) -> None:
|
||||
self.pool = await asyncpg.create_pool(
|
||||
config.DATABASE_URL,
|
||||
min_size=0,
|
||||
max_size=config.DB_POOL_MAX,
|
||||
timeout=config.DB_CONNECT_TIMEOUT,
|
||||
command_timeout=config.DB_COMMAND_TIMEOUT,
|
||||
max_inactive_connection_lifetime=60,
|
||||
)
|
||||
|
||||
async def close(self) -> None:
|
||||
if self.pool is not None:
|
||||
await self.pool.close()
|
||||
|
||||
def acquire(self):
|
||||
return self.pool.acquire(timeout=config.DB_ACQUIRE_TIMEOUT)
|
||||
|
||||
async def ping(self) -> bool:
|
||||
async with self.acquire() as conn:
|
||||
return await conn.fetchval("SELECT 1") == 1
|
||||
|
||||
|
||||
async def create_user(self, username: str, display_name: str, password_hash: str) -> dict:
|
||||
async with self.acquire() as conn:
|
||||
try:
|
||||
row = await conn.fetchrow(
|
||||
"""
|
||||
INSERT INTO users (id, username, display_name, password_hash)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING id, username, display_name, created_at
|
||||
""",
|
||||
uuid.uuid4(), username, display_name, password_hash,
|
||||
)
|
||||
except asyncpg.UniqueViolationError:
|
||||
raise ApiError(409, "conflict", "username already taken") from None
|
||||
return user_row(row)
|
||||
|
||||
async def get_credentials(self, username: str) -> Optional[asyncpg.Record]:
|
||||
async with self.acquire() as conn:
|
||||
return await conn.fetchrow(
|
||||
"SELECT id, username, display_name, created_at, password_hash FROM users WHERE username = $1",
|
||||
username,
|
||||
)
|
||||
|
||||
|
||||
async def create_session(self, token_hash: bytes, user_id: uuid.UUID, ttl_seconds: int) -> datetime:
|
||||
async with self.acquire() as conn:
|
||||
return await conn.fetchval(
|
||||
"""
|
||||
INSERT INTO sessions (token_hash, user_id, expires_at)
|
||||
VALUES ($1, $2, clock_timestamp() + make_interval(secs => $3))
|
||||
RETURNING expires_at
|
||||
""",
|
||||
token_hash, user_id, float(ttl_seconds),
|
||||
)
|
||||
|
||||
async def find_session(self, token_hash: bytes) -> Optional[asyncpg.Record]:
|
||||
async with self.acquire() as conn:
|
||||
return await conn.fetchrow(
|
||||
"""
|
||||
SELECT s.expires_at, u.id, u.username, u.display_name, u.created_at
|
||||
FROM sessions s JOIN users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = $1 AND s.revoked_at IS NULL AND s.expires_at > clock_timestamp()
|
||||
""",
|
||||
token_hash,
|
||||
)
|
||||
|
||||
async def revoke_session(self, token_hash: bytes) -> Optional[datetime]:
|
||||
async with self.acquire() as conn:
|
||||
return await conn.fetchval(
|
||||
"""
|
||||
UPDATE sessions SET revoked_at = clock_timestamp()
|
||||
WHERE token_hash = $1 AND revoked_at IS NULL AND expires_at > clock_timestamp()
|
||||
RETURNING expires_at
|
||||
""",
|
||||
token_hash,
|
||||
)
|
||||
|
||||
|
||||
async def create_chat(self, title: str, member_ids: List[uuid.UUID]) -> dict:
|
||||
chat_id = uuid.uuid4()
|
||||
async with self.acquire() as conn:
|
||||
try:
|
||||
async with conn.transaction():
|
||||
row = await conn.fetchrow(
|
||||
"INSERT INTO chats (id, title) VALUES ($1, $2) RETURNING id, title, created_at",
|
||||
chat_id, title,
|
||||
)
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO chat_members (chat_id, user_id, position)
|
||||
SELECT $1, m.user_id, m.ord - 1
|
||||
FROM unnest($2::uuid[]) WITH ORDINALITY AS m(user_id, ord)
|
||||
""",
|
||||
chat_id, member_ids,
|
||||
)
|
||||
except asyncpg.ForeignKeyViolationError:
|
||||
raise ApiError(400, "invalid_request", "unknown member in member_ids") from None
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"title": row["title"],
|
||||
"member_ids": [str(m) for m in member_ids],
|
||||
"created_at": fmt_ts(row["created_at"]),
|
||||
}
|
||||
|
||||
async def get_chat_for_member(self, chat_id: uuid.UUID, user_id: uuid.UUID) -> Optional[dict]:
|
||||
async with self.acquire() as conn:
|
||||
row = await conn.fetchrow(
|
||||
"""
|
||||
SELECT c.id, c.title, c.created_at,
|
||||
array_agg(m.user_id ORDER BY m.position) AS member_ids
|
||||
FROM chats c JOIN chat_members m ON m.chat_id = c.id
|
||||
WHERE c.id = $1
|
||||
AND EXISTS (SELECT 1 FROM chat_members me WHERE me.chat_id = c.id AND me.user_id = $2)
|
||||
GROUP BY c.id
|
||||
""",
|
||||
chat_id, user_id,
|
||||
)
|
||||
return chat_row(row) if row else None
|
||||
|
||||
async def list_chats(self, user_id: uuid.UUID, limit: int, cursor: Optional[str]) -> dict:
|
||||
after_t, after_i = decode_cursor("chats", cursor) if cursor else (None, None)
|
||||
async with self.acquire() as conn:
|
||||
rows = await conn.fetch(
|
||||
"""
|
||||
SELECT c.id, c.title, c.created_at,
|
||||
array_agg(m.user_id ORDER BY m.position) AS member_ids
|
||||
FROM chat_members me
|
||||
JOIN chats c ON c.id = me.chat_id
|
||||
JOIN chat_members m ON m.chat_id = c.id
|
||||
WHERE me.user_id = $1
|
||||
AND ($2::timestamptz IS NULL OR (c.created_at, c.id) > ($2, $3::uuid))
|
||||
GROUP BY c.id
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $4
|
||||
""",
|
||||
user_id, after_t, after_i, limit + 1,
|
||||
)
|
||||
return page_of([chat_row(r) for r in rows], "chats", limit)
|
||||
|
||||
async def is_member(self, chat_id: uuid.UUID, user_id: uuid.UUID) -> bool:
|
||||
async with self.acquire() as conn:
|
||||
return bool(await conn.fetchval(
|
||||
"SELECT EXISTS (SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2)",
|
||||
chat_id, user_id,
|
||||
))
|
||||
|
||||
|
||||
async def create_message(
|
||||
self, chat_id: uuid.UUID, sender_id: uuid.UUID, text: str, attachment_ids: List[uuid.UUID],
|
||||
key: str, request_hash: bytes,
|
||||
) -> Optional[dict]:
|
||||
async with self.acquire() as conn:
|
||||
for _ in range(3):
|
||||
try:
|
||||
async with conn.transaction():
|
||||
await conn.execute(
|
||||
"""
|
||||
DELETE FROM idempotency_keys
|
||||
WHERE user_id = $1 AND chat_id = $2 AND key = $3
|
||||
AND created_at < clock_timestamp() - make_interval(secs => $4)
|
||||
""",
|
||||
sender_id, chat_id, key, float(config.IDEMPOTENCY_TTL_SECONDS),
|
||||
)
|
||||
message_id = uuid.uuid4()
|
||||
claimed = await conn.fetchval(
|
||||
"""
|
||||
INSERT INTO idempotency_keys (user_id, chat_id, key, request_hash, message_id)
|
||||
SELECT $1, $2, $3, $4, $5
|
||||
WHERE EXISTS (SELECT 1 FROM chat_members WHERE chat_id = $2 AND user_id = $1)
|
||||
ON CONFLICT (user_id, chat_id, key) DO NOTHING
|
||||
RETURNING message_id
|
||||
""",
|
||||
sender_id, chat_id, key, request_hash, message_id,
|
||||
)
|
||||
if claimed is not None:
|
||||
if attachment_ids:
|
||||
ready = await conn.fetchval(
|
||||
"""
|
||||
SELECT count(*) FROM attachments
|
||||
WHERE id = ANY($1::uuid[]) AND chat_id = $2 AND status = 'ready'
|
||||
""",
|
||||
attachment_ids, chat_id,
|
||||
)
|
||||
if ready != len(attachment_ids):
|
||||
raise ApiError(404, "not_found", "attachment not found")
|
||||
row = await conn.fetchrow(
|
||||
"""
|
||||
INSERT INTO messages (id, chat_id, sender_id, text)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING id, chat_id, sender_id, text, created_at
|
||||
""",
|
||||
message_id, chat_id, sender_id, text,
|
||||
)
|
||||
if attachment_ids:
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO message_attachments (message_id, attachment_id, chat_id, position)
|
||||
SELECT $1, a.id, $2, a.ord - 1
|
||||
FROM unnest($3::uuid[]) WITH ORDINALITY AS a(id, ord)
|
||||
""",
|
||||
message_id, chat_id, attachment_ids,
|
||||
)
|
||||
return message_row(row, attachment_ids)
|
||||
except asyncpg.ForeignKeyViolationError:
|
||||
return None
|
||||
|
||||
existing = await conn.fetchrow(
|
||||
"""
|
||||
SELECT k.request_hash, m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
||||
ARRAY(SELECT ma.attachment_id FROM message_attachments ma WHERE ma.message_id = m.id ORDER BY ma.position) AS attachment_ids
|
||||
FROM idempotency_keys k
|
||||
JOIN messages m ON m.id = k.message_id
|
||||
JOIN chat_members cm ON cm.chat_id = k.chat_id AND cm.user_id = k.user_id
|
||||
WHERE k.user_id = $1 AND k.chat_id = $2 AND k.key = $3
|
||||
""",
|
||||
sender_id, chat_id, key,
|
||||
)
|
||||
if existing is None:
|
||||
is_member = await conn.fetchval(
|
||||
"SELECT EXISTS (SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2)",
|
||||
chat_id, sender_id,
|
||||
)
|
||||
if not is_member:
|
||||
return None
|
||||
continue
|
||||
if existing["request_hash"] != request_hash:
|
||||
raise ApiError(409, "conflict", "Idempotency-Key was already used with a different request")
|
||||
return message_row(existing)
|
||||
raise ApiError(503, "unavailable", "could not settle idempotent request, retry with the same key")
|
||||
|
||||
async def list_messages(self, chat_id: uuid.UUID, limit: int, cursor: Optional[str]) -> dict:
|
||||
resource = str(chat_id)
|
||||
async with self.acquire() as conn:
|
||||
if cursor:
|
||||
after_t, after_i = decode_cursor(resource, cursor)
|
||||
rows = await conn.fetch(
|
||||
"""
|
||||
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
||||
ARRAY(SELECT ma.attachment_id FROM message_attachments ma WHERE ma.message_id = m.id ORDER BY ma.position) AS attachment_ids
|
||||
FROM messages m
|
||||
WHERE m.chat_id = $1 AND (m.created_at, m.id) > ($2, $3)
|
||||
ORDER BY m.created_at, m.id
|
||||
LIMIT $4
|
||||
""",
|
||||
chat_id, after_t, after_i, limit + 1,
|
||||
)
|
||||
else:
|
||||
rows = await conn.fetch(
|
||||
"""
|
||||
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
||||
ARRAY(SELECT ma.attachment_id FROM message_attachments ma WHERE ma.message_id = m.id ORDER BY ma.position) AS attachment_ids
|
||||
FROM messages m
|
||||
WHERE m.chat_id = $1
|
||||
ORDER BY m.created_at, m.id
|
||||
LIMIT $2
|
||||
""",
|
||||
chat_id, limit + 1,
|
||||
)
|
||||
return page_of([message_row(r) for r in rows], resource, limit)
|
||||
|
||||
|
||||
async def create_pending_attachment(
|
||||
self, attachment_id: uuid.UUID, chat_id: uuid.UUID, owner_id: uuid.UUID, filename: str,
|
||||
content_type: str, size_bytes: int, sha256: str, width: int, height: int, object_key: str,
|
||||
) -> bool:
|
||||
async with self.acquire() as conn:
|
||||
try:
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes,
|
||||
sha256, width, height, object_key, status)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, 'pending')
|
||||
""",
|
||||
attachment_id, chat_id, owner_id, filename, content_type, size_bytes, sha256, width, height, object_key,
|
||||
)
|
||||
except asyncpg.ForeignKeyViolationError:
|
||||
return False
|
||||
return True
|
||||
|
||||
async def mark_attachment_ready(self, attachment_id: uuid.UUID) -> Optional[dict]:
|
||||
async with self.acquire() as conn:
|
||||
row = await conn.fetchrow(
|
||||
f"""
|
||||
UPDATE attachments SET status = 'ready', updated_at = clock_timestamp()
|
||||
WHERE id = $1 AND status = 'pending'
|
||||
RETURNING {ATTACHMENT_COLUMNS}
|
||||
""",
|
||||
attachment_id,
|
||||
)
|
||||
return attachment_row(row) if row else None
|
||||
|
||||
async def delete_pending_attachment(self, attachment_id: uuid.UUID) -> None:
|
||||
async with self.acquire() as conn:
|
||||
await conn.execute("DELETE FROM attachments WHERE id = $1 AND status = 'pending'", attachment_id)
|
||||
|
||||
async def get_attachment_for_member(self, attachment_id: uuid.UUID, user_id: uuid.UUID) -> Optional[asyncpg.Record]:
|
||||
async with self.acquire() as conn:
|
||||
return await conn.fetchrow(
|
||||
f"""
|
||||
SELECT {ATTACHMENT_COLUMNS} FROM attachments a
|
||||
WHERE a.id = $1 AND a.status = 'ready'
|
||||
AND EXISTS (SELECT 1 FROM chat_members m WHERE m.chat_id = a.chat_id AND m.user_id = $2)
|
||||
""",
|
||||
attachment_id, user_id,
|
||||
)
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
"""Cleanup of attachments that never became ready.
|
||||
|
||||
Invariant kept by the upload path: a metadata row (status=pending) is committed BEFORE the S3 PUT and
|
||||
switched to ready AFTER it. Therefore, after a crash/abort/failed COMMIT there can only be
|
||||
* a stale pending row (object may or may not exist), or
|
||||
* an object without any row (row already removed, compensating delete failed).
|
||||
Both are deleted only when older than ORPHAN_GRACE_SECONDS, far longer than any live upload
|
||||
(UPLOAD_TIMEOUT_SECONDS + S3 timeouts), so an in-flight upload is never touched. Ready rows and objects
|
||||
referenced by any row are never deleted. Every step is idempotent; repeating a run is safe.
|
||||
|
||||
python -m app.sweeper --once --dry-run # report only
|
||||
python -m app.sweeper --once # one real pass
|
||||
python -m app.sweeper # loop every SWEEP_INTERVAL_SECONDS
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import asyncpg
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
|
||||
from app import config
|
||||
from app.objects import ObjectStore, S3Unavailable
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
|
||||
logger = logging.getLogger("sweeper")
|
||||
|
||||
LOCK_ID = 2026_0004
|
||||
HEARTBEAT_FILE = "/tmp/sweeper-heartbeat"
|
||||
BATCH = 1000
|
||||
|
||||
|
||||
async def stale_pending(conn: asyncpg.Connection, grace: int):
|
||||
return await conn.fetch(
|
||||
"""
|
||||
SELECT id, object_key FROM attachments
|
||||
WHERE status = 'pending' AND created_at < clock_timestamp() - make_interval(secs => $1)
|
||||
ORDER BY created_at
|
||||
""",
|
||||
float(grace),
|
||||
)
|
||||
|
||||
|
||||
async def sweep(conn: asyncpg.Connection, objects: ObjectStore, grace: int, dry_run: bool) -> dict:
|
||||
started = time.monotonic()
|
||||
report = {"dry_run": dry_run, "grace_seconds": grace, "pending_found": 0, "pending_deleted": 0,
|
||||
"objects_scanned": 0, "orphans_found": 0, "orphans_deleted": 0, "orphan_keys_sample": []}
|
||||
|
||||
rows = await stale_pending(conn, grace)
|
||||
report["pending_found"] = len(rows)
|
||||
if not dry_run:
|
||||
for row in rows:
|
||||
# Object first, then the row: if we crash in between, the row remains and the next pass repeats.
|
||||
await run_in_threadpool(objects.delete_sync, row["object_key"])
|
||||
deleted = await conn.execute(
|
||||
"""
|
||||
DELETE FROM attachments
|
||||
WHERE id = $1 AND status = 'pending' AND created_at < clock_timestamp() - make_interval(secs => $2)
|
||||
""",
|
||||
row["id"], float(grace),
|
||||
)
|
||||
report["pending_deleted"] += int(deleted.split()[-1])
|
||||
|
||||
cutoff = datetime.now(timezone.utc) - timedelta(seconds=grace)
|
||||
|
||||
def old_keys():
|
||||
for key, modified in objects.list_originals():
|
||||
report["objects_scanned"] += 1
|
||||
if modified < cutoff:
|
||||
yield key
|
||||
|
||||
keys = await run_in_threadpool(lambda: list(old_keys()))
|
||||
for i in range(0, len(keys), BATCH):
|
||||
batch = keys[i:i + BATCH]
|
||||
known = {r["object_key"] for r in await conn.fetch(
|
||||
"SELECT object_key FROM attachments WHERE object_key = ANY($1::text[])", batch)}
|
||||
orphans = [k for k in batch if k not in known]
|
||||
report["orphans_found"] += len(orphans)
|
||||
report["orphan_keys_sample"].extend(orphans[:5 - len(report["orphan_keys_sample"])])
|
||||
if orphans and not dry_run:
|
||||
report["orphans_deleted"] += await run_in_threadpool(objects.delete_many, orphans)
|
||||
|
||||
report["duration_ms"] = round((time.monotonic() - started) * 1000, 1)
|
||||
return report
|
||||
|
||||
|
||||
async def run_once(grace: int, dry_run: bool) -> dict:
|
||||
conn = await asyncpg.connect(config.DATABASE_URL, timeout=config.DB_CONNECT_TIMEOUT)
|
||||
try:
|
||||
if not await conn.fetchval("SELECT pg_try_advisory_lock($1)", LOCK_ID):
|
||||
return {"skipped": "another sweeper holds the lock"}
|
||||
try:
|
||||
return await sweep(conn, ObjectStore(), grace, dry_run)
|
||||
finally:
|
||||
await conn.execute("SELECT pg_advisory_unlock($1)", LOCK_ID)
|
||||
finally:
|
||||
await conn.close()
|
||||
|
||||
|
||||
async def main() -> int:
|
||||
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
p.add_argument("--once", action="store_true")
|
||||
p.add_argument("--dry-run", action="store_true")
|
||||
p.add_argument("--grace", type=int, default=config.ORPHAN_GRACE_SECONDS)
|
||||
p.add_argument("--interval", type=int, default=config.SWEEP_INTERVAL_SECONDS)
|
||||
args = p.parse_args()
|
||||
if args.grace < 60:
|
||||
p.error("grace below 60 s could remove an upload that is still in progress")
|
||||
while True:
|
||||
try:
|
||||
report = await run_once(args.grace, args.dry_run)
|
||||
print(json.dumps(report, ensure_ascii=False), flush=True)
|
||||
with open(HEARTBEAT_FILE, "w", encoding="ascii") as fh:
|
||||
fh.write(str(time.time()))
|
||||
except (OSError, asyncpg.PostgresError, asyncpg.InterfaceError, S3Unavailable) as exc:
|
||||
logger.warning("sweep failed (%s); will retry", type(exc).__name__)
|
||||
if args.once:
|
||||
return 1
|
||||
if args.once:
|
||||
return 0
|
||||
await asyncio.sleep(args.interval)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(asyncio.run(main()))
|
||||
Reference in New Issue
Block a user