forked from mtusi2026/mtusi2026lab4
Хранить вложения в приватном S3 и сверять их с PostgreSQL.
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""Messenger API for laboratory 4."""
|
||||
+226
@@ -0,0 +1,226 @@
|
||||
"""Operator tools. Not part of the public HTTP API."""
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
from app.config import load_settings
|
||||
from app.db import close, connect, migrate, pool
|
||||
from app.reconcile import reconcile
|
||||
from app import s3client
|
||||
|
||||
|
||||
async def _prepare(settings):
|
||||
await connect(settings)
|
||||
await migrate(settings)
|
||||
|
||||
|
||||
async def _inject(settings, chat_id: str, owner_id: str) -> dict:
|
||||
if settings.app_env != "lab":
|
||||
raise SystemExit("inject is allowed only when APP_ENV=lab")
|
||||
chat_uuid = uuid.UUID(chat_id)
|
||||
owner_uuid = uuid.UUID(owner_id)
|
||||
member = await pool().fetchval(
|
||||
"SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2",
|
||||
chat_uuid,
|
||||
owner_uuid,
|
||||
)
|
||||
if member is None:
|
||||
raise SystemExit("owner is not a member of the chat")
|
||||
|
||||
def staged(note: str) -> tuple[str, str, bytes]:
|
||||
attachment_id = str(uuid.uuid4())
|
||||
key = f"o/{attachment_id}"
|
||||
payload = f"fault-{note}-{attachment_id}".encode("utf-8")
|
||||
return attachment_id, key, payload
|
||||
|
||||
fresh_id, fresh_key, fresh_body = staged("fresh-orphan")
|
||||
old_id, old_key, old_body = staged("old-orphan")
|
||||
stale_id, stale_key, stale_body = staged("stale-missing")
|
||||
used_id, used_key, used_body = staged("in-use-missing")
|
||||
|
||||
for key, body in (
|
||||
(fresh_key, fresh_body),
|
||||
(old_key, old_body),
|
||||
(stale_key, stale_body),
|
||||
(used_key, used_body),
|
||||
):
|
||||
s3client.put_bytes(settings, key, body)
|
||||
|
||||
async with pool().acquire() as conn:
|
||||
async with conn.transaction():
|
||||
for attachment_id, key, body, note in (
|
||||
(fresh_id, fresh_key, fresh_body, "fresh-orphan"),
|
||||
(old_id, old_key, old_body, "old-orphan"),
|
||||
):
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO object_ledger (
|
||||
object_key, attachment_id, chat_id, state, note, size_bytes, created_at, updated_at
|
||||
)
|
||||
VALUES ($1, $2, $3, 'staging', $4, $5, clock_timestamp(), clock_timestamp())
|
||||
""",
|
||||
key,
|
||||
uuid.UUID(attachment_id),
|
||||
chat_uuid,
|
||||
note,
|
||||
len(body),
|
||||
)
|
||||
await conn.execute(
|
||||
"""
|
||||
UPDATE object_ledger
|
||||
SET created_at = clock_timestamp() - interval '2 hours',
|
||||
updated_at = clock_timestamp() - interval '2 hours'
|
||||
WHERE object_key = $1
|
||||
""",
|
||||
old_key,
|
||||
)
|
||||
for attachment_id, key, body, filename in (
|
||||
(stale_id, stale_key, stale_body, "fault-stale-missing"),
|
||||
(used_id, used_key, used_body, "fault-in-use-missing"),
|
||||
):
|
||||
digest = hashlib.sha256(body).hexdigest()
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO attachments (
|
||||
id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||||
status, object_key, error_code, created_at, updated_at
|
||||
)
|
||||
VALUES (
|
||||
$1, $2, $3, $4, 'image/png', $5, $6, 'ready', $7, NULL,
|
||||
clock_timestamp() - interval '2 hours',
|
||||
clock_timestamp() - interval '2 hours'
|
||||
)
|
||||
""",
|
||||
uuid.UUID(attachment_id),
|
||||
chat_uuid,
|
||||
owner_uuid,
|
||||
filename,
|
||||
len(body),
|
||||
digest,
|
||||
key,
|
||||
)
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO object_ledger (
|
||||
object_key, attachment_id, chat_id, state, note, size_bytes, created_at, updated_at
|
||||
)
|
||||
VALUES (
|
||||
$1, $2, $3, 'committed', $4, $5,
|
||||
clock_timestamp() - interval '2 hours',
|
||||
clock_timestamp() - interval '2 hours'
|
||||
)
|
||||
""",
|
||||
key,
|
||||
uuid.UUID(attachment_id),
|
||||
chat_uuid,
|
||||
filename,
|
||||
len(body),
|
||||
)
|
||||
message_id = uuid.uuid4()
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES ($1, $2, $3, $4, clock_timestamp() - interval '2 hours')
|
||||
""",
|
||||
message_id,
|
||||
chat_uuid,
|
||||
owner_uuid,
|
||||
"fault-in-use",
|
||||
)
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO message_attachments (message_id, attachment_id, position)
|
||||
VALUES ($1, $2, 0)
|
||||
""",
|
||||
message_id,
|
||||
uuid.UUID(used_id),
|
||||
)
|
||||
|
||||
s3client.delete_object(settings, stale_key)
|
||||
s3client.delete_object(settings, used_key)
|
||||
return {
|
||||
"fresh_orphan": {"attachment_id": fresh_id, "object_key": fresh_key, "note": "fresh-orphan"},
|
||||
"old_orphan": {"attachment_id": old_id, "object_key": old_key, "note": "old-orphan"},
|
||||
"stale_missing": {"attachment_id": stale_id, "object_key": stale_key, "note": "fault-stale-missing"},
|
||||
"in_use_missing": {"attachment_id": used_id, "object_key": used_key, "note": "fault-in-use-missing"},
|
||||
}
|
||||
|
||||
|
||||
async def _probe(settings, attachment_id: str | None, object_key: str | None) -> dict:
|
||||
result = {}
|
||||
if attachment_id:
|
||||
row = await pool().fetchval("SELECT 1 FROM attachments WHERE id = $1::uuid", uuid.UUID(attachment_id))
|
||||
result["metadata"] = row is not None
|
||||
if object_key:
|
||||
result["object"] = s3client.object_exists(settings, object_key)
|
||||
return result
|
||||
|
||||
|
||||
def _anonymous_status(url: str) -> int:
|
||||
request = urllib.request.Request(url, method="GET")
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=5) as response:
|
||||
return response.status
|
||||
except urllib.error.HTTPError as exc:
|
||||
return exc.code
|
||||
|
||||
|
||||
async def _check_private(settings) -> dict:
|
||||
endpoint = settings.s3_endpoint.rstrip("/")
|
||||
object_status = _anonymous_status(f"{endpoint}/{settings.s3_bucket}/o/private-probe-missing")
|
||||
list_status = _anonymous_status(f"{endpoint}/{settings.s3_bucket}?list-type=2")
|
||||
return {
|
||||
"anonymous_object_status": object_status,
|
||||
"anonymous_list_status": list_status,
|
||||
"private": object_status == 403 and list_status == 403,
|
||||
}
|
||||
|
||||
|
||||
async def _run(args) -> dict:
|
||||
settings = load_settings()
|
||||
await _prepare(settings)
|
||||
try:
|
||||
if args.cmd == "reconcile":
|
||||
if args.apply and args.dry_run:
|
||||
raise SystemExit("choose either --apply or --dry-run")
|
||||
return await reconcile(settings, apply=bool(args.apply))
|
||||
if args.cmd == "inject":
|
||||
return await _inject(settings, args.chat_id, args.owner_id)
|
||||
if args.cmd == "probe":
|
||||
return await _probe(settings, args.attachment_id, args.object_key)
|
||||
if args.cmd == "check-private":
|
||||
return await _check_private(settings)
|
||||
raise SystemExit("unknown command")
|
||||
finally:
|
||||
await close()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description="Lab operator tools")
|
||||
sub = parser.add_subparsers(dest="cmd", required=True)
|
||||
reconcile_parser = sub.add_parser("reconcile")
|
||||
reconcile_parser.add_argument("--apply", action="store_true")
|
||||
reconcile_parser.add_argument("--dry-run", action="store_true")
|
||||
inject_parser = sub.add_parser("inject")
|
||||
inject_parser.add_argument("--chat-id", required=True)
|
||||
inject_parser.add_argument("--owner-id", required=True)
|
||||
probe_parser = sub.add_parser("probe")
|
||||
probe_parser.add_argument("--attachment-id")
|
||||
probe_parser.add_argument("--object-key")
|
||||
sub.add_parser("check-private")
|
||||
args = parser.parse_args()
|
||||
if args.cmd == "reconcile" and not args.apply and not args.dry_run:
|
||||
args.dry_run = True
|
||||
report = asyncio.run(_run(args))
|
||||
json.dump(report, sys.stdout, ensure_ascii=False)
|
||||
sys.stdout.write("\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,58 @@
|
||||
"""Process configuration. Secrets are read from the environment, never logged."""
|
||||
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
def _required(name: str) -> str:
|
||||
value = os.environ.get(name, "").strip()
|
||||
if not value:
|
||||
raise SystemExit(f"missing required environment variable {name}")
|
||||
return value
|
||||
|
||||
|
||||
def _int(name: str, default: int) -> int:
|
||||
raw = os.environ.get(name)
|
||||
if raw is None or raw.strip() == "":
|
||||
return default
|
||||
try:
|
||||
return int(raw)
|
||||
except ValueError as exc:
|
||||
raise SystemExit(f"environment variable {name} must be an integer") from exc
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Settings:
|
||||
instance_id: str
|
||||
database_url: str
|
||||
s3_endpoint: str
|
||||
s3_region: str
|
||||
s3_bucket: str
|
||||
s3_access_key: str
|
||||
s3_secret_key: str
|
||||
session_ttl_seconds: int
|
||||
idempotency_ttl_seconds: int
|
||||
max_upload_bytes: int
|
||||
max_image_pixels: int
|
||||
orphan_grace_seconds: int
|
||||
app_env: str
|
||||
# Full bitmap decode is bounded so one upload cannot expand to 40e6 pixels in RAM.
|
||||
full_decode_pixels: int = 1_000_000
|
||||
|
||||
|
||||
def load_settings() -> Settings:
|
||||
return Settings(
|
||||
instance_id=_required("INSTANCE_ID"),
|
||||
database_url=_required("DATABASE_URL"),
|
||||
s3_endpoint=_required("S3_ENDPOINT"),
|
||||
s3_region=os.environ.get("S3_REGION", "us-east-1").strip() or "us-east-1",
|
||||
s3_bucket=_required("S3_BUCKET"),
|
||||
s3_access_key=_required("S3_ACCESS_KEY_ID"),
|
||||
s3_secret_key=_required("S3_SECRET_ACCESS_KEY"),
|
||||
session_ttl_seconds=_int("SESSION_TTL_SECONDS", 3600),
|
||||
idempotency_ttl_seconds=_int("IDEMPOTENCY_TTL_SECONDS", 86400),
|
||||
max_upload_bytes=_int("MAX_UPLOAD_BYTES", 10_485_760),
|
||||
max_image_pixels=_int("MAX_IMAGE_PIXELS", 40_000_000),
|
||||
orphan_grace_seconds=_int("ORPHAN_GRACE_SECONDS", 120),
|
||||
app_env=os.environ.get("APP_ENV", "lab").strip() or "lab",
|
||||
)
|
||||
@@ -0,0 +1,61 @@
|
||||
"""PostgreSQL pool, JSON codec, and idempotent schema migration."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import asyncpg
|
||||
|
||||
from app.config import Settings
|
||||
|
||||
_pool: asyncpg.Pool | None = None
|
||||
_MIGRATION = Path(__file__).resolve().parents[1] / "infra" / "migrate.sql"
|
||||
|
||||
|
||||
async def _init_connection(conn: asyncpg.Connection) -> None:
|
||||
await conn.execute("SET TIME ZONE 'UTC'")
|
||||
await conn.execute("SET statement_timeout = '30s'")
|
||||
await conn.set_type_codec(
|
||||
"jsonb",
|
||||
encoder=json.dumps,
|
||||
decoder=json.loads,
|
||||
schema="pg_catalog",
|
||||
format="text",
|
||||
)
|
||||
|
||||
|
||||
async def connect(settings: Settings) -> asyncpg.Pool:
|
||||
global _pool
|
||||
if _pool is None:
|
||||
_pool = await asyncpg.create_pool(
|
||||
settings.database_url,
|
||||
min_size=1,
|
||||
max_size=12,
|
||||
timeout=10,
|
||||
command_timeout=30,
|
||||
init=_init_connection,
|
||||
)
|
||||
return _pool
|
||||
|
||||
|
||||
async def migrate(settings: Settings) -> None:
|
||||
pool = await connect(settings)
|
||||
sql = _MIGRATION.read_text(encoding="utf-8")
|
||||
statements = [part.strip() for part in sql.split(";") if part.strip()]
|
||||
async with pool.acquire() as conn:
|
||||
async with conn.transaction():
|
||||
await conn.execute("SELECT pg_advisory_xact_lock(874521)")
|
||||
for statement in statements:
|
||||
await conn.execute(statement)
|
||||
|
||||
|
||||
async def close() -> None:
|
||||
global _pool
|
||||
if _pool is not None:
|
||||
await _pool.close()
|
||||
_pool = None
|
||||
|
||||
|
||||
def pool() -> asyncpg.Pool:
|
||||
if _pool is None:
|
||||
raise RuntimeError("database pool is not connected")
|
||||
return _pool
|
||||
@@ -0,0 +1,23 @@
|
||||
"""API errors mapped to the contract body. Details stay in server logs."""
|
||||
|
||||
|
||||
class ApiError(Exception):
|
||||
def __init__(self, status: int, code: str, message: str, headers: dict | None = None):
|
||||
super().__init__(message)
|
||||
self.status = status
|
||||
self.code = code
|
||||
self.message = message
|
||||
self.headers = headers or {}
|
||||
|
||||
|
||||
def unauthorized(scheme: str) -> ApiError:
|
||||
if scheme == "basic":
|
||||
challenge = 'Basic realm="messenger", charset="UTF-8"'
|
||||
else:
|
||||
challenge = 'Bearer realm="messenger"'
|
||||
return ApiError(
|
||||
401,
|
||||
"unauthorized",
|
||||
"Требуется действительная аутентификация",
|
||||
{"WWW-Authenticate": challenge},
|
||||
)
|
||||
@@ -0,0 +1,92 @@
|
||||
"""Bounded PNG/JPEG checks. Pixel count is taken from headers before bitmap decode."""
|
||||
|
||||
from PIL import Image, ImageFile, UnidentifiedImageError
|
||||
|
||||
from app.errors import ApiError
|
||||
|
||||
ImageFile.LOAD_TRUNCATED_IMAGES = False
|
||||
|
||||
_PNG = b"\x89PNG\r\n\x1a\n"
|
||||
_JPEG_SOF = {0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF}
|
||||
|
||||
|
||||
def _png_size(path: str) -> tuple[int, int] | None:
|
||||
with open(path, "rb") as handle:
|
||||
if handle.read(8) != _PNG:
|
||||
return None
|
||||
length = handle.read(4)
|
||||
kind = handle.read(4)
|
||||
if kind != b"IHDR" or len(length) != 4 or int.from_bytes(length, "big") < 13:
|
||||
return None
|
||||
header = handle.read(8)
|
||||
if len(header) != 8:
|
||||
return None
|
||||
width = int.from_bytes(header[0:4], "big")
|
||||
height = int.from_bytes(header[4:8], "big")
|
||||
return width, height
|
||||
|
||||
|
||||
def _jpeg_size(path: str) -> tuple[int, int] | None:
|
||||
with open(path, "rb") as handle:
|
||||
if handle.read(2) != b"\xff\xd8":
|
||||
return None
|
||||
while True:
|
||||
marker_byte = handle.read(1)
|
||||
if marker_byte != b"\xff":
|
||||
return None
|
||||
while marker_byte == b"\xff":
|
||||
marker_byte = handle.read(1)
|
||||
if not marker_byte:
|
||||
return None
|
||||
marker = marker_byte[0]
|
||||
if marker in {0xD8, 0xD9, 0x01} or 0xD0 <= marker <= 0xD7:
|
||||
continue
|
||||
length_bytes = handle.read(2)
|
||||
if len(length_bytes) != 2:
|
||||
return None
|
||||
length = int.from_bytes(length_bytes, "big")
|
||||
if length < 2:
|
||||
return None
|
||||
if marker in _JPEG_SOF:
|
||||
payload = handle.read(length - 2)
|
||||
if len(payload) < 5:
|
||||
return None
|
||||
height = int.from_bytes(payload[1:3], "big")
|
||||
width = int.from_bytes(payload[3:5], "big")
|
||||
return width, height
|
||||
handle.seek(length - 2, 1)
|
||||
|
||||
|
||||
def _detect(path: str) -> str | None:
|
||||
with open(path, "rb") as handle:
|
||||
header = handle.read(12)
|
||||
if header.startswith(_PNG):
|
||||
return "image/png"
|
||||
if header.startswith(b"\xff\xd8\xff"):
|
||||
return "image/jpeg"
|
||||
return None
|
||||
|
||||
|
||||
def validate_image(path: str, declared: str, max_pixels: int, full_decode_pixels: int) -> None:
|
||||
detected = _detect(path)
|
||||
if detected is None or detected != declared:
|
||||
raise ApiError(415, "unsupported_media_type", "Файл не является PNG или JPEG заявленного типа")
|
||||
size = _png_size(path) if detected == "image/png" else _jpeg_size(path)
|
||||
if size is None:
|
||||
raise ApiError(415, "unsupported_media_type", "Не удалось прочитать размеры изображения")
|
||||
width, height = size
|
||||
if width <= 0 or height <= 0:
|
||||
raise ApiError(415, "unsupported_media_type", "Некорректные размеры изображения")
|
||||
if width > max_pixels or height > max_pixels or width * height > max_pixels:
|
||||
raise ApiError(413, "payload_too_large", "Изображение превышает лимит пикселей")
|
||||
Image.MAX_IMAGE_PIXELS = max_pixels
|
||||
try:
|
||||
with Image.open(path) as image:
|
||||
image.verify()
|
||||
if width * height <= full_decode_pixels:
|
||||
with Image.open(path) as image:
|
||||
image.load()
|
||||
except Image.DecompressionBombError as exc:
|
||||
raise ApiError(413, "payload_too_large", "Изображение превышает лимит пикселей") from exc
|
||||
except (UnidentifiedImageError, OSError, SyntaxError, ValueError) as exc:
|
||||
raise ApiError(415, "unsupported_media_type", "Повреждённое или неподдерживаемое изображение") from exc
|
||||
+792
@@ -0,0 +1,792 @@
|
||||
"""Users, sessions, chats, messages, and synchronous attachment upload."""
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import tempfile
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import asyncpg
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import VerifyMismatchError, VerificationError, InvalidHashError
|
||||
|
||||
from app.config import Settings
|
||||
from app.db import pool
|
||||
from app.errors import ApiError, unauthorized
|
||||
from app.images import validate_image
|
||||
from app import s3client
|
||||
|
||||
logger = logging.getLogger("messenger")
|
||||
|
||||
_HASHER = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1)
|
||||
_DUMMY_HASH = _HASHER.hash("timing-only-not-a-login-secret")
|
||||
_USERNAME = re.compile(r"^[a-z0-9_]{3,32}$")
|
||||
_IDEMPOTENCY = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
|
||||
_CONTROLS = set(range(32))
|
||||
|
||||
|
||||
def iso(value: datetime) -> str:
|
||||
if value.tzinfo is None:
|
||||
value = value.replace(tzinfo=timezone.utc)
|
||||
else:
|
||||
value = value.astimezone(timezone.utc)
|
||||
return value.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
|
||||
|
||||
|
||||
def parse_iso(value: str) -> datetime:
|
||||
if not isinstance(value, str) or not value.endswith("Z"):
|
||||
raise ValueError("timestamp")
|
||||
return datetime.fromisoformat(value[:-1] + "+00:00")
|
||||
|
||||
|
||||
def parse_uuid(value: str) -> str:
|
||||
try:
|
||||
return str(uuid.UUID(str(value)))
|
||||
except (ValueError, AttributeError, TypeError) as exc:
|
||||
raise ApiError(400, "invalid_request", "Некорректный идентификатор") from exc
|
||||
|
||||
|
||||
def _code_points(value: str) -> int:
|
||||
return len(value)
|
||||
|
||||
|
||||
def _require_object(data, allowed: set[str], required: set[str]) -> None:
|
||||
if not isinstance(data, dict):
|
||||
raise ApiError(400, "invalid_request", "Ожидается JSON-объект")
|
||||
extra = set(data) - allowed
|
||||
if extra:
|
||||
raise ApiError(400, "invalid_request", "Неизвестные поля")
|
||||
missing = required - set(data)
|
||||
if missing:
|
||||
raise ApiError(400, "invalid_request", "Отсутствуют обязательные поля")
|
||||
|
||||
|
||||
def _nonblank(value: str) -> bool:
|
||||
return value.strip() != ""
|
||||
|
||||
|
||||
def _lock_keys(scope: str) -> tuple[int, int]:
|
||||
digest = hashlib.sha256(scope.encode("utf-8")).digest()
|
||||
return int.from_bytes(digest[0:4], "big") & 0x7FFFFFFF, int.from_bytes(digest[4:8], "big") & 0x7FFFFFFF
|
||||
|
||||
|
||||
def _cursor_encode(payload: dict) -> str:
|
||||
raw = json.dumps(payload, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
|
||||
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
|
||||
|
||||
|
||||
def _cursor_decode(raw: str) -> dict:
|
||||
if not isinstance(raw, str) or raw == "":
|
||||
raise ApiError(400, "invalid_request", "Некорректный cursor")
|
||||
padding = "=" * (-len(raw) % 4)
|
||||
try:
|
||||
data = json.loads(base64.urlsafe_b64decode(raw + padding).decode("utf-8"))
|
||||
except (ValueError, UnicodeError, json.JSONDecodeError) as exc:
|
||||
raise ApiError(400, "invalid_request", "Некорректный cursor") from exc
|
||||
if not isinstance(data, dict):
|
||||
raise ApiError(400, "invalid_request", "Некорректный cursor")
|
||||
return data
|
||||
|
||||
|
||||
def user_dict(row) -> dict:
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"username": row["username"],
|
||||
"display_name": row["display_name"],
|
||||
"created_at": iso(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
def message_dict(row, attachment_ids: list[str]) -> dict:
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"chat_id": str(row["chat_id"]),
|
||||
"sender_id": str(row["sender_id"]),
|
||||
"text": row["text"],
|
||||
"created_at": iso(row["created_at"]),
|
||||
"attachment_ids": attachment_ids,
|
||||
}
|
||||
|
||||
|
||||
def attachment_dict(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": None,
|
||||
"created_at": iso(row["created_at"]),
|
||||
"updated_at": iso(row["updated_at"]),
|
||||
}
|
||||
|
||||
|
||||
async def _attachments_for(conn, message_ids: list) -> dict[str, list[str]]:
|
||||
grouped: dict[str, list[str]] = {str(item): [] for item in message_ids}
|
||||
if not message_ids:
|
||||
return grouped
|
||||
rows = await conn.fetch(
|
||||
"""
|
||||
SELECT message_id, attachment_id
|
||||
FROM message_attachments
|
||||
WHERE message_id = ANY($1::uuid[])
|
||||
ORDER BY message_id, position
|
||||
""",
|
||||
message_ids,
|
||||
)
|
||||
for row in rows:
|
||||
grouped.setdefault(str(row["message_id"]), []).append(str(row["attachment_id"]))
|
||||
return grouped
|
||||
|
||||
|
||||
async def _members_for(conn, chat_ids: list) -> dict[str, list[str]]:
|
||||
grouped: dict[str, list[str]] = {str(item): [] for item in chat_ids}
|
||||
if not chat_ids:
|
||||
return grouped
|
||||
rows = await conn.fetch(
|
||||
"""
|
||||
SELECT chat_id, user_id
|
||||
FROM chat_members
|
||||
WHERE chat_id = ANY($1::uuid[])
|
||||
ORDER BY chat_id, position
|
||||
""",
|
||||
chat_ids,
|
||||
)
|
||||
for row in rows:
|
||||
grouped.setdefault(str(row["chat_id"]), []).append(str(row["user_id"]))
|
||||
return grouped
|
||||
|
||||
|
||||
def chat_dict(row, member_ids: list[str]) -> dict:
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"title": row["title"],
|
||||
"member_ids": member_ids,
|
||||
"created_at": iso(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
async def register_user(body: dict) -> dict:
|
||||
_require_object(body, {"username", "display_name", "password"}, {"username", "display_name", "password"})
|
||||
username = body["username"]
|
||||
display_name = body["display_name"]
|
||||
password = body["password"]
|
||||
if not isinstance(username, str) or _USERNAME.fullmatch(username) is None:
|
||||
raise ApiError(400, "invalid_request", "Некорректное имя пользователя")
|
||||
if not isinstance(display_name, str) or not _nonblank(display_name) or _code_points(display_name) > 100:
|
||||
raise ApiError(400, "invalid_request", "Некорректное отображаемое имя")
|
||||
if not isinstance(password, str) or not (12 <= _code_points(password) <= 128) or "\x00" in password:
|
||||
raise ApiError(400, "invalid_request", "Некорректный пароль")
|
||||
password_hash = _HASHER.hash(password)
|
||||
try:
|
||||
row = await pool().fetchrow(
|
||||
"""
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES ($1, $2, $3, $4, clock_timestamp())
|
||||
RETURNING id, username, display_name, created_at
|
||||
""",
|
||||
uuid.uuid4(),
|
||||
username,
|
||||
display_name,
|
||||
password_hash,
|
||||
)
|
||||
except asyncpg.UniqueViolationError as exc:
|
||||
raise ApiError(409, "conflict", "Имя пользователя занято") from exc
|
||||
return user_dict(row)
|
||||
|
||||
|
||||
async def create_session(username: str, password: str, settings: Settings) -> dict:
|
||||
if not isinstance(username, str) or _USERNAME.fullmatch(username) is None:
|
||||
raise unauthorized("basic")
|
||||
if not isinstance(password, str) or "\x00" in password:
|
||||
raise unauthorized("basic")
|
||||
row = await pool().fetchrow(
|
||||
"""
|
||||
SELECT id, username, display_name, created_at, password_hash
|
||||
FROM users
|
||||
WHERE username = $1
|
||||
""",
|
||||
username,
|
||||
)
|
||||
if row is None:
|
||||
try:
|
||||
_HASHER.verify(_DUMMY_HASH, password)
|
||||
except (VerifyMismatchError, VerificationError, InvalidHashError):
|
||||
pass
|
||||
raise unauthorized("basic")
|
||||
try:
|
||||
ok = _HASHER.verify(row["password_hash"], password)
|
||||
except (VerifyMismatchError, VerificationError, InvalidHashError):
|
||||
ok = False
|
||||
if not ok:
|
||||
raise unauthorized("basic")
|
||||
token = secrets.token_urlsafe(32)
|
||||
token_hash = hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||
expires = await pool().fetchval(
|
||||
"""
|
||||
INSERT INTO sessions (token_hash, user_id, expires_at)
|
||||
VALUES ($1, $2, clock_timestamp() + make_interval(secs => $3::int))
|
||||
RETURNING expires_at
|
||||
""",
|
||||
token_hash,
|
||||
row["id"],
|
||||
settings.session_ttl_seconds,
|
||||
)
|
||||
return {
|
||||
"token": token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": iso(expires),
|
||||
"user": user_dict(row),
|
||||
}
|
||||
|
||||
|
||||
async def authenticate(token: str) -> dict:
|
||||
if not token:
|
||||
raise unauthorized("bearer")
|
||||
token_hash = hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||
row = await pool().fetchrow(
|
||||
"""
|
||||
SELECT 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,
|
||||
)
|
||||
if row is None:
|
||||
raise unauthorized("bearer")
|
||||
return user_dict(row)
|
||||
|
||||
|
||||
async def revoke_session(token: str) -> None:
|
||||
token_hash = hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||
await pool().execute(
|
||||
"""
|
||||
UPDATE sessions
|
||||
SET revoked_at = clock_timestamp()
|
||||
WHERE token_hash = $1 AND revoked_at IS NULL
|
||||
""",
|
||||
token_hash,
|
||||
)
|
||||
|
||||
|
||||
async def create_chat(user_id: str, body: dict) -> dict:
|
||||
_require_object(body, {"title", "member_ids"}, {"title", "member_ids"})
|
||||
title = body["title"]
|
||||
member_ids = body["member_ids"]
|
||||
if not isinstance(title, str) or not _nonblank(title) or _code_points(title) > 100 or "\x00" in title:
|
||||
raise ApiError(400, "invalid_request", "Некорректное название чата")
|
||||
if not isinstance(member_ids, list) or not (1 <= len(member_ids) <= 100):
|
||||
raise ApiError(400, "invalid_request", "Некорректный список участников")
|
||||
canonical = []
|
||||
for item in member_ids:
|
||||
if not isinstance(item, str):
|
||||
raise ApiError(400, "invalid_request", "Некорректный список участников")
|
||||
canonical.append(parse_uuid(item))
|
||||
if len(canonical) != len(set(canonical)):
|
||||
raise ApiError(400, "invalid_request", "Список участников содержит дубликаты")
|
||||
if user_id not in canonical:
|
||||
raise ApiError(400, "invalid_request", "Создатель должен входить в список участников")
|
||||
member_uuids = [uuid.UUID(item) for item in canonical]
|
||||
async with pool().acquire() as conn:
|
||||
async with conn.transaction():
|
||||
found = await conn.fetch("SELECT id FROM users WHERE id = ANY($1::uuid[])", member_uuids)
|
||||
if len(found) != len(canonical):
|
||||
raise ApiError(400, "invalid_request", "Участник не найден")
|
||||
row = await conn.fetchrow(
|
||||
"""
|
||||
INSERT INTO chats (id, title, created_at)
|
||||
VALUES ($1, $2, clock_timestamp())
|
||||
RETURNING id, title, created_at
|
||||
""",
|
||||
uuid.uuid4(),
|
||||
title,
|
||||
)
|
||||
for position, member_id in enumerate(member_uuids):
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO chat_members (chat_id, user_id, position)
|
||||
VALUES ($1, $2, $3)
|
||||
""",
|
||||
row["id"],
|
||||
member_id,
|
||||
position,
|
||||
)
|
||||
return chat_dict(row, canonical)
|
||||
|
||||
|
||||
def parse_limit(raw: str | None) -> int:
|
||||
if raw is None:
|
||||
return 50
|
||||
if not re.fullmatch(r"[1-9][0-9]*", raw):
|
||||
raise ApiError(400, "invalid_request", "Некорректный limit")
|
||||
value = int(raw)
|
||||
if value > 100:
|
||||
raise ApiError(400, "invalid_request", "Некорректный limit")
|
||||
return value
|
||||
|
||||
|
||||
async def list_chats(user_id: str, limit: int, cursor: str | None) -> dict:
|
||||
created_at = None
|
||||
cursor_id = None
|
||||
if cursor is not None:
|
||||
payload = _cursor_decode(cursor)
|
||||
if payload.get("kind") != "chat" or payload.get("user_id") != user_id:
|
||||
raise ApiError(400, "invalid_request", "Некорректный cursor")
|
||||
try:
|
||||
created_at = parse_iso(payload["created_at"])
|
||||
cursor_id = uuid.UUID(parse_uuid(payload["id"]))
|
||||
except (KeyError, ValueError, TypeError) as exc:
|
||||
raise ApiError(400, "invalid_request", "Некорректный cursor") from exc
|
||||
rows = await pool().fetch(
|
||||
"""
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $1
|
||||
WHERE ($2::timestamptz IS NULL OR (c.created_at, c.id) > ($2, $3))
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $4
|
||||
""",
|
||||
uuid.UUID(user_id),
|
||||
created_at,
|
||||
cursor_id,
|
||||
limit + 1,
|
||||
)
|
||||
has_more = len(rows) > limit
|
||||
rows = rows[:limit]
|
||||
members = await _members_for(pool(), [row["id"] for row in rows])
|
||||
items = [chat_dict(row, members.get(str(row["id"]), [])) for row in rows]
|
||||
next_cursor = None
|
||||
if has_more and rows:
|
||||
last = rows[-1]
|
||||
next_cursor = _cursor_encode(
|
||||
{
|
||||
"v": 1,
|
||||
"kind": "chat",
|
||||
"user_id": user_id,
|
||||
"created_at": iso(last["created_at"]),
|
||||
"id": str(last["id"]),
|
||||
}
|
||||
)
|
||||
return {"items": items, "next_cursor": next_cursor}
|
||||
|
||||
|
||||
async def get_chat(user_id: str, chat_id: str) -> dict:
|
||||
chat_uuid = uuid.UUID(parse_uuid(chat_id))
|
||||
row = await pool().fetchrow(
|
||||
"""
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $2
|
||||
WHERE c.id = $1
|
||||
""",
|
||||
chat_uuid,
|
||||
uuid.UUID(user_id),
|
||||
)
|
||||
if row is None:
|
||||
raise ApiError(404, "not_found", "Объект не найден")
|
||||
members = await _members_for(pool(), [row["id"]])
|
||||
return chat_dict(row, members.get(str(row["id"]), []))
|
||||
|
||||
|
||||
def _message_parts(body: dict) -> tuple[str, list[str]]:
|
||||
_require_object(body, {"text", "attachment_ids"}, {"text"})
|
||||
text = body["text"]
|
||||
if not isinstance(text, str) or "\x00" in text or _code_points(text) > 4000:
|
||||
raise ApiError(400, "invalid_request", "Некорректный текст сообщения")
|
||||
raw_ids = body.get("attachment_ids", [])
|
||||
if raw_ids is None or not isinstance(raw_ids, list) or len(raw_ids) > 10:
|
||||
raise ApiError(400, "invalid_request", "Некорректный список вложений")
|
||||
attachment_ids = []
|
||||
for item in raw_ids:
|
||||
if not isinstance(item, str):
|
||||
raise ApiError(400, "invalid_request", "Некорректный список вложений")
|
||||
attachment_ids.append(parse_uuid(item))
|
||||
if len(attachment_ids) != len(set(attachment_ids)):
|
||||
raise ApiError(400, "invalid_request", "Список вложений содержит дубликаты")
|
||||
if not _nonblank(text) and not attachment_ids:
|
||||
raise ApiError(400, "invalid_request", "Пустое сообщение")
|
||||
return text, attachment_ids
|
||||
|
||||
|
||||
def _canonical_hash(text: str, attachment_ids: list[str]) -> str:
|
||||
payload = json.dumps(
|
||||
{"attachment_ids": attachment_ids, "text": text},
|
||||
ensure_ascii=False,
|
||||
sort_keys=True,
|
||||
separators=(",", ":"),
|
||||
)
|
||||
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
async def create_message(user_id: str, chat_id: str, body: dict, idem_key: str | None, settings: Settings) -> dict:
|
||||
chat_id = parse_uuid(chat_id)
|
||||
if idem_key is None or _IDEMPOTENCY.fullmatch(idem_key) is None:
|
||||
raise ApiError(400, "invalid_request", "Требуется корректный Idempotency-Key")
|
||||
text, attachment_ids = _message_parts(body)
|
||||
request_hash = _canonical_hash(text, attachment_ids)
|
||||
path = f"/api/v1/chats/{chat_id}/messages"
|
||||
k1, k2 = _lock_keys(f"{user_id}|POST|{path}|{idem_key}")
|
||||
async with pool().acquire() as conn:
|
||||
async with conn.transaction():
|
||||
await conn.execute("SELECT pg_advisory_xact_lock($1::int, $2::int)", k1, k2)
|
||||
member = await conn.fetchval(
|
||||
"SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2",
|
||||
uuid.UUID(chat_id),
|
||||
uuid.UUID(user_id),
|
||||
)
|
||||
if member is None:
|
||||
raise ApiError(404, "not_found", "Объект не найден")
|
||||
existing = await conn.fetchrow(
|
||||
"""
|
||||
SELECT request_hash, response_json,
|
||||
created_at > clock_timestamp() - make_interval(secs => $4::int) AS fresh
|
||||
FROM idempotency
|
||||
WHERE user_id = $1 AND http_method = 'POST' AND path = $2 AND idem_key = $3
|
||||
""",
|
||||
uuid.UUID(user_id),
|
||||
path,
|
||||
idem_key,
|
||||
settings.idempotency_ttl_seconds,
|
||||
)
|
||||
if existing is not None and existing["fresh"]:
|
||||
if existing["request_hash"] != request_hash:
|
||||
raise ApiError(409, "conflict", "Ключ идемпотентности уже использован")
|
||||
stored = existing["response_json"]
|
||||
if isinstance(stored, str):
|
||||
stored = json.loads(stored)
|
||||
return stored
|
||||
if existing is not None and not existing["fresh"]:
|
||||
await conn.execute(
|
||||
"""
|
||||
DELETE FROM idempotency
|
||||
WHERE user_id = $1 AND http_method = 'POST' AND path = $2 AND idem_key = $3
|
||||
""",
|
||||
uuid.UUID(user_id),
|
||||
path,
|
||||
idem_key,
|
||||
)
|
||||
if attachment_ids:
|
||||
found = await conn.fetch(
|
||||
"SELECT id, chat_id, status FROM attachments WHERE id = ANY($1::uuid[])",
|
||||
[uuid.UUID(item) for item in attachment_ids],
|
||||
)
|
||||
by_id = {str(row["id"]): row for row in found}
|
||||
if len(by_id) != len(attachment_ids):
|
||||
raise ApiError(404, "not_found", "Объект не найден")
|
||||
for attachment_id in attachment_ids:
|
||||
row = by_id[attachment_id]
|
||||
if str(row["chat_id"]) != chat_id or row["status"] != "ready":
|
||||
if str(row["chat_id"]) != chat_id:
|
||||
raise ApiError(404, "not_found", "Объект не найден")
|
||||
raise ApiError(409, "conflict", "Вложение нельзя прикрепить")
|
||||
message = await conn.fetchrow(
|
||||
"""
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES ($1, $2, $3, $4, clock_timestamp())
|
||||
RETURNING id, chat_id, sender_id, text, created_at
|
||||
""",
|
||||
uuid.uuid4(),
|
||||
uuid.UUID(chat_id),
|
||||
uuid.UUID(user_id),
|
||||
text,
|
||||
)
|
||||
for position, attachment_id in enumerate(attachment_ids):
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO message_attachments (message_id, attachment_id, position)
|
||||
VALUES ($1, $2, $3)
|
||||
""",
|
||||
message["id"],
|
||||
uuid.UUID(attachment_id),
|
||||
position,
|
||||
)
|
||||
payload = message_dict(message, attachment_ids)
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO idempotency (
|
||||
user_id, http_method, path, idem_key, request_hash, status_code, response_json, created_at
|
||||
)
|
||||
VALUES ($1, 'POST', $2, $3, $4, 201, $5::jsonb, clock_timestamp())
|
||||
""",
|
||||
uuid.UUID(user_id),
|
||||
path,
|
||||
idem_key,
|
||||
request_hash,
|
||||
payload,
|
||||
)
|
||||
return payload
|
||||
|
||||
|
||||
async def list_messages(user_id: str, chat_id: str, limit: int, cursor: str | None) -> dict:
|
||||
chat_id = parse_uuid(chat_id)
|
||||
member = await pool().fetchval(
|
||||
"SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2",
|
||||
uuid.UUID(chat_id),
|
||||
uuid.UUID(user_id),
|
||||
)
|
||||
if member is None:
|
||||
raise ApiError(404, "not_found", "Объект не найден")
|
||||
created_at = None
|
||||
cursor_id = None
|
||||
if cursor is not None:
|
||||
payload = _cursor_decode(cursor)
|
||||
if payload.get("kind") != "message" or payload.get("chat_id") != chat_id:
|
||||
raise ApiError(400, "invalid_request", "Некорректный cursor")
|
||||
try:
|
||||
created_at = parse_iso(payload["created_at"])
|
||||
cursor_id = uuid.UUID(parse_uuid(payload["id"]))
|
||||
except (KeyError, ValueError, TypeError) as exc:
|
||||
raise ApiError(400, "invalid_request", "Некорректный cursor") from exc
|
||||
rows = await pool().fetch(
|
||||
"""
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
AND ($2::timestamptz IS NULL OR (created_at, id) > ($2, $3))
|
||||
ORDER BY created_at, id
|
||||
LIMIT $4
|
||||
""",
|
||||
uuid.UUID(chat_id),
|
||||
created_at,
|
||||
cursor_id,
|
||||
limit + 1,
|
||||
)
|
||||
has_more = len(rows) > limit
|
||||
rows = rows[:limit]
|
||||
grouped = await _attachments_for(pool(), [row["id"] for row in rows])
|
||||
items = [message_dict(row, grouped.get(str(row["id"]), [])) for row in rows]
|
||||
next_cursor = None
|
||||
if has_more and rows:
|
||||
last = rows[-1]
|
||||
next_cursor = _cursor_encode(
|
||||
{
|
||||
"v": 1,
|
||||
"kind": "message",
|
||||
"chat_id": chat_id,
|
||||
"created_at": iso(last["created_at"]),
|
||||
"id": str(last["id"]),
|
||||
}
|
||||
)
|
||||
return {"items": items, "next_cursor": next_cursor}
|
||||
|
||||
|
||||
def validate_filename(filename: str | None) -> str:
|
||||
if filename is None:
|
||||
raise ApiError(400, "invalid_request", "Требуется filename")
|
||||
if not isinstance(filename, str) or not (1 <= _code_points(filename) <= 255):
|
||||
raise ApiError(400, "invalid_request", "Некорректное имя файла")
|
||||
if not _nonblank(filename) or filename in {".", ".."}:
|
||||
raise ApiError(400, "invalid_request", "Некорректное имя файла")
|
||||
for char in filename:
|
||||
code = ord(char)
|
||||
if char in {"/", "\\"} or code in _CONTROLS or code == 127:
|
||||
raise ApiError(400, "invalid_request", "Некорректное имя файла")
|
||||
return filename
|
||||
|
||||
|
||||
def _media_type(value: str | None) -> str:
|
||||
if not value:
|
||||
raise ApiError(415, "unsupported_media_type", "Требуется image/png или image/jpeg")
|
||||
media = value.split(";", 1)[0].strip().lower()
|
||||
if media not in {"image/png", "image/jpeg"}:
|
||||
raise ApiError(415, "unsupported_media_type", "Поддерживаются только image/png и image/jpeg")
|
||||
return media
|
||||
|
||||
|
||||
async def _mark_ledger(key: str, state: str) -> None:
|
||||
await pool().execute(
|
||||
"""
|
||||
UPDATE object_ledger
|
||||
SET state = $2, updated_at = clock_timestamp()
|
||||
WHERE object_key = $1
|
||||
""",
|
||||
key,
|
||||
state,
|
||||
)
|
||||
|
||||
|
||||
async def _compensate(settings: Settings, key: str) -> None:
|
||||
"""Drop a staged object after a failed metadata commit. A failed delete stays for the reconciler."""
|
||||
try:
|
||||
await _to_thread(s3client.delete_object, settings, key)
|
||||
await _mark_ledger(key, "aborted")
|
||||
except Exception:
|
||||
logger.exception("compensation failed for staged object; reconciler will retry after the grace period")
|
||||
|
||||
|
||||
async def _to_thread(func, *args):
|
||||
import asyncio
|
||||
|
||||
return await asyncio.to_thread(func, *args)
|
||||
|
||||
|
||||
async def upload_attachment(
|
||||
user_id: str,
|
||||
chat_id: str,
|
||||
filename: str | None,
|
||||
content_type_header: str | None,
|
||||
content_length: str | None,
|
||||
byte_iter,
|
||||
settings: Settings,
|
||||
) -> dict:
|
||||
chat_id = parse_uuid(chat_id)
|
||||
member = await pool().fetchval(
|
||||
"SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2",
|
||||
uuid.UUID(chat_id),
|
||||
uuid.UUID(user_id),
|
||||
)
|
||||
if member is None:
|
||||
raise ApiError(404, "not_found", "Объект не найден")
|
||||
filename = validate_filename(filename)
|
||||
media = _media_type(content_type_header)
|
||||
if content_length is not None and not re.fullmatch(r"\d+", content_length):
|
||||
raise ApiError(400, "invalid_request", "Некорректный Content-Length")
|
||||
attachment_id = str(uuid.uuid4())
|
||||
object_key = f"o/{attachment_id}"
|
||||
os.makedirs("/tmp/uploads", exist_ok=True)
|
||||
fd, temp_path = tempfile.mkstemp(prefix="up-", dir="/tmp/uploads")
|
||||
os.close(fd)
|
||||
digest = hashlib.sha256()
|
||||
size = 0
|
||||
try:
|
||||
with open(temp_path, "wb") as handle:
|
||||
async for chunk in byte_iter:
|
||||
if not chunk:
|
||||
continue
|
||||
size += len(chunk)
|
||||
if size > settings.max_upload_bytes:
|
||||
raise ApiError(413, "payload_too_large", "Файл превышает 10 МиБ")
|
||||
digest.update(chunk)
|
||||
handle.write(chunk)
|
||||
if size < 1:
|
||||
raise ApiError(415, "unsupported_media_type", "Пустой файл")
|
||||
await _to_thread(
|
||||
validate_image,
|
||||
temp_path,
|
||||
media,
|
||||
settings.max_image_pixels,
|
||||
settings.full_decode_pixels,
|
||||
)
|
||||
sha256 = digest.hexdigest()
|
||||
await pool().execute(
|
||||
"""
|
||||
INSERT INTO object_ledger (
|
||||
object_key, attachment_id, chat_id, state, note, size_bytes, created_at, updated_at
|
||||
)
|
||||
VALUES ($1, $2, $3, 'staging', 'upload', $4, clock_timestamp(), clock_timestamp())
|
||||
""",
|
||||
object_key,
|
||||
uuid.UUID(attachment_id),
|
||||
uuid.UUID(chat_id),
|
||||
size,
|
||||
)
|
||||
try:
|
||||
await _to_thread(s3client.put_file, settings, object_key, temp_path, media, size)
|
||||
except Exception:
|
||||
await _compensate(settings, object_key)
|
||||
raise
|
||||
try:
|
||||
async with pool().acquire() as conn:
|
||||
async with conn.transaction():
|
||||
row = await conn.fetchrow(
|
||||
"""
|
||||
INSERT INTO attachments (
|
||||
id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||||
status, object_key, error_code, created_at, updated_at
|
||||
)
|
||||
VALUES (
|
||||
$1, $2, $3, $4, $5, $6, $7, 'ready', $8, NULL,
|
||||
clock_timestamp(), clock_timestamp()
|
||||
)
|
||||
RETURNING id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||||
status, created_at, updated_at
|
||||
""",
|
||||
uuid.UUID(attachment_id),
|
||||
uuid.UUID(chat_id),
|
||||
uuid.UUID(user_id),
|
||||
filename,
|
||||
media,
|
||||
size,
|
||||
sha256,
|
||||
object_key,
|
||||
)
|
||||
updated = await conn.execute(
|
||||
"""
|
||||
UPDATE object_ledger
|
||||
SET state = 'committed', updated_at = clock_timestamp()
|
||||
WHERE object_key = $1 AND state = 'staging'
|
||||
""",
|
||||
object_key,
|
||||
)
|
||||
if not updated.endswith("1"):
|
||||
raise RuntimeError("ledger was not in staging state")
|
||||
except Exception:
|
||||
logger.exception("metadata commit failed after object upload")
|
||||
await _compensate(settings, object_key)
|
||||
raise ApiError(503, "unavailable", "Не удалось сохранить метаданные вложения")
|
||||
return attachment_dict(row)
|
||||
finally:
|
||||
try:
|
||||
os.remove(temp_path)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
async def get_attachment(user_id: str, attachment_id: str) -> dict:
|
||||
attachment_id = parse_uuid(attachment_id)
|
||||
row = await pool().fetchrow(
|
||||
"""
|
||||
SELECT a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, a.sha256,
|
||||
a.status, a.created_at, a.updated_at
|
||||
FROM attachments a
|
||||
JOIN chat_members m ON m.chat_id = a.chat_id AND m.user_id = $2
|
||||
WHERE a.id = $1
|
||||
""",
|
||||
uuid.UUID(attachment_id),
|
||||
uuid.UUID(user_id),
|
||||
)
|
||||
if row is None:
|
||||
raise ApiError(404, "not_found", "Объект не найден")
|
||||
return attachment_dict(row)
|
||||
|
||||
|
||||
async def download_attachment(user_id: str, attachment_id: str, variant: str | None, settings: Settings) -> tuple[bytes, str]:
|
||||
if variant not in {None, "original"}:
|
||||
raise ApiError(400, "invalid_request", "Некорректный variant")
|
||||
attachment_id = parse_uuid(attachment_id)
|
||||
row = await pool().fetchrow(
|
||||
"""
|
||||
SELECT a.object_key, a.content_type, a.size_bytes
|
||||
FROM attachments a
|
||||
JOIN chat_members m ON m.chat_id = a.chat_id AND m.user_id = $2
|
||||
WHERE a.id = $1
|
||||
""",
|
||||
uuid.UUID(attachment_id),
|
||||
uuid.UUID(user_id),
|
||||
)
|
||||
if row is None:
|
||||
raise ApiError(404, "not_found", "Объект не найден")
|
||||
data = await _to_thread(s3client.get_bytes, settings, row["object_key"], settings.max_upload_bytes)
|
||||
if len(data) != row["size_bytes"]:
|
||||
raise ApiError(404, "not_found", "Объект не найден")
|
||||
return data, row["content_type"]
|
||||
|
||||
|
||||
async def ready(settings: Settings) -> None:
|
||||
try:
|
||||
await pool().fetchval("SELECT 1")
|
||||
except Exception as exc:
|
||||
raise ApiError(503, "unavailable", "База данных недоступна") from exc
|
||||
await _to_thread(s3client.head_bucket, settings)
|
||||
+293
@@ -0,0 +1,293 @@
|
||||
"""HTTP API. Every response carries X-Request-Id and X-Instance-Id."""
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import contextvars
|
||||
import json
|
||||
import logging
|
||||
import uuid
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
import asyncpg
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.responses import JSONResponse, Response
|
||||
from starlette.datastructures import MutableHeaders
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
from app.config import load_settings
|
||||
from app.db import close, connect, migrate
|
||||
from app.errors import ApiError, unauthorized
|
||||
from app import logic
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
|
||||
logger = logging.getLogger("messenger")
|
||||
|
||||
settings = load_settings()
|
||||
request_id_var: contextvars.ContextVar[str] = contextvars.ContextVar("request_id", default="")
|
||||
|
||||
_ERROR_CODES = {
|
||||
400: "invalid_request",
|
||||
401: "unauthorized",
|
||||
404: "not_found",
|
||||
409: "conflict",
|
||||
413: "payload_too_large",
|
||||
415: "unsupported_media_type",
|
||||
429: "rate_limited",
|
||||
503: "unavailable",
|
||||
}
|
||||
|
||||
|
||||
def _error_body(status: int, code: str, message: str) -> dict:
|
||||
return {"error": {"code": code, "message": message, "request_id": request_id_var.get() or "error"}}
|
||||
|
||||
|
||||
def _error_response(status: int, code: str, message: str, headers: dict | None = None) -> JSONResponse:
|
||||
response = JSONResponse(status_code=status, content=_error_body(status, code, message))
|
||||
for key, value in (headers or {}).items():
|
||||
response.headers[key] = value
|
||||
return response
|
||||
|
||||
|
||||
class ContextMiddleware:
|
||||
def __init__(self, app):
|
||||
self.app = app
|
||||
|
||||
async def __call__(self, scope, receive, send):
|
||||
if scope["type"] != "http":
|
||||
await self.app(scope, receive, send)
|
||||
return
|
||||
request_id = str(uuid.uuid4())
|
||||
token = request_id_var.set(request_id)
|
||||
started = False
|
||||
|
||||
async def send_wrapper(message):
|
||||
nonlocal started
|
||||
if message["type"] == "http.response.start":
|
||||
started = True
|
||||
headers = MutableHeaders(raw=message["headers"])
|
||||
headers["X-Request-Id"] = request_id
|
||||
headers["X-Instance-Id"] = settings.instance_id
|
||||
await send(message)
|
||||
|
||||
try:
|
||||
await self.app(scope, receive, send_wrapper)
|
||||
except Exception:
|
||||
logger.exception("unhandled ASGI error")
|
||||
if not started:
|
||||
body = json.dumps(_error_body(500, "internal_error", "Внутренняя ошибка")).encode("utf-8")
|
||||
await send(
|
||||
{
|
||||
"type": "http.response.start",
|
||||
"status": 500,
|
||||
"headers": [
|
||||
(b"content-type", b"application/json"),
|
||||
(b"x-request-id", request_id.encode("ascii")),
|
||||
(b"x-instance-id", settings.instance_id.encode("utf-8")),
|
||||
],
|
||||
}
|
||||
)
|
||||
await send({"type": "http.response.body", "body": body})
|
||||
finally:
|
||||
request_id_var.reset(token)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app: FastAPI):
|
||||
delay = 1
|
||||
for attempt in range(30):
|
||||
try:
|
||||
await connect(settings)
|
||||
await migrate(settings)
|
||||
logger.info("instance %s ready to serve", settings.instance_id)
|
||||
break
|
||||
except Exception:
|
||||
logger.exception("startup attempt %s failed", attempt + 1)
|
||||
await asyncio.sleep(delay)
|
||||
delay = min(delay * 2, 5)
|
||||
else:
|
||||
raise RuntimeError("database startup failed")
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
await close()
|
||||
|
||||
|
||||
app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None, redirect_slashes=False)
|
||||
app.add_middleware(ContextMiddleware)
|
||||
|
||||
|
||||
@app.exception_handler(ApiError)
|
||||
async def handle_api_error(_request: Request, exc: ApiError):
|
||||
return _error_response(exc.status, exc.code, exc.message, exc.headers)
|
||||
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def handle_http(_request: Request, exc: StarletteHTTPException):
|
||||
status = exc.status_code if exc.status_code in _ERROR_CODES else 500
|
||||
return _error_response(status, _ERROR_CODES.get(status, "internal_error"), "Запрос отклонён")
|
||||
|
||||
|
||||
@app.exception_handler(asyncpg.PostgresConnectionError)
|
||||
async def handle_db_down(_request: Request, exc: asyncpg.PostgresConnectionError):
|
||||
logger.exception("database connection failed")
|
||||
return _error_response(503, "unavailable", "База данных недоступна")
|
||||
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def handle_unexpected(_request: Request, exc: Exception):
|
||||
logger.exception("unhandled error")
|
||||
return _error_response(500, "internal_error", "Внутренняя ошибка")
|
||||
|
||||
|
||||
def _bearer(request: Request) -> str:
|
||||
header = request.headers.get("authorization", "")
|
||||
if not header.lower().startswith("bearer "):
|
||||
raise unauthorized("bearer")
|
||||
token = header.split(" ", 1)[1].strip()
|
||||
if not token:
|
||||
raise unauthorized("bearer")
|
||||
return token
|
||||
|
||||
|
||||
def _basic(request: Request) -> tuple[str, str]:
|
||||
header = request.headers.get("authorization", "")
|
||||
if not header.lower().startswith("basic "):
|
||||
raise unauthorized("basic")
|
||||
encoded = header.split(" ", 1)[1].strip()
|
||||
try:
|
||||
decoded = base64.b64decode(encoded).decode("utf-8")
|
||||
except (ValueError, UnicodeError) as exc:
|
||||
raise unauthorized("basic") from exc
|
||||
if ":" not in decoded:
|
||||
raise unauthorized("basic")
|
||||
username, password = decoded.split(":", 1)
|
||||
return username, password
|
||||
|
||||
|
||||
async def _current_user(request: Request) -> dict:
|
||||
return await logic.authenticate(_bearer(request))
|
||||
|
||||
|
||||
async def _json_object(request: Request) -> dict:
|
||||
media = (request.headers.get("content-type") or "").split(";", 1)[0].strip().lower()
|
||||
if media != "application/json":
|
||||
raise ApiError(400, "invalid_request", "Ожидается application/json")
|
||||
raw = bytearray()
|
||||
async for chunk in request.stream():
|
||||
if len(raw) + len(chunk) > 65536:
|
||||
raise ApiError(413, "payload_too_large", "Тело запроса слишком большое")
|
||||
raw.extend(chunk)
|
||||
try:
|
||||
data = json.loads(bytes(raw) if raw else b"")
|
||||
except (json.JSONDecodeError, UnicodeError) as exc:
|
||||
raise ApiError(400, "invalid_request", "Некорректный JSON") from exc
|
||||
if not isinstance(data, dict):
|
||||
raise ApiError(400, "invalid_request", "Ожидается JSON-объект")
|
||||
return data
|
||||
|
||||
|
||||
@app.get("/health/live")
|
||||
async def live():
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.get("/health/ready")
|
||||
async def ready():
|
||||
await logic.ready(settings)
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.post("/api/v1/users", status_code=201)
|
||||
async def register(request: Request):
|
||||
return await logic.register_user(await _json_object(request))
|
||||
|
||||
|
||||
@app.post("/api/v1/auth/sessions", status_code=201)
|
||||
async def login(request: Request):
|
||||
username, password = _basic(request)
|
||||
return await logic.create_session(username, password, settings)
|
||||
|
||||
|
||||
@app.delete("/api/v1/auth/sessions/current", status_code=204)
|
||||
async def logout(request: Request):
|
||||
token = _bearer(request)
|
||||
await logic.authenticate(token)
|
||||
await logic.revoke_session(token)
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
@app.get("/api/v1/users/me")
|
||||
async def me(request: Request):
|
||||
return await _current_user(request)
|
||||
|
||||
|
||||
@app.post("/api/v1/chats", status_code=201)
|
||||
async def create_chat(request: Request):
|
||||
user = await _current_user(request)
|
||||
return await logic.create_chat(user["id"], await _json_object(request))
|
||||
|
||||
|
||||
@app.get("/api/v1/chats")
|
||||
async def list_chats(request: Request):
|
||||
user = await _current_user(request)
|
||||
limit = logic.parse_limit(request.query_params.get("limit"))
|
||||
return await logic.list_chats(user["id"], limit, request.query_params.get("cursor"))
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}")
|
||||
async def get_chat(chat_id: str, request: Request):
|
||||
user = await _current_user(request)
|
||||
return await logic.get_chat(user["id"], chat_id)
|
||||
|
||||
|
||||
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
|
||||
async def create_message(chat_id: str, request: Request):
|
||||
user = await _current_user(request)
|
||||
body = await _json_object(request)
|
||||
return await logic.create_message(
|
||||
user["id"],
|
||||
chat_id,
|
||||
body,
|
||||
request.headers.get("idempotency-key"),
|
||||
settings,
|
||||
)
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}/messages")
|
||||
async def list_messages(chat_id: str, request: Request):
|
||||
user = await _current_user(request)
|
||||
limit = logic.parse_limit(request.query_params.get("limit"))
|
||||
return await logic.list_messages(user["id"], chat_id, limit, request.query_params.get("cursor"))
|
||||
|
||||
|
||||
@app.post("/api/v1/chats/{chat_id}/attachments", status_code=201)
|
||||
async def upload(chat_id: str, request: Request):
|
||||
user = await _current_user(request)
|
||||
payload = await logic.upload_attachment(
|
||||
user["id"],
|
||||
chat_id,
|
||||
request.query_params.get("filename"),
|
||||
request.headers.get("content-type"),
|
||||
request.headers.get("content-length"),
|
||||
request.stream(),
|
||||
settings,
|
||||
)
|
||||
return JSONResponse(status_code=201, content=payload)
|
||||
|
||||
|
||||
@app.get("/api/v1/attachments/{attachment_id}")
|
||||
async def attachment_meta(attachment_id: str, request: Request):
|
||||
user = await _current_user(request)
|
||||
return await logic.get_attachment(user["id"], attachment_id)
|
||||
|
||||
|
||||
@app.get("/api/v1/attachments/{attachment_id}/content")
|
||||
async def attachment_content(attachment_id: str, request: Request):
|
||||
user = await _current_user(request)
|
||||
data, media = await logic.download_attachment(
|
||||
user["id"],
|
||||
attachment_id,
|
||||
request.query_params.get("variant"),
|
||||
settings,
|
||||
)
|
||||
return Response(content=data, media_type=media, headers={"Content-Length": str(len(data))})
|
||||
@@ -0,0 +1,235 @@
|
||||
"""Reconcile PostgreSQL metadata with the private bucket.
|
||||
|
||||
Grace period: objects and rows younger than ORPHAN_GRACE_SECONDS are left alone,
|
||||
because an upload may have written S3 and not committed metadata yet.
|
||||
Attachments referenced by a message are never deleted.
|
||||
A dry-run reports the same actions apply would perform, then apply is safe to repeat.
|
||||
"""
|
||||
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from app.config import Settings
|
||||
from app.db import pool
|
||||
from app import s3client
|
||||
|
||||
|
||||
def _aware(value: datetime) -> datetime:
|
||||
if value.tzinfo is None:
|
||||
return value.replace(tzinfo=timezone.utc)
|
||||
return value.astimezone(timezone.utc)
|
||||
|
||||
|
||||
def _age(moment: datetime, now: datetime) -> float:
|
||||
return (_aware(now) - _aware(moment)).total_seconds()
|
||||
|
||||
|
||||
async def reconcile(settings: Settings, apply: bool) -> dict:
|
||||
started = time.perf_counter()
|
||||
db_started = time.perf_counter()
|
||||
async with pool().acquire() as conn:
|
||||
now = await conn.fetchval("SELECT clock_timestamp()")
|
||||
attachments = await conn.fetch(
|
||||
"SELECT id, object_key, filename, created_at FROM attachments"
|
||||
)
|
||||
ledger_rows = await conn.fetch(
|
||||
"SELECT object_key, attachment_id, state, note, created_at FROM object_ledger"
|
||||
)
|
||||
referenced = {
|
||||
str(row["attachment_id"])
|
||||
for row in await conn.fetch("SELECT attachment_id FROM message_attachments")
|
||||
}
|
||||
db_ms = (time.perf_counter() - db_started) * 1000
|
||||
list_started = time.perf_counter()
|
||||
objects, pages = s3client.list_objects(settings, "o/")
|
||||
list_ms = (time.perf_counter() - list_started) * 1000
|
||||
|
||||
by_key = {row["object_key"]: row for row in attachments}
|
||||
ledger = {row["object_key"]: row for row in ledger_rows}
|
||||
object_keys = {item["Key"] for item in objects}
|
||||
grace = settings.orphan_grace_seconds
|
||||
actions = []
|
||||
skipped: dict[str, int] = {}
|
||||
|
||||
def skip(reason: str) -> None:
|
||||
skipped[reason] = skipped.get(reason, 0) + 1
|
||||
|
||||
for item in objects:
|
||||
key = item["Key"]
|
||||
led = ledger.get(key)
|
||||
if key in by_key:
|
||||
skip("accounted")
|
||||
continue
|
||||
moment = led["created_at"] if led is not None else item["LastModified"]
|
||||
note = (led["note"] if led is not None and led["note"] else None) or (
|
||||
led["state"] if led is not None else "untracked"
|
||||
)
|
||||
age = _age(moment, now)
|
||||
attachment_id = str(led["attachment_id"]) if led is not None and led["attachment_id"] else None
|
||||
if led is not None and led["state"] in {"aborted", "purged"} and age >= grace:
|
||||
actions.append(
|
||||
{
|
||||
"op": "delete_orphan_object",
|
||||
"note": note,
|
||||
"object_key": key,
|
||||
"attachment_id": attachment_id,
|
||||
"age_seconds": int(age),
|
||||
}
|
||||
)
|
||||
continue
|
||||
if age < grace:
|
||||
skip("fresh_orphan")
|
||||
continue
|
||||
actions.append(
|
||||
{
|
||||
"op": "delete_orphan_object",
|
||||
"note": note,
|
||||
"object_key": key,
|
||||
"attachment_id": attachment_id,
|
||||
"age_seconds": int(age),
|
||||
}
|
||||
)
|
||||
|
||||
for row in attachments:
|
||||
if row["object_key"] in object_keys:
|
||||
continue
|
||||
attachment_id = str(row["id"])
|
||||
age = _age(row["created_at"], now)
|
||||
if attachment_id in referenced:
|
||||
skip("in_use_missing")
|
||||
continue
|
||||
if age < grace:
|
||||
skip("fresh_missing")
|
||||
continue
|
||||
actions.append(
|
||||
{
|
||||
"op": "delete_stale_metadata",
|
||||
"note": row["filename"],
|
||||
"object_key": row["object_key"],
|
||||
"attachment_id": attachment_id,
|
||||
"age_seconds": int(age),
|
||||
}
|
||||
)
|
||||
|
||||
for row in ledger_rows:
|
||||
if row["object_key"] in object_keys or row["object_key"] in by_key:
|
||||
continue
|
||||
if row["state"] in {"aborted", "purged"}:
|
||||
skip("terminal_ledger")
|
||||
continue
|
||||
age = _age(row["created_at"], now)
|
||||
if age < grace:
|
||||
skip("fresh_intent")
|
||||
continue
|
||||
actions.append(
|
||||
{
|
||||
"op": "abort_stale_intent",
|
||||
"note": row["note"] or row["state"],
|
||||
"object_key": row["object_key"],
|
||||
"attachment_id": str(row["attachment_id"]) if row["attachment_id"] else None,
|
||||
"age_seconds": int(age),
|
||||
}
|
||||
)
|
||||
|
||||
applied = []
|
||||
if apply:
|
||||
for action in actions:
|
||||
result = await _apply_one(settings, action, grace)
|
||||
if result is not None:
|
||||
applied.append(result)
|
||||
|
||||
public_actions = [_public(item) for item in (applied if apply else actions)]
|
||||
return {
|
||||
"mode": "apply" if apply else "dry-run",
|
||||
"duration_ms": round((time.perf_counter() - started) * 1000, 3),
|
||||
"db_ms": round(db_ms, 3),
|
||||
"list_ms": round(list_ms, 3),
|
||||
"list_pages": pages,
|
||||
"objects_seen": len(objects),
|
||||
"attachment_rows": len(attachments),
|
||||
"ledger_rows": len(ledger_rows),
|
||||
"referenced_attachments": len(referenced),
|
||||
"grace_seconds": grace,
|
||||
"skipped": skipped,
|
||||
"actions": public_actions,
|
||||
"action_count": len(public_actions),
|
||||
}
|
||||
|
||||
|
||||
def _public(action: dict) -> dict:
|
||||
return {
|
||||
"op": action["op"],
|
||||
"note": action.get("note"),
|
||||
"attachment_id": action.get("attachment_id"),
|
||||
"age_seconds": action.get("age_seconds"),
|
||||
}
|
||||
|
||||
|
||||
async def _apply_one(settings: Settings, action: dict, grace: int) -> dict | None:
|
||||
key = action["object_key"]
|
||||
op = action["op"]
|
||||
async with pool().acquire() as conn:
|
||||
now = await conn.fetchval("SELECT clock_timestamp()")
|
||||
if op == "delete_orphan_object":
|
||||
owner = await conn.fetchrow("SELECT id, created_at FROM attachments WHERE object_key = $1", key)
|
||||
if owner is not None:
|
||||
return None
|
||||
led = await conn.fetchrow("SELECT created_at, state FROM object_ledger WHERE object_key = $1", key)
|
||||
moment = led["created_at"] if led is not None else now
|
||||
if led is not None and _age(moment, now) < grace and led["state"] not in {"aborted", "purged"}:
|
||||
return None
|
||||
s3client.delete_object(settings, key)
|
||||
if led is not None:
|
||||
await conn.execute(
|
||||
"""
|
||||
UPDATE object_ledger
|
||||
SET state = 'purged', updated_at = clock_timestamp()
|
||||
WHERE object_key = $1
|
||||
""",
|
||||
key,
|
||||
)
|
||||
return action
|
||||
if op == "delete_stale_metadata":
|
||||
attachment_id = action["attachment_id"]
|
||||
row = await conn.fetchrow(
|
||||
"SELECT object_key, created_at FROM attachments WHERE id = $1::uuid",
|
||||
attachment_id,
|
||||
)
|
||||
if row is None or _age(row["created_at"], now) < grace:
|
||||
return None
|
||||
used = await conn.fetchval(
|
||||
"SELECT 1 FROM message_attachments WHERE attachment_id = $1::uuid",
|
||||
attachment_id,
|
||||
)
|
||||
if used is not None or s3client.object_exists(settings, row["object_key"]):
|
||||
return None
|
||||
async with conn.transaction():
|
||||
await conn.execute("DELETE FROM attachments WHERE id = $1::uuid", attachment_id)
|
||||
await conn.execute(
|
||||
"""
|
||||
UPDATE object_ledger
|
||||
SET state = 'purged', updated_at = clock_timestamp()
|
||||
WHERE object_key = $1
|
||||
""",
|
||||
row["object_key"],
|
||||
)
|
||||
return action
|
||||
if op == "abort_stale_intent":
|
||||
led = await conn.fetchrow(
|
||||
"SELECT state, created_at FROM object_ledger WHERE object_key = $1",
|
||||
key,
|
||||
)
|
||||
if led is None or led["state"] in {"aborted", "purged"} or _age(led["created_at"], now) < grace:
|
||||
return None
|
||||
if s3client.object_exists(settings, key):
|
||||
s3client.delete_object(settings, key)
|
||||
await conn.execute(
|
||||
"""
|
||||
UPDATE object_ledger
|
||||
SET state = 'aborted', updated_at = clock_timestamp()
|
||||
WHERE object_key = $1 AND state IN ('staging', 'committed')
|
||||
""",
|
||||
key,
|
||||
)
|
||||
return action
|
||||
return None
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
"""S3 client for the private attachment bucket. Object keys are chosen by the server."""
|
||||
|
||||
import socket
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
from botocore.exceptions import BotoCoreError, ClientError, EndpointConnectionError
|
||||
|
||||
from app.config import Settings
|
||||
from app.errors import ApiError
|
||||
|
||||
_client = None
|
||||
|
||||
|
||||
def client(settings: Settings):
|
||||
global _client
|
||||
if _client is None:
|
||||
_client = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=settings.s3_endpoint,
|
||||
aws_access_key_id=settings.s3_access_key,
|
||||
aws_secret_access_key=settings.s3_secret_key,
|
||||
region_name=settings.s3_region,
|
||||
config=Config(
|
||||
signature_version="s3v4",
|
||||
s3={"addressing_style": "path"},
|
||||
connect_timeout=1,
|
||||
read_timeout=20,
|
||||
retries={"max_attempts": 1, "mode": "standard"},
|
||||
),
|
||||
)
|
||||
return _client
|
||||
|
||||
|
||||
def _unavailable(exc: Exception) -> ApiError:
|
||||
return ApiError(503, "unavailable", "Хранилище недоступно")
|
||||
|
||||
|
||||
def _ensure_reachable(settings: Settings) -> None:
|
||||
"""Fail in about a second when the endpoint black-holes a stopped container."""
|
||||
parsed = urlparse(settings.s3_endpoint)
|
||||
port = parsed.port or (443 if parsed.scheme == "https" else 80)
|
||||
try:
|
||||
with socket.create_connection((parsed.hostname, port), timeout=1):
|
||||
return
|
||||
except OSError as exc:
|
||||
raise _unavailable(exc) from exc
|
||||
|
||||
|
||||
def head_bucket(settings: Settings) -> None:
|
||||
_ensure_reachable(settings)
|
||||
try:
|
||||
client(settings).head_bucket(Bucket=settings.s3_bucket)
|
||||
except (ClientError, EndpointConnectionError, BotoCoreError, OSError) as exc:
|
||||
raise _unavailable(exc) from exc
|
||||
|
||||
|
||||
def put_file(settings: Settings, key: str, path: str, content_type: str, size: int) -> None:
|
||||
_ensure_reachable(settings)
|
||||
try:
|
||||
with open(path, "rb") as handle:
|
||||
client(settings).put_object(
|
||||
Bucket=settings.s3_bucket,
|
||||
Key=key,
|
||||
Body=handle,
|
||||
ContentLength=size,
|
||||
ContentType=content_type,
|
||||
)
|
||||
except (ClientError, EndpointConnectionError, BotoCoreError, OSError) as exc:
|
||||
raise _unavailable(exc) from exc
|
||||
|
||||
|
||||
def put_bytes(settings: Settings, key: str, payload: bytes, content_type: str = "application/octet-stream") -> None:
|
||||
_ensure_reachable(settings)
|
||||
try:
|
||||
client(settings).put_object(
|
||||
Bucket=settings.s3_bucket,
|
||||
Key=key,
|
||||
Body=payload,
|
||||
ContentLength=len(payload),
|
||||
ContentType=content_type,
|
||||
)
|
||||
except (ClientError, EndpointConnectionError, BotoCoreError, OSError) as exc:
|
||||
raise _unavailable(exc) from exc
|
||||
|
||||
|
||||
def get_bytes(settings: Settings, key: str, limit: int) -> bytes:
|
||||
_ensure_reachable(settings)
|
||||
try:
|
||||
obj = client(settings).get_object(Bucket=settings.s3_bucket, Key=key)
|
||||
body = obj["Body"]
|
||||
try:
|
||||
data = body.read(limit + 1)
|
||||
finally:
|
||||
body.close()
|
||||
except ClientError as exc:
|
||||
code = exc.response.get("Error", {}).get("Code", "")
|
||||
status = exc.response.get("ResponseMetadata", {}).get("HTTPStatusCode")
|
||||
if code in {"NoSuchKey", "404", "NotFound", "NoSuchBucket"} or status == 404:
|
||||
raise ApiError(404, "not_found", "Объект не найден") from exc
|
||||
raise _unavailable(exc) from exc
|
||||
except (EndpointConnectionError, BotoCoreError, OSError) as exc:
|
||||
raise _unavailable(exc) from exc
|
||||
if len(data) > limit:
|
||||
raise ApiError(500, "internal_error", "Внутренняя ошибка")
|
||||
return data
|
||||
|
||||
|
||||
def delete_object(settings: Settings, key: str) -> None:
|
||||
_ensure_reachable(settings)
|
||||
try:
|
||||
client(settings).delete_object(Bucket=settings.s3_bucket, Key=key)
|
||||
except (ClientError, EndpointConnectionError, BotoCoreError, OSError) as exc:
|
||||
raise _unavailable(exc) from exc
|
||||
|
||||
|
||||
def object_exists(settings: Settings, key: str) -> bool:
|
||||
_ensure_reachable(settings)
|
||||
try:
|
||||
client(settings).head_object(Bucket=settings.s3_bucket, Key=key)
|
||||
return True
|
||||
except ClientError as exc:
|
||||
code = exc.response.get("Error", {}).get("Code", "")
|
||||
status = exc.response.get("ResponseMetadata", {}).get("HTTPStatusCode")
|
||||
if code in {"NoSuchKey", "404", "NotFound", "NoSuchBucket"} or status in {404, 400}:
|
||||
return False
|
||||
raise _unavailable(exc) from exc
|
||||
except (EndpointConnectionError, BotoCoreError, OSError) as exc:
|
||||
raise _unavailable(exc) from exc
|
||||
|
||||
|
||||
def list_objects(settings: Settings, prefix: str = "o/") -> tuple[list[dict], int]:
|
||||
_ensure_reachable(settings)
|
||||
found = []
|
||||
pages = 0
|
||||
token = None
|
||||
while True:
|
||||
kwargs = {"Bucket": settings.s3_bucket, "Prefix": prefix, "MaxKeys": 1000}
|
||||
if token:
|
||||
kwargs["ContinuationToken"] = token
|
||||
try:
|
||||
response = client(settings).list_objects_v2(**kwargs)
|
||||
except (ClientError, EndpointConnectionError, BotoCoreError, OSError) as exc:
|
||||
raise _unavailable(exc) from exc
|
||||
pages += 1
|
||||
found.extend(response.get("Contents") or [])
|
||||
if not response.get("IsTruncated"):
|
||||
return found, pages
|
||||
token = response.get("NextContinuationToken")
|
||||
if not token:
|
||||
raise ApiError(503, "unavailable", "Хранилище вернуло неполный список")
|
||||
Reference in New Issue
Block a user