ЛР 4: вложения в S3 (MinIO), reconciler БД<->S3, отчёт и evidence

Перенесён минимум lab3. Добавлены загрузка/скачивание PNG/JPEG через API
с потоковой проверкой целостности, метаданные в PostgreSQL и байты в
приватном bucket, отдельный S3-пользователь с ограниченными правами,
идемпотентный bootstrap bucket, компенсация и reconciler (трек 2),
тесты отказов, эксперименты по памяти и согласованности.
This commit is contained in:
alenchha
2026-11-02 16:59:17 +03:00
parent ec540a1a72
commit 078a8341b5
50 changed files with 3320 additions and 24 deletions
View File
+64
View File
@@ -0,0 +1,64 @@
import os
import socket
def _int(name, default):
value = os.environ.get(name)
return int(value) if value not in (None, "") else default
def _float(name, default):
value = os.environ.get(name)
return float(value) if value not in (None, "") else default
def _secret(name, default=""):
path = os.environ.get(name + "_FILE")
if path:
with open(path, encoding="utf-8") as handle:
return handle.read().strip()
return os.environ.get(name, default)
DATABASE_URL = _secret("DATABASE_URL")
CACHE_URL = _secret("CACHE_URL")
SESSION_STORE = os.environ.get("SESSION_STORE", "postgres")
SESSION_TTL_SECONDS = _int("SESSION_TTL_SECONDS", 3600)
SESSION_CACHE_TTL_SECONDS = _int("SESSION_CACHE_TTL_SECONDS", 30)
SESSION_SWEEP_SECONDS = _int("SESSION_SWEEP_SECONDS", 60)
DB_POOL_MIN = _int("DB_POOL_MIN", 1)
DB_POOL_MAX = _int("DB_POOL_MAX", 10)
DB_POOL_TIMEOUT = _float("DB_POOL_TIMEOUT", 3.0)
DB_CONNECT_TIMEOUT = _int("DB_CONNECT_TIMEOUT", 3)
DB_STATEMENT_TIMEOUT_MS = _int("DB_STATEMENT_TIMEOUT_MS", 5000)
DB_OP_TIMEOUT = _float("DB_OP_TIMEOUT", 6.0)
REQUEST_TIMEOUT = _float("REQUEST_TIMEOUT", 8.0)
DB_READY_TIMEOUT = _float("DB_READY_TIMEOUT", 1.5)
READY_CHECK_SECONDS = _float("READY_CHECK_SECONDS", 1.0)
READY_FAILURES = _int("READY_FAILURES", 2)
CACHE_TIMEOUT = _float("CACHE_TIMEOUT", 0.2)
MAX_INFLIGHT_REQUESTS = _int("MAX_INFLIGHT_REQUESTS", 64)
MAX_BODY_BYTES = _int("MAX_BODY_BYTES", 65536)
MAX_RSS_MB = _int("MAX_RSS_MB", 0)
PASSWORD_MIN = 12
PASSWORD_MAX = 128
SESSION_REVOKED_TTL_SECONDS = max(
_int("SESSION_REVOKED_TTL_SECONDS", 60),
SESSION_CACHE_TTL_SECONDS + int(REQUEST_TIMEOUT) + 5,
)
INSTANCE_ID = os.environ.get("INSTANCE_ID") or socket.gethostname()
IDEMPOTENCY_TTL_SECONDS = _int("IDEMPOTENCY_TTL_SECONDS", 86400)
S3_ENDPOINT = os.environ.get("S3_ENDPOINT", "http://s3:9000")
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")
MAX_UPLOAD_BYTES = _int("MAX_UPLOAD_BYTES", 10485760)
MAX_IMAGE_PIXELS = _int("MAX_IMAGE_PIXELS", 40000000)
S3_CONNECT_TIMEOUT = _float("S3_CONNECT_TIMEOUT", 3.0)
S3_READ_TIMEOUT = _float("S3_READ_TIMEOUT", 6.0)
UPLOAD_SPOOL_BYTES = _int("UPLOAD_SPOOL_BYTES", 1048576)
RECONCILE_INTERVAL_SECONDS = _int("RECONCILE_INTERVAL_SECONDS", 300)
RECONCILE_GRACE_SECONDS = _int("RECONCILE_GRACE_SECONDS", 900)
UPLOAD_CONCURRENCY = _int("UPLOAD_CONCURRENCY", 2)
+43
View File
@@ -0,0 +1,43 @@
import base64
import json
import re
import uuid
from datetime import datetime, timezone
TS_RE = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z")
TS_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ"
class BadCursor(Exception):
pass
def fmt(ts: datetime) -> str:
return ts.astimezone(timezone.utc).strftime(TS_FORMAT)
def encode_cursor(scope: str, created_at: str, item_id: str) -> str:
raw = json.dumps({"s": scope, "t": created_at, "i": item_id}, separators=(",", ":")).encode()
return base64.urlsafe_b64encode(raw).decode().rstrip("=")
def decode_cursor(scope: str, cursor: str):
try:
raw = base64.urlsafe_b64decode(cursor + "=" * (-len(cursor) % 4))
data = json.loads(raw)
except Exception:
raise BadCursor() from None
if not isinstance(data, dict) or set(data) != {"s", "t", "i"} or data["s"] != scope:
raise BadCursor()
ts, item_id = data["t"], data["i"]
if not isinstance(ts, str) or not TS_RE.fullmatch(ts) or not isinstance(item_id, str):
raise BadCursor()
try:
parsed = datetime.strptime(ts, TS_FORMAT).replace(tzinfo=timezone.utc)
if str(uuid.UUID(item_id)) != item_id:
raise BadCursor()
except ValueError:
raise BadCursor() from None
if encode_cursor(scope, ts, item_id) != cursor:
raise BadCursor()
return parsed, item_id
+99
View File
@@ -0,0 +1,99 @@
import asyncio
from contextlib import asynccontextmanager
import psycopg
from psycopg.rows import dict_row
from psycopg_pool import AsyncConnectionPool, PoolTimeout
from app import config
from app.errors import unavailable
BROKEN = (psycopg.OperationalError, psycopg.InterfaceError, PoolTimeout)
async def discard(conn) -> None:
try:
await conn.close()
except Exception:
pass
class Guarded:
def __init__(self, conn, timeout: float):
self.conn = conn
self.timeout = timeout
async def execute(self, *args, **kwargs):
try:
return await asyncio.wait_for(self.conn.execute(*args, **kwargs), self.timeout)
except asyncio.TimeoutError:
await discard(self.conn)
raise unavailable("Хранилище не ответило за отведённое время") from None
def transaction(self):
return self.conn.transaction()
class Database:
def __init__(self) -> None:
options = "-c statement_timeout=%d -c lock_timeout=%d -c idle_in_transaction_session_timeout=%d" % (
config.DB_STATEMENT_TIMEOUT_MS,
config.DB_STATEMENT_TIMEOUT_MS,
config.DB_STATEMENT_TIMEOUT_MS * 2,
)
self.pool = AsyncConnectionPool(
conninfo=config.DATABASE_URL,
min_size=config.DB_POOL_MIN,
max_size=config.DB_POOL_MAX,
timeout=config.DB_POOL_TIMEOUT,
max_lifetime=600.0,
open=False,
kwargs={
"autocommit": True,
"row_factory": dict_row,
"connect_timeout": config.DB_CONNECT_TIMEOUT,
"options": options,
},
)
async def open(self) -> None:
await self.pool.open(wait=False)
async def close(self) -> None:
await self.pool.close()
@asynccontextmanager
async def connection(self):
try:
async with self.pool.connection(timeout=config.DB_POOL_TIMEOUT) as conn:
yield Guarded(conn, config.DB_OP_TIMEOUT)
except BROKEN:
raise unavailable("Хранилище недоступно") from None
@asynccontextmanager
async def transaction(self):
async with self.connection() as conn:
async with conn.transaction():
yield conn
async def in_transaction(self, action):
async def run():
async with self.transaction() as conn:
return await action(conn)
try:
return await asyncio.wait_for(run(), config.DB_OP_TIMEOUT)
except asyncio.TimeoutError:
raise unavailable("Хранилище не ответило за отведённое время") from None
async def ready(self) -> bool:
try:
async with self.pool.connection(timeout=config.DB_READY_TIMEOUT) as conn:
try:
await asyncio.wait_for(conn.execute("SELECT 1"), config.DB_READY_TIMEOUT)
except asyncio.TimeoutError:
await discard(conn)
return False
return True
except Exception:
return False
+37
View File
@@ -0,0 +1,37 @@
from typing import Optional
from fastapi.responses import JSONResponse
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
BEARER_CHALLENGE = 'Bearer realm="messenger"'
class ApiError(Exception):
def __init__(self, status: int, code: str, message: str, headers: Optional[dict] = None):
self.status, self.code, self.message, self.headers = status, code, message, headers or {}
def bad(message: str) -> ApiError:
return ApiError(400, "invalid_request", message)
def unauthorized(scheme: str = "Bearer") -> ApiError:
challenge = BASIC_CHALLENGE if scheme == "Basic" else BEARER_CHALLENGE
message = "Нужны имя пользователя и пароль" if scheme == "Basic" else "Нужна действующая сессия"
return ApiError(401, "unauthorized", message, {"WWW-Authenticate": challenge})
def not_found() -> ApiError:
return ApiError(404, "not_found", "Объект не найден")
def unavailable(message: str) -> ApiError:
return ApiError(503, "unavailable", message, {"Retry-After": "1"})
def error_body(rid: str, instance: str, status: int, code: str, message: str, headers: Optional[dict] = None) -> JSONResponse:
return JSONResponse(
status_code=status,
content={"error": {"code": code, "message": message, "request_id": rid}},
headers={"X-Request-Id": rid, "X-Instance-Id": instance, **(headers or {})},
)
+192
View File
@@ -0,0 +1,192 @@
"""Integrity checks for uploaded PNG/JPEG with bounded memory.
PNG: own streaming scanner (chunk CRCs, IHDR rules, zlib stream decoded 1 MiB at a time, every row filter byte in
0..4, decoded size equal to the size implied by IHDR, IEND present). JPEG: libjpeg decodes the whole entropy
stream through Pillow in 1/8 scale, so memory stays at ~1/64 of the image. Both finish before anything is stored.
"""
import struct
import time
import zlib
from PIL import Image
from app import config
from app.errors import ApiError
PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
VALID_DEPTHS = {0: (1, 2, 4, 8, 16), 2: (8, 16), 3: (1, 2, 4, 8), 4: (8, 16), 6: (8, 16)}
CHANNELS = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}
ADAM7 = ((0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4, 4), (0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2))
Image.MAX_IMAGE_PIXELS = None
FORMATS = {"image/png": "PNG", "image/jpeg": "JPEG"}
FULL_DECODE_MAX_PIXELS = 4000000
SCAN_SECONDS = 10.0
OUT_STEP = 1 << 20
class Invalid(Exception):
pass
def invalid() -> ApiError:
return ApiError(415, "unsupported_media_type", "Файл не является корректным PNG/JPEG")
class RowPlan:
def __init__(self, segments):
self.segments = [s for s in segments if s[0] > 1 and s[1] > 0]
self.seg = 0
self.done = 0
self.pos = 0
def feed(self, data: bytes) -> None:
i, n = 0, len(data)
while i < n:
while self.seg < len(self.segments) and self.done == self.segments[self.seg][1]:
self.seg += 1
self.done = 0
if self.seg >= len(self.segments):
raise Invalid("data after the last row")
length, rows = self.segments[self.seg]
if self.pos > 0:
take = min(length - self.pos, n - i)
i += take
self.pos += take
if self.pos == length:
self.pos = 0
self.done += 1
continue
full = min((n - i) // length, rows - self.done)
if full > 0:
if max(data[i:i + full * length:length]) > 4:
raise Invalid("bad filter type")
i += full * length
self.done += full
else:
if data[i] > 4:
raise Invalid("bad filter type")
self.pos = n - i
i = n
def complete(self) -> bool:
while self.seg < len(self.segments) and self.done == self.segments[self.seg][1]:
self.seg += 1
self.done = 0
return self.seg >= len(self.segments) and self.pos == 0
def png_plan(width, height, depth, color, interlace):
bits = CHANNELS[color] * depth
if not interlace:
return RowPlan([(1 + (width * bits + 7) // 8, height)])
segments = []
for x0, y0, dx, dy in ADAM7:
w = (width - x0 + dx - 1) // dx if width > x0 else 0
h = (height - y0 + dy - 1) // dy if height > y0 else 0
if w and h:
segments.append((1 + (w * bits + 7) // 8, h))
return RowPlan(segments)
def scan_png(fileobj) -> None:
deadline = time.monotonic() + SCAN_SECONDS
fileobj.seek(0)
if fileobj.read(8) != PNG_SIGNATURE:
raise Invalid("signature")
plan = decomp = None
palette = seen_idat = idat_closed = False
color = None
first = True
while True:
if time.monotonic() > deadline:
raise Invalid("scan too slow")
head = fileobj.read(8)
if len(head) < 8:
raise Invalid("truncated before IEND")
length, kind = struct.unpack(">I4s", head)
if length > 0x7FFFFFFF:
raise Invalid("chunk length")
if first and kind != b"IHDR":
raise Invalid("IHDR must be first")
crc = zlib.crc32(kind)
if kind == b"IHDR":
body = fileobj.read(length)
if not first or length != 13 or len(body) != 13:
raise Invalid("IHDR")
width, height, depth, color, comp, filt, interlace = struct.unpack(">IIBBBBB", body)
if not (0 < width <= 0x7FFFFFFF and 0 < height <= 0x7FFFFFFF) or comp or filt or interlace not in (0, 1):
raise Invalid("IHDR fields")
if color not in VALID_DEPTHS or depth not in VALID_DEPTHS[color]:
raise Invalid("color type / depth")
plan = png_plan(width, height, depth, color, interlace)
decomp = zlib.decompressobj()
crc = zlib.crc32(body, crc)
else:
remaining = length
while remaining:
buf = fileobj.read(min(remaining, 65536))
if not buf:
raise Invalid("truncated chunk")
remaining -= len(buf)
crc = zlib.crc32(buf, crc)
if kind == b"IDAT":
if idat_closed or (color == 3 and not palette):
raise Invalid("IDAT order")
seen_idat = True
out = decomp.decompress(buf, OUT_STEP)
while True:
plan.feed(out)
if not decomp.unconsumed_tail:
break
if time.monotonic() > deadline:
raise Invalid("scan too slow")
out = decomp.decompress(decomp.unconsumed_tail, OUT_STEP)
if kind == b"PLTE":
palette = True
if color in (0, 4) or length % 3 or not 3 <= length <= 768:
raise Invalid("PLTE")
elif kind != b"IDAT" and seen_idat:
idat_closed = True
tail = fileobj.read(4)
if len(tail) < 4 or struct.unpack(">I", tail)[0] != crc & 0xFFFFFFFF:
raise Invalid("crc")
first = False
if kind == b"IEND":
if length or not seen_idat:
raise Invalid("IEND")
break
if not decomp.eof or decomp.unused_data or not plan.complete():
raise Invalid("pixel data does not match IHDR")
def inspect_image(fileobj, size: int, content_type: str) -> None:
"""Raises ApiError 413 (too many pixels) or 415 (not a decodable image of the declared type)."""
try:
fileobj.seek(0)
img = Image.open(fileobj)
width, height = img.size
if img.format != FORMATS[content_type]:
raise invalid()
if width * height > config.MAX_IMAGE_PIXELS:
raise ApiError(413, "payload_too_large", "Изображение превышает 40 млн пикселей")
small = width * height <= FULL_DECODE_MAX_PIXELS
if content_type == "image/png":
scan_png(fileobj)
else:
fileobj.seek(max(0, size - 1024))
if b"\xff\xd9" not in fileobj.read():
raise invalid()
if not small:
fileobj.seek(0)
scaled = Image.open(fileobj)
scaled.draft(scaled.mode, (1, 1))
scaled.load()
if small:
fileobj.seek(0)
Image.open(fileobj).load()
except ApiError:
raise
except Exception:
raise invalid() from None
finally:
fileobj.seek(0)
+640
View File
@@ -0,0 +1,640 @@
import asyncio
import base64
import binascii
import hashlib
import json
import logging
import os
import re
import resource
import signal
import tempfile
import unicodedata
import sys
import uuid
from contextlib import asynccontextmanager
from typing import List, Optional, Tuple
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse, Response
from starlette.concurrency import iterate_in_threadpool, run_in_threadpool
from starlette.responses import StreamingResponse
from app import config, passwords, reconcile, repo
from app.cursor import BadCursor, decode_cursor, encode_cursor
from app.db import Database
from app.imagecheck import inspect_image
from app.errors import ApiError, bad, error_body, not_found, unauthorized, unavailable
from app.s3 import S3Storage
from app.sessions import SessionStore
logging.basicConfig(stream=sys.stdout, level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
log = logging.getLogger("messenger")
USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$")
IDEMPOTENCY_KEY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
ZERO_WIDTH = str.maketrans({char: None for char in "​‌‍⁠"})
EXEMPT_PATHS = ("/health/live", "/health/ready")
PAGE_SIZE = os.sysconf("SC_PAGE_SIZE") if hasattr(os, "sysconf") else 4096
ALLOWED_CONTENT_TYPES = {"image/png", "image/jpeg"}
PNG_MAGIC = b"\x89PNG\r\n\x1a\n"
JPEG_MAGIC = b"\xff\xd8\xff"
upload_slots = asyncio.Semaphore(config.UPLOAD_CONCURRENCY)
background = set()
db = Database()
sessions = SessionStore(db)
s3 = S3Storage()
state = {"draining": False, "ready": True, "s3_ok": False, "inflight": 0, "rejected": {}}
def rss_mb() -> float:
try:
with open("/proc/self/statm") as handle:
return int(handle.read().split()[1]) * PAGE_SIZE / 1048576
except OSError:
peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
return peak / 1048576 if sys.platform == "darwin" else peak / 1024
def count_rejection(code: str) -> None:
state["rejected"][code] = state["rejected"].get(code, 0) + 1
async def sweeper() -> None:
while True:
await asyncio.sleep(config.SESSION_SWEEP_SECONDS)
try:
removed = await sessions.sweep()
if removed:
log.info("sessions_expired removed=%d", removed)
except Exception:
log.warning("session sweep skipped: storage unavailable")
try:
async with db.connection() as conn:
removed = await repo.cleanup_idempotency(conn, config.IDEMPOTENCY_TTL_SECONDS)
if removed:
log.info("idempotency_cleanup removed=%d", removed)
except Exception:
log.warning("idempotency cleanup skipped")
async def reconciler_loop() -> None:
await asyncio.sleep(config.RECONCILE_INTERVAL_SECONDS)
while True:
try:
result = await reconcile.run(db, s3, config.RECONCILE_GRACE_SECONDS, dry_run=False)
if result.get("skipped") or any(v for k, v in result.items() if k.startswith(("deleted", "marked", "removed"))):
log.info("reconcile %s", result)
except Exception:
log.warning("reconcile skipped: dependency unavailable")
await asyncio.sleep(config.RECONCILE_INTERVAL_SECONDS)
async def readiness_watch() -> None:
failures = 0
while True:
if await db.ready():
failures = 0
if not state["ready"]:
state["ready"] = True
log.info("ready again: database reachable")
else:
failures += 1
if failures >= config.READY_FAILURES and state["ready"]:
state["ready"] = False
log.warning("not ready: database unreachable, business requests get 503")
s3_ok = await run_in_threadpool(s3.probe)
if s3_ok != state["s3_ok"]:
state["s3_ok"] = s3_ok
log.info("object storage %s", "reachable" if s3_ok else "UNREACHABLE: uploads/downloads get 503, /health/ready 503")
await asyncio.sleep(config.READY_CHECK_SECONDS)
@asynccontextmanager
async def lifespan(_app: FastAPI):
previous = {}
def on_signal(signum, frame):
if not state["draining"]:
state["draining"] = True
log.info("signal %s: draining, new requests get 503", signal.Signals(signum).name)
handler = previous.get(signum)
if callable(handler):
handler(signum, frame)
for sig in (signal.SIGTERM, signal.SIGINT):
previous[sig] = signal.getsignal(sig)
signal.signal(sig, on_signal)
await db.open()
await sessions.open()
await run_in_threadpool(s3.open)
state["s3_ok"] = await run_in_threadpool(s3.probe)
tasks = [asyncio.create_task(sweeper()), asyncio.create_task(readiness_watch()), asyncio.create_task(reconciler_loop())]
log.info(
"started: instance=%s session_store=%s session_ttl=%d cache_ttl=%d pool=%d..%d max_inflight=%d max_body=%d idem_ttl=%d s3=%s bucket=%s",
config.INSTANCE_ID, config.SESSION_STORE, config.SESSION_TTL_SECONDS, config.SESSION_CACHE_TTL_SECONDS,
config.DB_POOL_MIN, config.DB_POOL_MAX, config.MAX_INFLIGHT_REQUESTS, config.MAX_BODY_BYTES,
config.IDEMPOTENCY_TTL_SECONDS, config.S3_ENDPOINT, config.S3_BUCKET,
)
yield
for task in tasks:
task.cancel()
await sessions.close()
await db.close()
log.info("stopped: cache=%s rejected=%s", sessions.stats, state["rejected"])
app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None)
@app.middleware("http")
async def guard(request: Request, call_next):
rid = uuid.uuid4().hex
request.state.rid = rid
exempt = request.url.path in EXEMPT_PATHS
if state["draining"] and request.url.path != "/health/live":
count_rejection("draining")
return error_body(rid, config.INSTANCE_ID, 503, "unavailable", "Сервер завершает работу", {"Retry-After": "1", "Connection": "close"})
if not exempt and not state["ready"]:
count_rejection("not_ready")
return error_body(rid, config.INSTANCE_ID, 503, "unavailable", "Нет связи с базой данных", {"Retry-After": "1"})
if not exempt and state["inflight"] >= config.MAX_INFLIGHT_REQUESTS:
count_rejection("inflight")
return error_body(rid, config.INSTANCE_ID, 429, "rate_limited", "Слишком много одновременных запросов", {"Retry-After": "1"})
state["inflight"] += 1
try:
response = await asyncio.wait_for(call_next(request), config.REQUEST_TIMEOUT)
except asyncio.TimeoutError:
count_rejection("request_timeout")
log.warning("request timeout request_id=%s method=%s path=%s", rid, request.method, request.url.path)
response = error_body(
rid, config.INSTANCE_ID, 503, "unavailable",
"Запрос не удалось обработать за отведённое время", {"Retry-After": "1"},
)
except Exception:
log.exception("unhandled error request_id=%s", rid)
response = error_body(rid, config.INSTANCE_ID, 500, "internal_error", "Внутренняя ошибка сервера")
finally:
state["inflight"] -= 1
response.headers["X-Request-Id"] = rid
response.headers["X-Instance-Id"] = config.INSTANCE_ID
return response
@app.exception_handler(ApiError)
async def api_error_handler(request: Request, exc: ApiError):
if exc.status in (413, 429, 503):
count_rejection(exc.code)
return error_body(request.state.rid, config.INSTANCE_ID, exc.status, exc.code, exc.message, exc.headers)
def parse_uuid(value: object) -> Optional[str]:
if not isinstance(value, str):
return None
try:
return str(uuid.UUID(value))
except ValueError:
return None
def non_blank(value: object, max_len: int) -> bool:
if not isinstance(value, str) or not 1 <= len(value) <= max_len:
return False
return value.translate(ZERO_WIDTH).strip() != ""
async def read_json(request: Request, required: Tuple[str, ...], optional: Tuple[str, ...] = ()) -> dict:
if request.headers.get("content-type", "").split(";")[0].strip().lower() != "application/json":
raise ApiError(415, "unsupported_media_type", "Ожидается application/json")
too_large = ApiError(413, "payload_too_large", "Тело запроса слишком большое", {"Connection": "close"})
declared = request.headers.get("content-length")
if declared and declared.isdigit() and int(declared) > config.MAX_BODY_BYTES:
raise too_large
raw = bytearray()
async for chunk in request.stream():
raw += chunk
if len(raw) > config.MAX_BODY_BYTES:
raise too_large
try:
body = json.loads(bytes(raw).decode("utf-8"))
except (UnicodeDecodeError, ValueError, RecursionError):
raise bad("Некорректный JSON") from None
if not isinstance(body, dict):
raise bad("Ожидается JSON-объект")
allowed = set(required) | set(optional)
if set(body) - allowed:
raise bad("Лишние поля в запросе")
if set(required) - set(body):
raise bad("Отсутствуют обязательные поля")
return body
def ensure_capacity() -> None:
if config.MAX_RSS_MB and rss_mb() > config.MAX_RSS_MB:
raise unavailable("Достигнут лимит памяти процесса, запись недоступна")
def bearer_token(request: Request) -> str:
scheme, _, value = request.headers.get("authorization", "").partition(" ")
token = value.strip()
if scheme.lower() != "bearer" or not token:
raise unauthorized()
return token
async def actor(request: Request) -> dict:
user = await sessions.resolve(bearer_token(request))
if user is None:
raise unauthorized()
return user
def basic_credentials(request: Request) -> Tuple[str, str]:
scheme, _, value = request.headers.get("authorization", "").partition(" ")
if scheme.lower() != "basic" or not value.strip():
raise unauthorized("Basic")
try:
decoded = base64.b64decode(value.strip(), validate=True).decode("utf-8")
except (binascii.Error, ValueError, UnicodeDecodeError):
raise unauthorized("Basic") from None
username, separator, password = decoded.partition(":")
if not separator:
raise unauthorized("Basic")
return username, password
async def member_chat(user: dict, chat_id: str) -> dict:
cid = parse_uuid(chat_id)
if cid is None:
raise bad("chat_id должен быть UUID")
async with db.connection() as conn:
chat = await repo.chat_for_member(conn, cid, user["id"])
if chat is None:
raise not_found()
return chat
def page_params(request: Request) -> Tuple[int, Optional[str]]:
query = request.query_params
limit = 50
if "limit" in query:
if not re.fullmatch(r"[0-9]{1,3}", query["limit"]) or not 1 <= int(query["limit"]) <= 100:
raise bad("limit должен быть целым 1..100")
limit = int(query["limit"])
cursor = query.get("cursor")
if cursor is not None and cursor == "":
raise bad("Некорректный cursor")
return limit, cursor
def keyset(scope: str, cursor: Optional[str]):
if cursor is None:
return None
try:
return decode_cursor(scope, cursor)
except BadCursor:
raise bad("Некорректный cursor") from None
def page(scope: str, items: List[dict], has_more: bool) -> JSONResponse:
next_cursor = encode_cursor(scope, items[-1]["created_at"], items[-1]["id"]) if has_more and items else None
return JSONResponse({"items": items, "next_cursor": next_cursor})
def detect_content_type(head: bytes) -> Optional[str]:
if head[:8] == PNG_MAGIC:
return "image/png"
if head[:3] == JPEG_MAGIC:
return "image/jpeg"
return None
def validate_filename(filename: str) -> None:
if not 1 <= len(filename) <= 255 or filename.strip() == "" or filename in (".", ".."):
raise bad("filename: 1..255 символов, не только пробелы")
if "/" in filename or "\\" in filename or any(unicodedata.category(ch) in ("Cc", "Cs", "Zl", "Zp") for ch in filename):
raise bad("filename содержит недопустимые символы")
@app.get("/health/live")
async def live():
return {"status": "ok"}
@app.get("/health/ready")
async def ready():
if not await db.ready():
raise unavailable("База данных недоступна")
if not state["s3_ok"]:
raise unavailable("Хранилище файлов недоступно")
return {"status": "ok"}
@app.post("/api/v1/users", status_code=201)
async def create_user(request: Request):
body = await read_json(request, ("username", "display_name", "password"))
if not isinstance(body["username"], str) or not USERNAME_RE.fullmatch(body["username"]):
raise bad("username должен соответствовать [a-z0-9_]{3,32}")
if not non_blank(body["display_name"], 100):
raise bad("display_name: 1..100 символов, не только пробелы")
password = body["password"]
if not isinstance(password, str) or not config.PASSWORD_MIN <= len(password) <= config.PASSWORD_MAX:
raise bad("password: %d..%d символов" % (config.PASSWORD_MIN, config.PASSWORD_MAX))
ensure_capacity()
password_hash = await run_in_threadpool(passwords.hash_password, password)
async with db.connection() as conn:
user = await repo.create_user(conn, body["username"], body["display_name"], password_hash)
if user is None:
raise ApiError(409, "conflict", "username уже занят")
log.info("user_created id=%s", user["id"])
return JSONResponse(user, status_code=201)
@app.post("/api/v1/auth/sessions", status_code=201)
async def login(request: Request):
if await request.body():
raise bad("POST /auth/sessions не принимает тело запроса")
username, password = basic_credentials(request)
row = None
if USERNAME_RE.fullmatch(username) and config.PASSWORD_MIN <= len(password) <= config.PASSWORD_MAX:
async with db.connection() as conn:
row = await repo.credentials(conn, username)
stored = row["password_hash"] if row else passwords.DUMMY_HASH
matches = await run_in_threadpool(passwords.verify_password, stored, password)
if row is None or not matches:
log.info("login_failed username_known=%s", row is not None)
raise unauthorized("Basic")
user = repo.public_user(row)
token, expires_at = await sessions.create(user)
log.info("session_created user=%s", user["id"])
return JSONResponse({"token": token, "token_type": "Bearer", "expires_at": expires_at, "user": user}, status_code=201)
@app.delete("/api/v1/auth/sessions/current", status_code=204)
async def logout(request: Request):
token = bearer_token(request)
user = await sessions.resolve(token)
if user is None:
raise unauthorized()
await sessions.revoke(token)
log.info("session_revoked user=%s", user["id"])
return Response(status_code=204)
@app.get("/api/v1/users/me")
async def me(request: Request):
return await actor(request)
@app.post("/api/v1/chats", status_code=201)
async def create_chat(request: Request):
user = await actor(request)
body = await read_json(request, ("title", "member_ids"))
if not non_blank(body["title"], 100):
raise bad("title: 1..100 символов, не только пробелы")
raw_ids = body["member_ids"]
if not isinstance(raw_ids, list) or not 1 <= len(raw_ids) <= 100:
raise bad("member_ids: массив из 1..100 UUID")
ids: List[str] = []
for value in raw_ids:
parsed = parse_uuid(value)
if parsed is None:
raise bad("member_ids содержит некорректный UUID")
ids.append(parsed)
if len(set(ids)) != len(ids):
raise bad("member_ids содержит дубликаты")
if user["id"] not in ids:
raise bad("Создатель должен входить в member_ids")
ensure_capacity()
async def insert(conn):
return await repo.create_chat(conn, body["title"], ids)
try:
chat = await db.in_transaction(insert)
except repo.UnknownMember:
raise bad("member_ids содержит неизвестного пользователя") from None
log.info("chat_created id=%s members=%d", chat["id"], len(ids))
return JSONResponse(chat, status_code=201)
@app.get("/api/v1/chats")
async def list_chats(request: Request):
user = await actor(request)
limit, cursor = page_params(request)
scope = "chats:" + user["id"]
after = keyset(scope, cursor)
async with db.connection() as conn:
items, has_more = await repo.list_chats(conn, user["id"], limit, after)
return page(scope, items, has_more)
@app.get("/api/v1/chats/{chat_id}")
async def get_chat(chat_id: str, request: Request):
return await member_chat(await actor(request), chat_id)
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
async def create_message(chat_id: str, request: Request):
user = await actor(request)
cid = parse_uuid(chat_id)
if cid is None:
raise bad("chat_id должен быть UUID")
idem_key = request.headers.get("idempotency-key", "")
if not idem_key or not IDEMPOTENCY_KEY_RE.fullmatch(idem_key):
raise bad("Заголовок Idempotency-Key обязателен и должен соответствовать [A-Za-z0-9._:-]{1,128}")
body = await read_json(request, ("text",), ("attachment_ids",))
text = body["text"]
attachment_ids_raw = body.get("attachment_ids", [])
if not isinstance(attachment_ids_raw, list):
raise bad("attachment_ids должен быть массивом UUID")
if len(attachment_ids_raw) > 10:
raise bad("attachment_ids: максимум 10 вложений")
attachment_ids: List[str] = []
for value in attachment_ids_raw:
parsed = parse_uuid(value)
if parsed is None:
raise bad("attachment_ids содержит некорректный UUID")
attachment_ids.append(parsed)
if len(set(attachment_ids)) != len(attachment_ids):
raise bad("attachment_ids содержит дубликаты")
has_text = isinstance(text, str) and non_blank(text, 4000)
has_attachments = len(attachment_ids) > 0
if not has_text and not has_attachments:
raise bad("text: 1..4000 символов, не только пробелы")
if isinstance(text, str) and len(text) > 4000:
raise bad("text: 1..4000 символов, не только пробелы")
if not isinstance(text, str):
raise bad("text должен быть строкой")
ensure_capacity()
normalized = {"text": text}
if attachment_ids:
normalized["attachment_ids"] = attachment_ids
body_hash = hashlib.sha256(
json.dumps(normalized, sort_keys=True, ensure_ascii=False).encode()
).hexdigest()
async def do(conn):
return await repo.create_message_idempotent(conn, cid, user["id"], text, attachment_ids, idem_key, body_hash)
status, message = await db.in_transaction(do)
if status == "conflict":
raise ApiError(409, "conflict", "Idempotency-Key использован с другим телом запроса")
if status == "not_member":
raise not_found()
if status == "attachment_not_found":
raise not_found()
if status == "attachment_failed":
raise ApiError(409, "conflict", "Вложение в состоянии failed, нельзя прикрепить")
return JSONResponse(message, status_code=201)
@app.get("/api/v1/chats/{chat_id}/messages")
async def list_messages(chat_id: str, request: Request):
chat = await member_chat(await actor(request), chat_id)
limit, cursor = page_params(request)
scope = "messages:" + chat["id"]
after = keyset(scope, cursor)
async with db.connection() as conn:
items, has_more = await repo.list_messages(conn, chat["id"], limit, after)
return page(scope, items, has_more)
@app.post("/api/v1/chats/{chat_id}/attachments", status_code=201)
async def upload_attachment(chat_id: str, request: Request):
user = await actor(request)
chat = await member_chat(user, chat_id)
filename = request.query_params.get("filename", "")
validate_filename(filename)
declared_ct = request.headers.get("content-type", "").split(";")[0].strip().lower()
if declared_ct not in ALLOWED_CONTENT_TYPES:
raise ApiError(415, "unsupported_media_type", "Допускается только image/png или image/jpeg")
declared_length = request.headers.get("content-length")
too_large = ApiError(413, "payload_too_large", "Файл превышает 10 MiB", {"Connection": "close"})
if declared_length and declared_length.isdigit() and int(declared_length) > config.MAX_UPLOAD_BYTES:
raise too_large
ensure_capacity()
sha = hashlib.sha256()
size = 0
with tempfile.SpooledTemporaryFile(max_size=config.UPLOAD_SPOOL_BYTES) as spool:
head = b""
async for chunk in request.stream():
size += len(chunk)
if size > config.MAX_UPLOAD_BYTES:
raise too_large
if len(head) < 8:
head += chunk[: 8 - len(head)]
if len(head) == 8 and detect_content_type(head) is None:
raise ApiError(415, "unsupported_media_type", "Содержимое не является PNG/JPEG")
sha.update(chunk)
spool.write(chunk)
if size == 0:
raise bad("Пустой файл")
actual_ct = detect_content_type(head)
if actual_ct is None:
raise ApiError(415, "unsupported_media_type", "Содержимое не является PNG/JPEG")
if actual_ct != declared_ct:
raise ApiError(415, "unsupported_media_type", "Content-Type не соответствует содержимому файла")
async with upload_slots:
await run_in_threadpool(inspect_image, spool, size, actual_ct)
attachment_id = str(uuid.uuid4())
object_key = "attachments/" + attachment_id
async with db.connection() as conn:
await repo.begin_attachment(
conn, attachment_id, chat["id"], user["id"], filename, actual_ct, size, sha.hexdigest(), object_key,
)
try:
async with upload_slots:
await run_in_threadpool(s3.put, object_key, spool, size, actual_ct)
except BaseException:
defer(compensate(attachment_id, object_key))
raise
try:
async with db.connection() as conn:
att = await repo.finish_attachment(conn, attachment_id)
except BaseException:
await compensate(attachment_id, object_key)
raise
if att is None:
raise unavailable("Загрузка отменена сверкой, повторите запрос")
log.info("attachment_uploaded id=%s chat=%s size=%d", att["id"], chat["id"], size)
return JSONResponse(att, status_code=201)
def defer(coro) -> None:
task = asyncio.ensure_future(coro)
background.add(task)
task.add_done_callback(background.discard)
async def compensate(attachment_id: str, object_key: str) -> None:
"""Best effort; whatever is left behind is collected by the reconciler after the grace period."""
try:
async with db.connection() as conn:
await repo.abort_attachment(conn, attachment_id)
await run_in_threadpool(s3.delete, object_key)
except BaseException:
log.warning("compensation incomplete attachment=%s, left for reconciler", attachment_id)
async def accessible_attachment(request: Request, attachment_id: str) -> dict:
user = await actor(request)
aid = parse_uuid(attachment_id)
if aid is None:
raise bad("attachment_id должен быть UUID")
async with db.connection() as conn:
row = await repo.get_attachment(conn, aid)
if row is None:
raise not_found()
chat = await repo.chat_for_member(conn, str(row["chat_id"]), user["id"])
if chat is None:
raise not_found()
return row
@app.get("/api/v1/attachments/{attachment_id}")
async def get_attachment(attachment_id: str, request: Request):
return repo._attachment(await accessible_attachment(request, attachment_id))
@app.get("/api/v1/attachments/{attachment_id}/content")
async def download_attachment(attachment_id: str, request: Request):
row = await accessible_attachment(request, attachment_id)
variant = request.query_params.get("variant", "original")
if variant != "original":
raise not_found()
if row["status"] != "ready":
raise ApiError(409, "conflict", "Вложение недоступно для скачивания")
opened = await run_in_threadpool(s3.open_stream, row["object_key"])
if opened is None:
log.error("object_missing attachment=%s", row["id"])
raise unavailable("Оригинал временно недоступен")
chunks, length = opened
return StreamingResponse(
iterate_in_threadpool(chunks), media_type=row["content_type"], headers={"Content-Length": str(length)},
)
@app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "PATCH", "DELETE"])
async def fallback(request: Request):
raise not_found()
+16
View File
@@ -0,0 +1,16 @@
from argon2 import PasswordHasher
from argon2.exceptions import Argon2Error, VerifyMismatchError
HASHER = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1)
DUMMY_HASH = HASHER.hash("there-is-no-such-user-password")
def hash_password(password: str) -> str:
return HASHER.hash(password)
def verify_password(stored: str, password: str) -> bool:
try:
return HASHER.verify(stored, password)
except (VerifyMismatchError, Argon2Error, ValueError):
return False
+115
View File
@@ -0,0 +1,115 @@
"""DB <-> S3 reconciliation for attachments.
Invariant: a row is inserted as 'uploading' BEFORE the object is written, and becomes 'ready' only AFTER the
PUT succeeded. So every object has a row, and a client only ever sees 'ready' rows.
Cases (all gated by a grace period so in-flight uploads are never touched):
stale_uploading row 'uploading' older than grace AND its object (if any) older than grace -> delete both;
a fresh object under an old row is left alone (re-checked via LastModified)
orphan_object object without any row, older than grace -> delete object
missing_object 'ready' row confirmed longer than grace ago whose object is gone (re-checked by HEAD) -> mark 'failed'/object_missing, never delete the row
Rows referenced by messages are never deleted: only 'uploading' rows can be removed, and those cannot be linked.
"""
import logging
import time
from datetime import datetime, timedelta, timezone
from starlette.concurrency import run_in_threadpool
log = logging.getLogger("messenger.reconcile")
LOCK_ID = 2026_0104
PREFIX = "attachments/"
BATCH = 500
async def run(db, s3, grace_seconds: int, dry_run: bool = True) -> dict:
started = time.monotonic()
result = {
"dry_run": dry_run, "grace_seconds": grace_seconds,
"stale_uploading": 0, "orphan_objects": 0, "missing_objects": 0,
"deleted_objects": 0, "removed_rows": 0, "marked_failed": 0,
"objects_scanned": 0, "rows_scanned": 0, "protected_fresh_objects": 0,
}
async with db.connection() as conn:
cur = await conn.execute("SELECT pg_try_advisory_lock(%s) AS got", (LOCK_ID,))
if not (await cur.fetchone())["got"]:
return {"skipped": "another reconciler is running"}
try:
cutoff = datetime.now(timezone.utc) - timedelta(seconds=grace_seconds)
await _stale_uploading(conn, s3, cutoff, dry_run, result)
await _orphan_objects(conn, s3, cutoff, dry_run, result)
await _missing_objects(conn, s3, cutoff, dry_run, result)
finally:
await conn.execute("SELECT pg_advisory_unlock(%s)", (LOCK_ID,))
result["seconds"] = round(time.monotonic() - started, 3)
return result
async def _stale_uploading(conn, s3, cutoff, dry_run, result):
cur = await conn.execute(
"SELECT id, object_key FROM attachments WHERE status = 'uploading' AND created_at < %s", (cutoff,),
)
for row in await cur.fetchall():
modified = await run_in_threadpool(s3.head, row["object_key"])
if modified is not None and modified >= cutoff:
result["protected_fresh_objects"] += 1
continue
result["stale_uploading"] += 1
if dry_run:
continue
if modified is not None:
await run_in_threadpool(s3.delete, row["object_key"])
result["deleted_objects"] += 1
done = await conn.execute(
"DELETE FROM attachments WHERE id = %s AND status = 'uploading' AND created_at < %s", (row["id"], cutoff),
)
result["removed_rows"] += done.rowcount
async def _orphan_objects(conn, s3, cutoff, dry_run, result):
pages = await run_in_threadpool(lambda: iter(s3.list_pages(PREFIX)))
while True:
page = await run_in_threadpool(next, pages, None)
if page is None:
break
result["objects_scanned"] += len(page)
keys = [o["Key"] for o in page]
if not keys:
continue
cur = await conn.execute("SELECT object_key FROM attachments WHERE object_key = ANY(%s)", (keys,))
known = {row["object_key"] for row in await cur.fetchall()}
for obj in page:
if obj["Key"] in known or obj["LastModified"] >= cutoff:
continue
result["orphan_objects"] += 1
if not dry_run:
again = await conn.execute("SELECT 1 FROM attachments WHERE object_key = %s", (obj["Key"],))
if await again.fetchone() is None:
await run_in_threadpool(s3.delete, obj["Key"])
result["deleted_objects"] += 1
async def _missing_objects(conn, s3, cutoff, dry_run, result):
last = None
while True:
cur = await conn.execute(
"SELECT id, object_key FROM attachments WHERE status = 'ready' AND updated_at < %s"
" AND (%s::uuid IS NULL OR id > %s::uuid) ORDER BY id LIMIT %s",
(cutoff, last, last, BATCH),
)
rows = await cur.fetchall()
if not rows:
return
for row in rows:
result["rows_scanned"] += 1
if await run_in_threadpool(s3.exists, row["object_key"]):
continue
result["missing_objects"] += 1
if not dry_run:
done = await conn.execute(
"UPDATE attachments SET status = 'failed', error_code = 'object_missing',"
" updated_at = clock_timestamp() WHERE id = %s AND status = 'ready'", (row["id"],),
)
result["marked_failed"] += done.rowcount
last = str(rows[-1]["id"])
+293
View File
@@ -0,0 +1,293 @@
import hashlib
import json
from typing import List, Optional, Tuple
import psycopg
from app.cursor import fmt
MESSAGE_COLUMNS = "id, chat_id, sender_id, text, created_at"
CHAT_QUERY = (
"SELECT c.id, c.title, c.created_at,"
" ARRAY(SELECT m2.user_id FROM chat_members m2 WHERE m2.chat_id = c.id ORDER BY m2.user_id) AS member_ids"
)
class UnknownMember(Exception):
pass
def decoded(value) -> str:
return bytes(value).decode("utf-8")
def public_user(row) -> dict:
return {
"id": str(row["id"]),
"username": row["username"],
"display_name": decoded(row["display_name"]),
"created_at": fmt(row["created_at"]),
}
def _chat(row) -> dict:
return {
"id": str(row["id"]),
"title": decoded(row["title"]),
"member_ids": [str(value) for value in row["member_ids"]],
"created_at": fmt(row["created_at"]),
}
def _message(row) -> dict:
return {
"id": str(row["id"]),
"chat_id": str(row["chat_id"]),
"sender_id": str(row["sender_id"]),
"text": decoded(row["text"]),
"created_at": fmt(row["created_at"]),
}
def _message_with_attachments(row, attachment_ids: List[str]) -> dict:
msg = _message(row)
msg["attachment_ids"] = attachment_ids
return msg
def _attachment(row) -> 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": row["error_code"],
"created_at": fmt(row["created_at"]),
"updated_at": fmt(row["updated_at"]),
}
async def create_user(conn, username: str, display_name: str, password_hash: str) -> Optional[dict]:
try:
cur = await conn.execute(
"INSERT INTO users (id, username, display_name, password_hash, created_at)"
" VALUES (gen_random_uuid(), %s, %s, %s, clock_timestamp())"
" RETURNING id, username, display_name, created_at",
(username, display_name.encode("utf-8"), password_hash),
)
except psycopg.errors.UniqueViolation:
return None
return public_user(await cur.fetchone())
async def credentials(conn, username: str):
cur = await conn.execute(
"SELECT id, username, display_name, created_at, password_hash FROM users WHERE username = %s",
(username,),
)
return await cur.fetchone()
async def create_chat(conn, title: str, member_ids: List[str]) -> dict:
cur = await conn.execute(
"INSERT INTO chats (id, title, created_at)"
" VALUES (gen_random_uuid(), %s, clock_timestamp())"
" RETURNING id, title, created_at",
(title.encode("utf-8"),),
)
chat = await cur.fetchone()
cur = await conn.execute(
"INSERT INTO chat_members (chat_id, user_id) SELECT %s, u.id FROM users u WHERE u.id = ANY(%s::uuid[])",
(chat["id"], member_ids),
)
if cur.rowcount != len(member_ids):
raise UnknownMember()
chat["member_ids"] = list(member_ids)
return _chat(chat)
async def chat_for_member(conn, chat_id: str, user_id: str) -> Optional[dict]:
cur = await conn.execute(
CHAT_QUERY + " FROM chats c JOIN chat_members m ON m.chat_id = c.id AND m.user_id = %s WHERE c.id = %s",
(user_id, chat_id),
)
row = await cur.fetchone()
return _chat(row) if row else None
async def list_chats(conn, user_id: str, limit: int, after) -> Tuple[List[dict], bool]:
ts, last_id = after if after else (None, None)
cur = await conn.execute(
CHAT_QUERY
+ " FROM chats c JOIN chat_members m ON m.chat_id = c.id"
" WHERE m.user_id = %s AND (%s::timestamptz IS NULL OR (c.created_at, c.id) > (%s::timestamptz, %s::uuid))"
" ORDER BY c.created_at, c.id LIMIT %s",
(user_id, ts, ts, last_id, limit + 1),
)
rows = await cur.fetchall()
return [_chat(row) for row in rows[:limit]], len(rows) > limit
async def create_message(conn, chat_id: str, sender_id: str, text: str) -> Optional[dict]:
cur = await conn.execute(
"INSERT INTO messages (id, chat_id, sender_id, text, created_at)"
" SELECT gen_random_uuid(), %s, %s, %s, clock_timestamp()"
" WHERE EXISTS (SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s)"
" RETURNING " + MESSAGE_COLUMNS,
(chat_id, sender_id, text.encode("utf-8"), chat_id, sender_id),
)
row = await cur.fetchone()
return _message(row) if row else None
async def _fetch_message_attachment_ids(conn, message_id: str) -> List[str]:
cur = await conn.execute(
"SELECT attachment_id FROM message_attachments WHERE message_id = %s ORDER BY position",
(message_id,),
)
rows = await cur.fetchall()
return [str(row["attachment_id"]) for row in rows]
async def _link_attachments(conn, message_id: str, chat_id: str, attachment_ids: List[str]) -> None:
for pos, aid in enumerate(attachment_ids):
await conn.execute(
"INSERT INTO message_attachments (message_id, attachment_id, position) VALUES (%s, %s, %s)",
(message_id, aid, pos),
)
async def list_messages(conn, chat_id: str, limit: int, after) -> Tuple[List[dict], bool]:
ts, last_id = after if after else (None, None)
cur = await conn.execute(
"SELECT " + MESSAGE_COLUMNS + " FROM messages"
" WHERE chat_id = %s AND (%s::timestamptz IS NULL OR (created_at, id) > (%s::timestamptz, %s::uuid))"
" ORDER BY created_at, id LIMIT %s",
(chat_id, ts, ts, last_id, limit + 1),
)
rows = await cur.fetchall()
messages = []
for row in rows[:limit]:
aids = await _fetch_message_attachment_ids(conn, row["id"])
messages.append(_message_with_attachments(row, aids))
return messages, len(rows) > limit
def _idem_lock_id(user_id: str, chat_id: str, key: str) -> int:
raw = "%s:%s:%s" % (user_id, chat_id, key)
return int(hashlib.sha256(raw.encode()).hexdigest()[:15], 16)
async def create_message_idempotent(conn, chat_id: str, sender_id: str, text: str,
attachment_ids: List[str], idem_key: str, body_hash: str):
lock_id = _idem_lock_id(sender_id, chat_id, idem_key)
await conn.execute("SELECT pg_advisory_xact_lock(%s)", (lock_id,))
cur = await conn.execute(
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s",
(chat_id, sender_id),
)
if await cur.fetchone() is None:
return "not_member", None
cur = await conn.execute(
"SELECT request_body_hash, response_json FROM idempotency_keys"
" WHERE user_id = %s AND chat_id = %s AND key = %s",
(sender_id, chat_id, idem_key),
)
existing = await cur.fetchone()
if existing:
if existing["request_body_hash"] != body_hash:
return "conflict", None
return "replay", json.loads(existing["response_json"])
if attachment_ids:
cur = await conn.execute(
"SELECT id, chat_id, status FROM attachments WHERE id = ANY(%s::uuid[]) AND status <> 'uploading'",
(attachment_ids,),
)
att_rows = await cur.fetchall()
found_ids = {str(row["id"]) for row in att_rows}
for aid in attachment_ids:
if aid not in found_ids:
return "attachment_not_found", None
for row in att_rows:
if str(row["chat_id"]) != chat_id:
return "attachment_not_found", None
if row["status"] == "failed":
return "attachment_failed", None
text_bytes = text.encode("utf-8") if text else b""
cur = await conn.execute(
"INSERT INTO messages (id, chat_id, sender_id, text, created_at)"
" SELECT gen_random_uuid(), %s, %s, %s, clock_timestamp()"
" WHERE EXISTS (SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s)"
" RETURNING " + MESSAGE_COLUMNS,
(chat_id, sender_id, text_bytes, chat_id, sender_id),
)
row = await cur.fetchone()
if row is None:
return "not_member", None
if attachment_ids:
await _link_attachments(conn, row["id"], chat_id, attachment_ids)
message = _message_with_attachments(row, list(attachment_ids))
await conn.execute(
"INSERT INTO idempotency_keys (user_id, chat_id, key, request_body_hash, response_json, created_at)"
" VALUES (%s, %s, %s, %s, %s, clock_timestamp())",
(sender_id, chat_id, idem_key, body_hash, json.dumps(message, ensure_ascii=False)),
)
return "created", message
async def cleanup_idempotency(conn, ttl_seconds: int) -> int:
cur = await conn.execute(
"DELETE FROM idempotency_keys WHERE created_at < now() - make_interval(secs => %s)",
(ttl_seconds,),
)
return cur.rowcount
async def begin_attachment(conn, attachment_id: str, chat_id: str, owner_id: str, filename: str,
content_type: str, size_bytes: int, sha256: str, object_key: str) -> None:
await conn.execute(
"INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key,"
" status, error_code, created_at, updated_at)"
" VALUES (%s, %s, %s, %s, %s, %s, %s, %s, 'uploading', NULL, clock_timestamp(), clock_timestamp())",
(attachment_id, chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key),
)
async def finish_attachment(conn, attachment_id: str) -> Optional[dict]:
cur = await conn.execute(
"UPDATE attachments SET status = 'ready', updated_at = clock_timestamp()"
" WHERE id = %s AND status = 'uploading'"
" RETURNING id, chat_id, owner_id, filename, content_type, size_bytes, sha256, status, error_code,"
" created_at, updated_at",
(attachment_id,),
)
row = await cur.fetchone()
return _attachment(row) if row else None
async def abort_attachment(conn, attachment_id: str) -> None:
await conn.execute("DELETE FROM attachments WHERE id = %s AND status = 'uploading'", (attachment_id,))
async def get_attachment(conn, attachment_id: str):
cur = await conn.execute(
"SELECT id, chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key, status, error_code,"
" created_at, updated_at FROM attachments WHERE id = %s AND status <> 'uploading'",
(attachment_id,),
)
return await cur.fetchone()
+97
View File
@@ -0,0 +1,97 @@
import logging
from typing import Iterator, Optional, Tuple
import boto3
from botocore.config import Config as BotoConfig
from botocore.exceptions import BotoCoreError, ClientError
from app import config
from app.errors import unavailable
log = logging.getLogger("messenger.s3")
MISSING = ("NoSuchKey", "404", "NotFound")
class S3Storage:
def __init__(self) -> None:
self.client = None
self.probe_client = None
def open(self) -> None:
self.probe_client = self._client(1.0, 1.5)
self.client = self._client(config.S3_CONNECT_TIMEOUT, config.S3_READ_TIMEOUT)
def _client(self, connect: float, read: float):
return boto3.client(
"s3",
endpoint_url=config.S3_ENDPOINT,
region_name=config.S3_REGION,
aws_access_key_id=config.S3_ACCESS_KEY_ID,
aws_secret_access_key=config.S3_SECRET_ACCESS_KEY,
config=BotoConfig(
signature_version="s3v4",
s3={"addressing_style": "path"},
connect_timeout=connect,
read_timeout=read,
retries={"max_attempts": 0},
),
)
def probe(self) -> bool:
try:
self.probe_client.head_bucket(Bucket=config.S3_BUCKET)
return True
except Exception:
return False
def put(self, key: str, fileobj, size: int, content_type: str) -> None:
try:
fileobj.seek(0)
self.client.put_object(
Bucket=config.S3_BUCKET, Key=key, Body=fileobj, ContentLength=size, ContentType=content_type,
)
except (BotoCoreError, ClientError) as exc:
log.error("s3_put_failed key=%s error=%s", key, type(exc).__name__)
raise unavailable("Хранилище файлов недоступно") from None
def open_stream(self, key: str) -> Optional[Tuple[Iterator[bytes], int]]:
try:
response = self.client.get_object(Bucket=config.S3_BUCKET, Key=key)
except ClientError as exc:
if exc.response["Error"].get("Code", "") in MISSING:
return None
log.error("s3_get_failed key=%s error=%s", key, type(exc).__name__)
raise unavailable("Хранилище файлов недоступно") from None
except BotoCoreError as exc:
log.error("s3_get_failed key=%s error=%s", key, type(exc).__name__)
raise unavailable("Хранилище файлов недоступно") from None
body = response["Body"]
return body.iter_chunks(65536), int(response["ContentLength"])
def head(self, key: str):
"""LastModified of the object, or None when it does not exist."""
try:
return self.client.head_object(Bucket=config.S3_BUCKET, Key=key)["LastModified"]
except ClientError as exc:
if exc.response["Error"].get("Code", "") in MISSING:
return None
raise
def exists(self, key: str) -> bool:
return self.head(key) is not None
def delete(self, key: str) -> None:
self.client.delete_object(Bucket=config.S3_BUCKET, Key=key)
def list_pages(self, prefix: str):
paginator = self.client.get_paginator("list_objects_v2")
for page in paginator.paginate(Bucket=config.S3_BUCKET, Prefix=prefix, PaginationConfig={"PageSize": 500}):
yield page.get("Contents", [])
def ready(self) -> bool:
try:
self.client.head_bucket(Bucket=config.S3_BUCKET)
return True
except Exception:
return False
+154
View File
@@ -0,0 +1,154 @@
import hashlib
import json
import logging
import secrets
from datetime import datetime, timedelta, timezone
from typing import Optional
import valkey.asyncio as valkey
from app import config, repo
from app.cursor import fmt
from app.errors import unavailable
log = logging.getLogger("messenger.sessions")
REVOKED = "revoked"
class SessionStore:
def __init__(self, db) -> None:
self.db = db
self.client = None
self.stats = {"hits": 0, "misses": 0, "errors": 0}
async def open(self) -> None:
if not config.CACHE_URL:
log.info("session cache disabled: CACHE_URL is empty")
return
self.client = valkey.Valkey.from_url(
config.CACHE_URL,
socket_timeout=config.CACHE_TIMEOUT,
socket_connect_timeout=config.CACHE_TIMEOUT,
decode_responses=True,
)
async def close(self) -> None:
if self.client is not None:
await self.client.aclose()
self.client = None
@staticmethod
def digest(token: str) -> bytes:
return hashlib.sha256(token.encode("utf-8")).digest()
@staticmethod
def key(digest: bytes) -> str:
return "session:" + digest.hex()
async def create(self, user: dict) -> tuple:
token = secrets.token_urlsafe(32)
digest = self.digest(token)
expires_at = datetime.now(timezone.utc) + timedelta(seconds=config.SESSION_TTL_SECONDS)
async with self.db.connection() as conn:
await conn.execute(
"INSERT INTO sessions (token_hash, user_id, created_at, expires_at)"
" VALUES (%s, %s, clock_timestamp(), %s)",
(digest, user["id"], expires_at),
)
await self._cache_put(digest, user, expires_at)
return token, fmt(expires_at)
async def resolve(self, token: str) -> Optional[dict]:
digest = self.digest(token)
cached = await self._cache_get(digest)
if cached == REVOKED:
self.stats["hits"] += 1
return None
if cached is not None:
self.stats["hits"] += 1
return cached
self.stats["misses"] += 1
async with self.db.connection() as conn:
cur = await conn.execute(
"SELECT u.id, u.username, u.display_name, u.created_at, s.expires_at"
" FROM sessions s JOIN users u ON u.id = s.user_id"
" WHERE s.token_hash = %s AND s.expires_at > now()",
(digest,),
)
row = await cur.fetchone()
if row is None:
return None
user = repo.public_user(row)
await self._cache_put(digest, user, row["expires_at"])
return user
async def revoke(self, token: str) -> None:
digest = self.digest(token)
await self._cache_revoke(digest)
try:
async with self.db.connection() as conn:
await conn.execute("DELETE FROM sessions WHERE token_hash = %s", (digest,))
except Exception:
await self._cache_release(digest)
raise
async def sweep(self) -> int:
async with self.db.connection() as conn:
cur = await conn.execute("DELETE FROM sessions WHERE expires_at <= now()")
return cur.rowcount
def _cache_ttl(self, expires_at: datetime) -> int:
remaining = int((expires_at - datetime.now(timezone.utc)).total_seconds())
return min(config.SESSION_CACHE_TTL_SECONDS, remaining)
async def _cache_get(self, digest: bytes) -> Optional[dict]:
if self.client is None:
return None
try:
raw = await self.client.get(self.key(digest))
except Exception:
self._cache_failed("get")
return None
if not raw:
return None
if raw == REVOKED:
return REVOKED
try:
return json.loads(raw)
except ValueError:
return None
async def _cache_put(self, digest: bytes, user: dict, expires_at: datetime) -> None:
if self.client is None:
return
ttl = self._cache_ttl(expires_at)
if ttl <= 0:
return
payload = json.dumps(user)
try:
await self.client.set(self.key(digest), payload, ex=ttl, nx=True)
except Exception:
self._cache_failed("set")
async def _cache_release(self, digest: bytes) -> None:
if self.client is None:
return
try:
await self.client.delete(self.key(digest))
except Exception:
self._cache_failed("release")
async def _cache_revoke(self, digest: bytes) -> None:
if self.client is None:
return
try:
await self.client.set(self.key(digest), REVOKED, ex=config.SESSION_REVOKED_TTL_SECONDS)
except Exception:
self._cache_failed("revoke")
raise unavailable("Кэш сессий недоступен, выход из сессии не подтверждён") from None
def _cache_failed(self, operation: str) -> None:
self.stats["errors"] += 1
if self.stats["errors"] % 50 == 1:
log.warning("session cache %s failed, falling back to postgres (errors=%d)", operation, self.stats["errors"])