Собрать стенд lab4: вложения в MinIO и сверка хранилищ

This commit is contained in:
Wladislava1
2026-11-12 10:57:42 +03:00
parent ec540a1a72
commit 3715c6a395
33 changed files with 3111 additions and 45 deletions
+190
View File
@@ -0,0 +1,190 @@
"""Проверка PNG/JPEG и доступ к приватному bucket. Ключ объекта назначает сервер."""
import io
import os
from datetime import datetime, timezone
from minio import Minio
from minio.error import S3Error
from PIL import Image, UnidentifiedImageError
from PIL.Image import DecompressionBombError
from errors import ApiError, DependencyDown
MAX_BYTES = 10 * 1024 * 1024
MAX_PIXELS = 40_000_000
BUCKET = os.environ.get("S3_BUCKET", "messenger-attachments")
Image.MAX_IMAGE_PIXELS = MAX_PIXELS
_client = None
def read_secret(path):
with open(path, encoding="utf-8") as handle:
return handle.read().strip()
def client():
global _client
if _client is None:
endpoint = os.environ.get("S3_ENDPOINT", "minio:9000").strip()
access = read_secret(os.environ["S3_ACCESS_KEY_FILE"])
secret = read_secret(os.environ["S3_SECRET_KEY_FILE"])
secure = os.environ.get("S3_SECURE", "false").strip().lower() == "true"
_client = Minio(endpoint, access_key=access, secret_key=secret, secure=secure)
return _client
def bucket_ready():
try:
return client().bucket_exists(BUCKET)
except Exception:
return False
def put_bytes(key, data, content_type, created_at):
stamp = created_at.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
try:
client().put_object(
BUCKET,
key,
io.BytesIO(data),
length=len(data),
content_type=content_type,
metadata={"created-at": stamp},
)
except S3Error as exc:
raise DependencyDown() from exc
def delete_quiet(key):
try:
client().remove_object(BUCKET, key)
return True
except Exception:
return False
def open_object(key):
try:
return client().get_object(BUCKET, key)
except S3Error as exc:
code = getattr(exc, "code", "")
if code in ("NoSuchKey", "NoSuchBucket"):
return None
raise DependencyDown() from exc
def object_key(chat_id, attachment_id):
return "chats/{}/attachments/{}/original".format(chat_id, attachment_id)
def declared_type(header):
if not header:
return None
media = header.split(";", 1)[0].strip().lower()
if media in ("image/png", "image/jpeg"):
return media
return None
def _png_size(data):
if len(data) < 24 or data[:8] != b"\x89PNG\r\n\x1a\n" or data[12:16] != b"IHDR":
return None
width = int.from_bytes(data[16:20], "big")
height = int.from_bytes(data[20:24], "big")
return width, height
def _jpeg_size(data):
if len(data) < 4 or data[:2] != b"\xff\xd8":
return None
index = 2
limit = len(data)
while index + 8 < limit:
if data[index] != 0xFF:
return None
while index < limit and data[index] == 0xFF:
index += 1
if index >= limit:
return None
marker = data[index]
index += 1
if marker in (0xD8, 0xD9):
continue
if index + 2 > limit:
return None
segment = int.from_bytes(data[index:index + 2], "big")
if segment < 2 or index + segment > limit:
return None
if marker in (0xC0, 0xC1, 0xC2):
if segment < 7:
return None
height = int.from_bytes(data[index + 3:index + 5], "big")
width = int.from_bytes(data[index + 5:index + 7], "big")
return width, height
index += segment
return None
def _too_many_pixels(width, height):
if width <= 0 or height <= 0:
raise ApiError(415, "unsupported_media_type", "Файл не является PNG или JPEG")
if width > MAX_PIXELS or height > MAX_PIXELS or width * height > MAX_PIXELS:
raise ApiError(413, "payload_too_large", "В изображении больше 40 миллионов пикселей")
def inspect_image(data, declared):
if declared == "image/png":
size = _png_size(data)
elif declared == "image/jpeg":
size = _jpeg_size(data)
else:
size = None
detected = None
if data.startswith(b"\x89PNG\r\n\x1a\n"):
detected = "image/png"
elif data.startswith(b"\xff\xd8\xff"):
detected = "image/jpeg"
if size is None or detected != declared:
raise ApiError(415, "unsupported_media_type", "Файл не является PNG или JPEG")
_too_many_pixels(size[0], size[1])
try:
with Image.open(io.BytesIO(data)) as image:
image.load()
except DecompressionBombError as exc:
raise ApiError(413, "payload_too_large", "В изображении больше 40 миллионов пикселей") from exc
except (UnidentifiedImageError, OSError, SyntaxError, ValueError) as exc:
raise ApiError(415, "unsupported_media_type", "Файл не является PNG или JPEG") from exc
return declared
def list_objects():
found = []
try:
for item in client().list_objects(BUCKET, prefix="chats/", recursive=True):
if item.is_dir:
continue
stat = client().stat_object(BUCKET, item.object_name)
raw = None
if stat.metadata:
meta = {str(key).lower(): value for key, value in stat.metadata.items()}
raw = meta.get("x-amz-meta-created-at") or meta.get("created-at")
created = _parse_stamp(raw) if raw else None
if created is None and item.last_modified is not None:
created = item.last_modified
found.append({"key": item.object_name, "created_at": created})
except S3Error as exc:
raise DependencyDown() from exc
return found
def _parse_stamp(value):
text = value.strip().replace("Z", "+00:00")
try:
parsed = datetime.fromisoformat(text)
except ValueError:
return None
if parsed.tzinfo is None:
parsed = parsed.replace(tzinfo=timezone.utc)
return parsed
+28
View File
@@ -0,0 +1,28 @@
class ApiError(Exception):
def __init__(self, status, code, message, headers=None):
self.status = status
self.code = code
self.message = message
self.headers = headers or {}
class DependencyDown(Exception):
"""Postgres или Redis не ответили. Наружу это 503 без имени хранилища."""
class IdempotencyConflict(Exception):
"""Тот же Idempotency-Key уже зафиксирован с другим телом."""
class AttachmentRejected(Exception):
"""Вложение есть, но прикрепить его к сообщению нельзя."""
def error_body(code, message, request_id):
return {
"error": {
"code": code,
"message": message,
"request_id": request_id,
}
}
+471
View File
@@ -0,0 +1,471 @@
import json
import logging
import os
import re
import uuid
from contextlib import asynccontextmanager
import anyio
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse, Response, StreamingResponse
from pydantic import ValidationError
from starlette.exceptions import HTTPException as StarletteHTTPException
from blobs import MAX_BYTES, declared_type, inspect_image, open_object
from errors import ApiError, AttachmentRejected, DependencyDown, IdempotencyConflict, error_body
from schemas import CreateChat, CreateMessage, CreateUser
from store import Store, instance_id
LOGGER = logging.getLogger("messenger")
store = Store()
INSTANCE_ID = instance_id()
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
BEARER_CHALLENGE = 'Bearer realm="messenger"'
IDEMPOTENCY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
MAX_JSON_BYTES = 65536
@asynccontextmanager
async def lifespan(_app):
await anyio.to_thread.run_sync(store.startup)
yield
store.shutting_down = True
await anyio.to_thread.run_sync(store.shutdown)
app = FastAPI(
title="mtusi-messenger",
version="lab4",
lifespan=lifespan,
redirect_slashes=False,
docs_url="/docs",
redoc_url=None,
openapi_url="/openapi.json",
)
def request_id_of(request: Request):
rid = getattr(request.state, "request_id", None)
if rid:
return rid
return str(uuid.uuid4())
def stamp(request: Request, response):
response.headers["X-Request-Id"] = request_id_of(request)
response.headers["X-Instance-Id"] = INSTANCE_ID
return response
def json_ok(request: Request, payload, status_code=200):
return stamp(request, JSONResponse(payload, status_code=status_code))
def json_error(request: Request, status, code, message, extra_headers=None):
headers = {"X-Request-Id": request_id_of(request), "X-Instance-Id": INSTANCE_ID}
if extra_headers:
headers.update(extra_headers)
return JSONResponse(error_body(code, message, request_id_of(request)), status_code=status, headers=headers)
@app.middleware("http")
async def wrap_request(request: Request, call_next):
incoming = request.headers.get("X-Request-Id", "")
if incoming and len(incoming) <= 200 and incoming.isprintable() and incoming.strip():
request.state.request_id = incoming.strip()
else:
request.state.request_id = str(uuid.uuid4())
if store.shutting_down and request.url.path != "/health/live":
return json_error(request, 503, "unavailable", "Сервис временно недоступен")
response = await call_next(request)
return stamp(request, response)
@app.exception_handler(ApiError)
async def api_error_handler(request: Request, exc: ApiError):
return json_error(request, exc.status, exc.code, exc.message, exc.headers)
@app.exception_handler(RequestValidationError)
async def request_validation_handler(request: Request, _exc: RequestValidationError):
return json_error(request, 400, "invalid_request", "Некорректный запрос")
@app.exception_handler(ValidationError)
async def pydantic_handler(request: Request, _exc: ValidationError):
return json_error(request, 400, "invalid_request", "Некорректный запрос")
@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
if exc.status_code == 404:
return json_error(request, 404, "not_found", "Объект не найден")
return json_error(request, exc.status_code if exc.status_code < 500 else 500, "invalid_request", "Некорректный запрос")
@app.exception_handler(Exception)
async def unexpected_handler(request: Request, exc: Exception):
if isinstance(exc, ApiError):
return json_error(request, exc.status, exc.code, exc.message, exc.headers)
LOGGER.exception("unhandled")
return json_error(request, 500, "internal_error", "Внутренняя ошибка")
def unavailable():
raise ApiError(503, "unavailable", "Сервис временно недоступен")
def bearer_unauthorized():
raise ApiError(401, "unauthorized", "Требуется авторизация", {"WWW-Authenticate": BEARER_CHALLENGE})
def basic_unauthorized():
raise ApiError(401, "unauthorized", "Неверные учётные данные", {"WWW-Authenticate": BASIC_CHALLENGE})
def invalid():
raise ApiError(400, "invalid_request", "Некорректный запрос")
async def call_store(func, *args):
try:
return await anyio.to_thread.run_sync(func, *args)
except DependencyDown:
unavailable()
except IdempotencyConflict:
raise ApiError(409, "conflict", "Ключ уже использован с другим телом")
except AttachmentRejected:
raise ApiError(409, "conflict", "Вложение нельзя прикрепить")
def parse_basic(request: Request):
header = request.headers.get("Authorization", "")
if not header.lower().startswith("basic "):
basic_unauthorized()
raw = header.split(" ", 1)[1].strip()
try:
import base64
decoded = base64.b64decode(raw, validate=True).decode("utf-8")
except (ValueError, UnicodeError):
basic_unauthorized()
if ":" not in decoded:
basic_unauthorized()
username, password = decoded.split(":", 1)
return username, password
def parse_bearer(request: Request):
header = request.headers.get("Authorization", "")
# Basic на бизнес-методе не открывает сессию. X-User-Id не смотрим.
if not header.lower().startswith("bearer "):
bearer_unauthorized()
token = header.split(" ", 1)[1].strip()
if len(token) < 32 or len(token) > 512 or any(ch.isspace() for ch in token):
bearer_unauthorized()
return token
async def current_user(request: Request):
token = parse_bearer(request)
user = await call_store(store.user_for_token, token)
if user is None:
bearer_unauthorized()
request.state.user_id = user["id"]
request.state.token = token
return user
def parse_chat_id(chat_id):
try:
return str(uuid.UUID(chat_id))
except ValueError:
invalid()
def parse_limit(raw):
if raw is None:
return 50
if not isinstance(raw, str) or len(raw) > 3 or not raw.isdigit():
invalid()
value = int(raw)
if value < 1 or value > 100:
invalid()
return value
async def read_json(request: Request):
ctype = request.headers.get("content-type", "")
if "application/json" not in ctype.lower():
raise ApiError(415, "unsupported_media_type", "Нужен application/json")
length = request.headers.get("content-length")
if length is not None and (not length.isdigit() or int(length) > MAX_JSON_BYTES):
raise ApiError(413, "payload_too_large", "Слишком большое тело")
raw = await request.body()
if len(raw) > MAX_JSON_BYTES:
raise ApiError(413, "payload_too_large", "Слишком большое тело")
try:
payload = json.loads(raw)
except (ValueError, UnicodeError):
invalid()
if not isinstance(payload, dict):
invalid()
return payload
def parse_idempotency_key(request: Request):
key = request.headers.get("Idempotency-Key")
if key is None or not IDEMPOTENCY_RE.fullmatch(key):
invalid()
return key
@app.get("/health/live")
async def liveness(request: Request):
return json_ok(request, {"status": "ok"})
@app.get("/health/ready")
async def readiness(request: Request):
if store.shutting_down:
raise ApiError(503, "unavailable", "Сервис временно недоступен")
ok = await call_store(store.ready)
if not ok:
unavailable()
return json_ok(request, {"status": "ok"})
@app.post("/api/v1/users", status_code=201)
async def register_user(request: Request, body: CreateUser):
user = await call_store(store.create_user, body.username, body.display_name, body.password)
if user is None:
raise ApiError(409, "conflict", "Имя пользователя занято")
return json_ok(request, user, 201)
@app.post("/api/v1/auth/sessions", status_code=201)
async def create_session(request: Request):
username, password = parse_basic(request)
session = await call_store(store.login, username, password)
if session is None:
basic_unauthorized()
request.state.user_id = session["user"]["id"]
return json_ok(request, session, 201)
@app.delete("/api/v1/auth/sessions/current", status_code=204)
async def revoke_session(request: Request):
user = await current_user(request)
request.state.user_id = user["id"]
removed = await call_store(store.revoke, request.state.token)
if not removed:
bearer_unauthorized()
return stamp(request, Response(status_code=204))
@app.get("/api/v1/users/me")
async def me(request: Request):
user = await current_user(request)
return json_ok(request, user)
@app.post("/api/v1/chats", status_code=201)
async def create_chat(request: Request):
user = await current_user(request)
payload = await read_json(request)
try:
body = CreateChat.model_validate(payload)
except ValidationError:
invalid()
try:
chat = await call_store(store.create_chat, body.title, body.member_ids, user["id"])
except ValueError:
invalid()
return json_ok(request, chat, 201)
@app.get("/api/v1/chats")
async def list_chats(request: Request):
user = await current_user(request)
limit = parse_limit(request.query_params.get("limit"))
cursor = request.query_params.get("cursor")
if cursor is not None and (not cursor or len(cursor) > 512):
invalid()
try:
items, next_cursor = await call_store(store.list_chats, user["id"], limit, cursor)
except ValueError:
invalid()
return json_ok(request, {"items": items, "next_cursor": next_cursor})
@app.get("/api/v1/chats/{chat_id}")
async def get_chat(request: Request, chat_id: str):
user = await current_user(request)
chat = await call_store(store.get_chat, parse_chat_id(chat_id), user["id"])
if chat is None:
raise ApiError(404, "not_found", "Объект не найден")
return json_ok(request, chat)
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
async def create_message(request: Request, chat_id: str):
user = await current_user(request)
canonical = parse_chat_id(chat_id)
payload = await read_json(request)
key = parse_idempotency_key(request)
try:
body = CreateMessage.model_validate(payload)
except ValidationError:
invalid()
try:
message = await call_store(
store.add_message, canonical, user["id"], body.text, key, body.attachment_ids
)
except ValueError:
invalid()
if message is None:
raise ApiError(404, "not_found", "Объект не найден")
return json_ok(request, message, 201)
@app.get("/api/v1/chats/{chat_id}/messages")
async def list_messages(request: Request, chat_id: str):
user = await current_user(request)
canonical = parse_chat_id(chat_id)
limit = parse_limit(request.query_params.get("limit"))
cursor = request.query_params.get("cursor")
if cursor is not None and (not cursor or len(cursor) > 512):
invalid()
try:
result = await call_store(store.list_messages, canonical, user["id"], limit, cursor)
except ValueError:
invalid()
if result is None:
raise ApiError(404, "not_found", "Объект не найден")
items, next_cursor = result
return json_ok(request, {"items": items, "next_cursor": next_cursor})
def check_filename(value):
if not isinstance(value, str) or not value or len(value) > 255:
invalid()
if "/" in value or "\\" in value or "\x00" in value:
invalid()
if any(ord(char) < 32 or ord(char) == 127 for char in value):
invalid()
return value
def parse_attachment_id(value):
try:
return str(uuid.UUID(value))
except (TypeError, ValueError):
invalid()
async def read_upload(request: Request):
header = request.headers.get("content-length")
if header is not None:
try:
announced = int(header)
except ValueError:
invalid()
if announced > MAX_BYTES:
raise ApiError(413, "payload_too_large", "Файл больше 10 МиБ")
if announced < 1:
raise ApiError(415, "unsupported_media_type", "Нужен PNG или JPEG")
chunks = []
total = 0
async for chunk in request.stream():
total += len(chunk)
if total > MAX_BYTES:
raise ApiError(413, "payload_too_large", "Файл больше 10 МиБ")
chunks.append(chunk)
if total < 1:
raise ApiError(415, "unsupported_media_type", "Нужен PNG или JPEG")
return b"".join(chunks)
@app.post("/api/v1/chats/{chat_id}/attachments", status_code=201)
async def upload_attachment(request: Request, chat_id: str):
user = await current_user(request)
canonical = parse_chat_id(chat_id)
member = await call_store(store.is_member, canonical, user["id"])
if not member:
raise ApiError(404, "not_found", "Объект не найден")
filename = check_filename(request.query_params.get("filename"))
media = declared_type(request.headers.get("content-type"))
if media is None:
raise ApiError(415, "unsupported_media_type", "Нужен PNG или JPEG")
data = await read_upload(request)
content_type = await anyio.to_thread.run_sync(inspect_image, data, media)
saved = await call_store(
store.save_attachment, canonical, user["id"], filename, content_type, data
)
if saved is None:
raise ApiError(404, "not_found", "Объект не найден")
return json_ok(request, saved, 201)
@app.get("/api/v1/attachments/{attachment_id}")
async def get_attachment(request: Request, attachment_id: str):
user = await current_user(request)
canonical = parse_attachment_id(attachment_id)
found = await call_store(store.get_attachment, canonical, user["id"])
if found is None:
raise ApiError(404, "not_found", "Объект не найден")
return json_ok(request, found)
@app.get("/api/v1/attachments/{attachment_id}/content")
async def download_attachment(request: Request, attachment_id: str):
user = await current_user(request)
canonical = parse_attachment_id(attachment_id)
variant = request.query_params.get("variant")
if variant not in (None, "original"):
raise ApiError(404, "not_found", "Объект не найден")
opened = await call_store(store.open_attachment, canonical, user["id"])
if opened is None:
raise ApiError(404, "not_found", "Объект не найден")
def chunks():
body = open_object(opened["object_key"])
if body is None:
return
try:
for piece in body.stream(64 * 1024):
yield piece
finally:
body.close()
body.release_conn()
probe = await anyio.to_thread.run_sync(open_object, opened["object_key"])
if probe is None:
raise ApiError(404, "not_found", "Объект не найден")
probe.close()
probe.release_conn()
response = StreamingResponse(chunks(), media_type=opened["content_type"])
response.headers["Content-Length"] = str(opened["size_bytes"])
return stamp(request, response)
def setup_logging():
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
if __name__ == "__main__":
import uvicorn
setup_logging()
host = os.environ.get("APP_HOST", "0.0.0.0")
port = int(os.environ.get("APP_PORT", "8080"))
uvicorn.run(
app,
host=host,
port=port,
timeout_graceful_shutdown=5,
timeout_keep_alive=2,
access_log=False,
)
+112
View File
@@ -0,0 +1,112 @@
"""Однократные миграции. Запускается отдельным контейнером, не каждой репликой API."""
import logging
import os
import sys
import time
from pathlib import Path
import psycopg
from psycopg.rows import dict_row
LOGGER = logging.getLogger("migrate")
MIGRATION_LOCK = 421003
CONNECT_TIMEOUT = 3
def read_secret_file(path):
with open(path, encoding="utf-8") as handle:
return handle.read().strip()
def database_url():
path = os.environ.get("DATABASE_URL_FILE")
if path:
return read_secret_file(path)
url = os.environ.get("DATABASE_URL", "").strip()
if not url:
raise RuntimeError("DATABASE_URL_FILE")
return url
def split_sql(script):
parts = []
buf = []
for line in script.splitlines():
if line.strip().startswith("--"):
continue
buf.append(line)
if line.strip().endswith(";"):
statement = "\n".join(buf).strip()
if statement.endswith(";"):
statement = statement[:-1].strip()
if statement:
parts.append(statement)
buf = []
tail = "\n".join(buf).strip().rstrip(";").strip()
if tail:
parts.append(tail)
return parts
def wait_postgres(conninfo):
last = None
for _ in range(60):
try:
with psycopg.connect(conninfo, connect_timeout=CONNECT_TIMEOUT) as conn:
conn.execute("SELECT 1")
return
except psycopg.OperationalError as exc:
last = type(exc).__name__
time.sleep(1)
LOGGER.error("postgres not ready: %s", last)
raise SystemExit(1)
def apply(conninfo):
directory = Path(__file__).resolve().parents[1] / "migrations"
with psycopg.connect(conninfo, connect_timeout=CONNECT_TIMEOUT, row_factory=dict_row) as conn:
conn.execute("SELECT pg_advisory_lock(%s)", (MIGRATION_LOCK,))
conn.commit()
try:
conn.execute(
"""
CREATE TABLE IF NOT EXISTS schema_migrations (
version text PRIMARY KEY,
applied_at timestamptz NOT NULL DEFAULT now()
)
"""
)
conn.commit()
for path in sorted(directory.glob("*.sql")):
version = path.stem
found = conn.execute(
"SELECT 1 FROM schema_migrations WHERE version = %s",
(version,),
).fetchone()
conn.rollback()
if found:
LOGGER.info("migration %s already applied", version)
continue
with conn.transaction():
for statement in split_sql(path.read_text(encoding="utf-8")):
conn.execute(statement)
conn.execute(
"INSERT INTO schema_migrations (version) VALUES (%s)",
(version,),
)
LOGGER.info("migration %s applied", version)
finally:
conn.execute("SELECT pg_advisory_unlock(%s)", (MIGRATION_LOCK,))
conn.commit()
def main():
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
conninfo = database_url()
wait_postgres(conninfo)
apply(conninfo)
return 0
if __name__ == "__main__":
sys.exit(main())
+26
View File
@@ -0,0 +1,26 @@
from argon2 import PasswordHasher
from argon2.exceptions import InvalidHash, VerificationError, VerifyMismatchError
# Параметры ближе к учебному стенду, чем к максимальным: time=2, 19 MiB, Argon2id.
# Хеш всё равно медленный password KDF, не SHA-256 и не открытый текст.
hasher = PasswordHasher(
time_cost=2,
memory_cost=19456,
parallelism=1,
hash_len=32,
salt_len=16,
)
# Чтобы неизвестный username не отвечал заметно быстрее известного.
DUMMY_HASH = hasher.hash("dummy-password-not-a-user")
def hash_password(password):
return hasher.hash(password)
def verify_password(password, encoded):
try:
return hasher.verify(encoded, password)
except (VerifyMismatchError, VerificationError, InvalidHash):
return False
+154
View File
@@ -0,0 +1,154 @@
"""Сверка строк attachments и объектов bucket.
Свежий объект моложе grace не удаляется: загрузка могла записать файл
раньше, чем строка в базе. Строка, на которую ссылается сообщение, тоже
не удаляется, даже если файла уже нет. По умолчанию только план, без удалений.
"""
import argparse
import json
import os
import sys
import time
from datetime import datetime, timezone
import psycopg
from psycopg.rows import dict_row
from blobs import BUCKET, delete_quiet, list_objects
def grace_seconds():
raw = os.environ.get("RECONCILE_GRACE_SECONDS", "120")
value = int(raw)
if value < 1:
raise RuntimeError("RECONCILE_GRACE_SECONDS")
return value
def database_url():
path = os.environ.get("DATABASE_URL_FILE")
if not path:
raise RuntimeError("DATABASE_URL_FILE")
with open(path, encoding="utf-8") as handle:
return handle.read().strip()
def aware(value):
if value is None:
return None
if value.tzinfo is None:
return value.replace(tzinfo=timezone.utc)
return value.astimezone(timezone.utc)
def plan(grace):
started = time.perf_counter()
objects = list_objects()
listed = time.perf_counter()
now = datetime.now(timezone.utc)
with psycopg.connect(database_url(), row_factory=dict_row) as conn:
rows = conn.execute(
"""
SELECT a.id, a.object_key, a.created_at,
EXISTS (
SELECT 1 FROM message_attachments m
WHERE m.attachment_id = a.id
) AS in_use
FROM attachments a
"""
).fetchall()
by_key = {row["object_key"]: row for row in rows}
object_keys = {item["key"] for item in objects}
actions = []
preserved = []
for item in objects:
row = by_key.get(item["key"])
if row is not None:
continue
created = aware(item["created_at"]) or now
age = (now - created).total_seconds()
entry = {"key": item["key"], "age_seconds": round(age, 3)}
if age < grace:
entry["reason"] = "fresh_object"
preserved.append(entry)
continue
entry["action"] = "delete_orphan_object"
actions.append(entry)
for row in rows:
if row["object_key"] in object_keys:
continue
created = aware(row["created_at"]) or now
age = (now - created).total_seconds()
entry = {
"attachment_id": str(row["id"]),
"key": row["object_key"],
"age_seconds": round(age, 3),
}
if row["in_use"]:
entry["reason"] = "missing_but_in_use"
preserved.append(entry)
continue
if age < grace:
entry["reason"] = "fresh_row"
preserved.append(entry)
continue
entry["action"] = "delete_orphan_row"
actions.append(entry)
return {
"bucket": BUCKET,
"grace_seconds": grace,
"objects": len(objects),
"rows": len(rows),
"list_seconds": round(listed - started, 6),
"plan_seconds": round(time.perf_counter() - started, 6),
"actions": actions,
"preserved": preserved,
}
def apply_plan(report):
deleted_objects = 0
deleted_rows = 0
with psycopg.connect(database_url(), row_factory=dict_row) as conn:
for action in report["actions"]:
if action["action"] == "delete_orphan_object":
if delete_quiet(action["key"]):
deleted_objects += 1
elif action["action"] == "delete_orphan_row":
with conn.transaction():
result = conn.execute(
"""
DELETE FROM attachments
WHERE id = %s
AND NOT EXISTS (
SELECT 1 FROM message_attachments m
WHERE m.attachment_id = attachments.id
)
""",
(action["attachment_id"],),
)
deleted_rows += result.rowcount
report["deleted_objects"] = deleted_objects
report["deleted_rows"] = deleted_rows
return report
def main():
parser = argparse.ArgumentParser(description="Сверить вложения в базе и в bucket")
parser.add_argument("--apply", action="store_true", help="выполнить удаления; без флага только план")
parser.add_argument("--grace", type=int, default=None)
args = parser.parse_args()
grace = args.grace if args.grace is not None else grace_seconds()
if grace < 1:
print("grace должен быть не меньше 1 секунды", file=sys.stderr)
return 2
report = plan(grace)
report["apply"] = bool(args.apply)
if args.apply:
apply_plan(report)
print(json.dumps(report, ensure_ascii=False, sort_keys=True))
return 0
if __name__ == "__main__":
raise SystemExit(main())
+128
View File
@@ -0,0 +1,128 @@
import re
import uuid
from pydantic import BaseModel, ConfigDict, field_validator, model_validator
USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$")
class StrictModel(BaseModel):
model_config = ConfigDict(extra="forbid")
def _visible(value, limit):
if not isinstance(value, str) or not value.strip() or len(value) > limit:
raise ValueError("text")
return value
class CreateUser(StrictModel):
username: str
display_name: str
password: str
@field_validator("username")
@classmethod
def username_ok(cls, value):
if not isinstance(value, str) or not USERNAME_RE.fullmatch(value):
raise ValueError("username")
return value
@field_validator("display_name")
@classmethod
def display_name_ok(cls, value):
return _visible(value, 100)
@field_validator("password")
@classmethod
def password_ok(cls, value):
if not isinstance(value, str) or not value.strip():
raise ValueError("password")
# Длина в code points, не в байтах: bcrypt тут не подходит из-за усечения UTF-8.
if len(value) < 12 or len(value) > 128:
raise ValueError("password")
return value
class CreateChat(StrictModel):
title: str
member_ids: list
@field_validator("title")
@classmethod
def title_ok(cls, value):
return _visible(value, 100)
@field_validator("member_ids")
@classmethod
def member_ids_ok(cls, value):
if not isinstance(value, list) or not (1 <= len(value) <= 100):
raise ValueError("member_ids")
# Канонический UUID (нижний регистр). Иначе один и тот же id
# в разном регистре выглядит как два участника и упирается в PK.
normalized = []
seen = set()
for item in value:
if not isinstance(item, str):
raise ValueError("member_ids")
try:
canonical = str(uuid.UUID(item))
except ValueError as exc:
raise ValueError("member_ids") from exc
if canonical in seen:
raise ValueError("member_ids")
seen.add(canonical)
normalized.append(canonical)
return normalized
class CreateMessage(StrictModel):
text: str
attachment_ids: list = []
@model_validator(mode="before")
@classmethod
def fill_attachments(cls, value):
# Нет поля и явный [] — одно и то же тело для Idempotency-Key.
if not isinstance(value, dict):
return value
data = dict(value)
data.setdefault("attachment_ids", [])
return data
@field_validator("text")
@classmethod
def text_ok(cls, value):
if not isinstance(value, str) or len(value) > 4000:
raise ValueError("text")
if value != "" and not value.strip():
raise ValueError("text")
return value
@field_validator("attachment_ids")
@classmethod
def attachments_ok(cls, value):
if not isinstance(value, list) or len(value) > 10:
raise ValueError("attachment_ids")
normalized = []
seen = set()
for item in value:
if not isinstance(item, str):
raise ValueError("attachment_ids")
try:
canonical = str(uuid.UUID(item))
except ValueError as exc:
raise ValueError("attachment_ids") from exc
if canonical in seen:
raise ValueError("attachment_ids")
seen.add(canonical)
normalized.append(canonical)
return normalized
@model_validator(mode="after")
def text_or_file(self):
if self.text == "" and not self.attachment_ids:
raise ValueError("text")
if self.text and not self.text.strip():
raise ValueError("text")
return self
+774
View File
@@ -0,0 +1,774 @@
import base64
import hashlib
import json
import logging
import os
import secrets
import socket
import time
import uuid
from datetime import datetime, timedelta, timezone
import psycopg
import redis
from psycopg.errors import CheckViolation, ForeignKeyViolation, UniqueViolation
from psycopg.rows import dict_row
from psycopg_pool import ConnectionPool, PoolTimeout
from errors import AttachmentRejected, DependencyDown, IdempotencyConflict
from passwords import DUMMY_HASH, hash_password, verify_password
LOGGER = logging.getLogger("messenger")
POOL_TIMEOUT_SECONDS = 3
STATEMENT_TIMEOUT_MS = 5000
LOCK_TIMEOUT_MS = 3000
REDIS_MAX_CONNECTIONS = 16
REDIS_SOCKET_TIMEOUT = 2
SCHEMA_VERSION = "003_attachments"
SQL_MESSAGES_FIRST = """
SELECT id, chat_id, sender_id, body AS text, created_at
FROM messages
WHERE chat_id = %s
ORDER BY created_at, id
LIMIT %s
"""
SQL_MESSAGES_AFTER = """
SELECT id, chat_id, sender_id, body AS text, created_at
FROM messages
WHERE chat_id = %s
AND (created_at, id) > (%s, %s)
ORDER BY created_at, id
LIMIT %s
"""
SQL_MESSAGE_BY_ID = """
SELECT id, chat_id, sender_id, body AS text, created_at
FROM messages
WHERE id = %s
"""
def instance_id():
# Docker без hostname: в контейнере это id контейнера, он не меняется,
# пока живёт этот контейнер. stop-one.sh находит контейнер по этому значению.
return socket.gethostname()
def pool_max():
raw = os.environ.get("POOL_MAX", "10")
try:
value = int(raw)
except ValueError as exc:
raise RuntimeError("POOL_MAX") from exc
if not 1 <= value <= 32:
raise RuntimeError("POOL_MAX")
return value
def utc_now():
return datetime.now(timezone.utc)
def dump_time(value):
if value.tzinfo is None:
value = value.replace(tzinfo=timezone.utc)
text = value.astimezone(timezone.utc).isoformat(timespec="microseconds")
if text.endswith("+00:00"):
text = text[:-6] + "Z"
return text
def parse_time(value):
if not isinstance(value, str) or not value.endswith("Z"):
raise ValueError("time")
return datetime.fromisoformat(value[:-1] + "+00:00")
def encode_cursor(scope, created_at, item_id):
raw = "{}|{}|{}".format(scope, created_at, item_id).encode("utf-8")
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
def decode_cursor(cursor, expected_scope):
if not isinstance(cursor, str) or not cursor or len(cursor) > 512:
raise ValueError("cursor")
pad = "=" * (-len(cursor) % 4)
try:
decoded = base64.urlsafe_b64decode(cursor + pad).decode("utf-8")
except (ValueError, UnicodeError) as exc:
raise ValueError("cursor") from exc
parts = decoded.split("|")
if len(parts) != 3:
raise ValueError("cursor")
scope, created_at, item_id = parts
if scope != expected_scope:
raise ValueError("cursor")
parse_time(created_at)
try:
uuid.UUID(item_id)
except ValueError as exc:
raise ValueError("cursor") from exc
return created_at, item_id
def session_key(token):
digest = hashlib.sha256(token.encode("utf-8")).hexdigest()
return "sess:" + digest
def message_fingerprint(text, attachment_ids):
# Канонический JSON: порядок ключей не важен, пропущенный attachment_ids равен [].
canonical = json.dumps(
{"attachment_ids": list(attachment_ids), "text": text},
ensure_ascii=False,
sort_keys=True,
separators=(",", ":"),
)
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
def advisory_key(user_id, path, idem_key):
raw = "\0".join((user_id, "POST", path, idem_key)).encode("utf-8")
digest = hashlib.sha256(raw).digest()
return int.from_bytes(digest[:8], "big", signed=True)
def chat_path(chat_id):
return "/api/v1/chats/" + chat_id + "/messages"
def public_user(row):
return {
"id": str(row["id"]),
"username": row["username"],
"display_name": row["display_name"],
"created_at": dump_time(row["created_at"]),
}
def public_message(row, attachment_ids=None):
return {
"id": str(row["id"]),
"chat_id": str(row["chat_id"]),
"sender_id": str(row["sender_id"]),
"text": row["text"],
"attachment_ids": list(attachment_ids or []),
"created_at": dump_time(row["created_at"]),
}
def public_attachment(row):
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": int(row["size_bytes"]),
"sha256": row["sha256"],
"status": "ready",
"variants": [],
"error_code": None,
"created_at": dump_time(row["created_at"]),
"updated_at": dump_time(row["updated_at"]),
}
def public_chat(row, member_ids=None):
members = member_ids if member_ids is not None else row["member_ids"]
return {
"id": str(row["id"]),
"title": row["title"],
"member_ids": [str(item) for item in members],
"created_at": dump_time(row["created_at"]),
}
def read_secret_file(path):
with open(path, encoding="utf-8") as handle:
return handle.read().strip()
def _db_down(exc):
raise DependencyDown() from exc
class Store:
def __init__(self):
self.pool = None
self.redis = None
self.ttl = int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
self.idem_ttl = int(os.environ.get("IDEMPOTENCY_TTL_SECONDS", "86400"))
self.pool_size = pool_max()
self.shutting_down = False
if self.ttl < 1 or self.idem_ttl < 1:
raise RuntimeError("TTL")
kind = os.environ.get("SESSION_STORE", "redis").strip().lower()
if kind != "redis":
raise RuntimeError("SESSION_STORE")
def database_url(self):
path = os.environ.get("DATABASE_URL_FILE")
if path:
return read_secret_file(path)
url = os.environ.get("DATABASE_URL", "").strip()
if not url:
raise RuntimeError("DATABASE_URL_FILE")
return url
def redis_url(self):
path = os.environ.get("CACHE_URL_FILE")
if path:
return read_secret_file(path)
url = os.environ.get("CACHE_URL", "").strip()
if not url:
raise RuntimeError("CACHE_URL_FILE")
return url
def startup(self):
conninfo = self.database_url()
self._wait_schema(conninfo)
self.pool = ConnectionPool(
conninfo,
min_size=1,
max_size=self.pool_size,
timeout=POOL_TIMEOUT_SECONDS,
max_waiting=64,
max_lifetime=300,
kwargs={
"connect_timeout": POOL_TIMEOUT_SECONDS,
"row_factory": dict_row,
"application_name": "mtusi-lab4-" + instance_id(),
"options": "-c statement_timeout={} -c lock_timeout={} -c idle_in_transaction_session_timeout=15000".format(
STATEMENT_TIMEOUT_MS,
LOCK_TIMEOUT_MS,
),
},
open=True,
)
pool = redis.ConnectionPool.from_url(
self.redis_url(),
max_connections=REDIS_MAX_CONNECTIONS,
socket_timeout=REDIS_SOCKET_TIMEOUT,
socket_connect_timeout=REDIS_SOCKET_TIMEOUT,
health_check_interval=30,
decode_responses=True,
)
self.redis = redis.Redis(connection_pool=pool)
self._wait_redis()
self._wait_bucket()
LOGGER.info("ready instance=%s ttl=%s pool_max=%s", instance_id(), self.ttl, self.pool_size)
def shutdown(self):
self.shutting_down = True
if self.pool is not None:
self.pool.close()
if self.redis is not None:
self.redis.close()
def ready(self):
if self.shutting_down or self.pool is None or self.redis is None:
return False
try:
with self.pool.connection(timeout=POOL_TIMEOUT_SECONDS) as conn:
row = conn.execute(
"SELECT 1 FROM schema_migrations WHERE version = %s",
(SCHEMA_VERSION,),
).fetchone()
if row is None:
return False
self.redis.ping()
from blobs import bucket_ready
if not bucket_ready():
return False
except Exception:
LOGGER.warning("ready check failed")
return False
return True
def _wait_redis(self):
last = None
for _ in range(60):
try:
self.redis.ping()
return
except redis.RedisError as exc:
last = type(exc).__name__
time.sleep(1)
LOGGER.error("redis not ready: %s", last)
raise SystemExit(1)
def _wait_schema(self, conninfo):
# Схему накатывает сервис migrate. Реплики только ждут её, не применяют сами.
last = None
for _ in range(90):
try:
with psycopg.connect(conninfo, connect_timeout=POOL_TIMEOUT_SECONDS, row_factory=dict_row) as conn:
row = conn.execute(
"SELECT 1 FROM schema_migrations WHERE version = %s",
(SCHEMA_VERSION,),
).fetchone()
if row is not None:
return
last = "migration missing"
except psycopg.Error as exc:
last = type(exc).__name__
time.sleep(1)
LOGGER.error("schema not ready: %s", last)
raise SystemExit(1)
def _wait_bucket(self):
from blobs import bucket_ready
for _ in range(60):
if bucket_ready():
return
time.sleep(1)
LOGGER.error("object storage not ready")
raise SystemExit(1)
def _connect(self):
try:
return self.pool.connection(timeout=POOL_TIMEOUT_SECONDS)
except PoolTimeout as exc:
_db_down(exc)
def create_user(self, username, display_name, password):
password_hash = hash_password(password)
user_id = uuid.uuid4()
created = utc_now()
try:
with self._connect() as conn:
with conn.transaction():
row = conn.execute(
"""
INSERT INTO users (id, username, display_name, password_hash, created_at)
VALUES (%s, %s, %s, %s, %s)
ON CONFLICT (username) DO NOTHING
RETURNING id, username, display_name, created_at
""",
(user_id, username, display_name, password_hash, created),
).fetchone()
except psycopg.OperationalError as exc:
_db_down(exc)
if row is None:
return None
return public_user(row)
def login(self, username, password):
try:
with self._connect() as conn:
row = conn.execute(
"""
SELECT id, username, display_name, password_hash, created_at
FROM users
WHERE username = %s
""",
(username,),
).fetchone()
except psycopg.OperationalError as exc:
_db_down(exc)
if row is None:
verify_password(password, DUMMY_HASH)
return None
if not verify_password(password, row["password_hash"]):
return None
return self._issue(public_user(row))
def _issue(self, user):
token = secrets.token_urlsafe(32)
expires = utc_now() + timedelta(seconds=self.ttl)
payload = json.dumps(
{"user_id": user["id"], "expires_at": dump_time(expires)},
separators=(",", ":"),
)
# pxat — абсолютное время. Рестарт Redis не сдвигает срок.
# В значении тоже лежит expires_at: даже если TTL ключа разъедется, сессия кончится вовремя.
try:
self.redis.set(session_key(token), payload, pxat=int(expires.timestamp() * 1000))
except redis.RedisError as exc:
raise DependencyDown() from exc
return {
"token": token,
"token_type": "Bearer",
"expires_at": dump_time(expires),
"user": user,
}
def user_for_token(self, token):
key = session_key(token)
try:
raw = self.redis.get(key)
except redis.RedisError as exc:
raise DependencyDown() from exc
if not raw:
return None
try:
payload = json.loads(raw)
expires = parse_time(payload["expires_at"])
user_id = payload["user_id"]
uuid.UUID(user_id)
except (ValueError, KeyError, TypeError):
return None
if utc_now() >= expires:
try:
self.redis.delete(key)
except redis.RedisError as exc:
raise DependencyDown() from exc
return None
try:
with self._connect() as conn:
row = conn.execute(
"""
SELECT id, username, display_name, created_at
FROM users
WHERE id = %s
""",
(user_id,),
).fetchone()
except psycopg.OperationalError as exc:
_db_down(exc)
if row is None:
return None
return public_user(row)
def revoke(self, token):
try:
deleted = self.redis.delete(session_key(token))
except redis.RedisError as exc:
raise DependencyDown() from exc
return deleted == 1
def create_chat(self, title, member_ids, caller_id):
try:
caller_uuid = uuid.UUID(str(caller_id))
member_uuids = []
seen = set()
for item in member_ids:
member_uuid = uuid.UUID(str(item))
if member_uuid in seen:
raise ValueError("members")
seen.add(member_uuid)
member_uuids.append(member_uuid)
except ValueError as exc:
raise ValueError("members") from exc
if caller_uuid not in seen:
raise ValueError("members")
chat_id = uuid.uuid4()
created = utc_now()
canonical_members = [str(item) for item in member_uuids]
try:
with self._connect() as conn:
try:
with conn.transaction():
conn.execute(
"INSERT INTO chats (id, title, created_at) VALUES (%s, %s, %s)",
(chat_id, title, created),
)
for ordinal, member_id in enumerate(member_uuids):
conn.execute(
"""
INSERT INTO chat_members (chat_id, user_id, ordinal)
VALUES (%s, %s, %s)
""",
(chat_id, member_id, ordinal),
)
row = conn.execute(
"SELECT id, title, created_at FROM chats WHERE id = %s",
(chat_id,),
).fetchone()
except ForeignKeyViolation as exc:
raise ValueError("members") from exc
except UniqueViolation as exc:
raise ValueError("members") from exc
except psycopg.OperationalError as exc:
_db_down(exc)
return public_chat(row, canonical_members)
def _member(self, conn, chat_id, user_id):
return conn.execute(
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s",
(chat_id, user_id),
).fetchone()
def get_chat(self, chat_id, user_id):
try:
with self._connect() as conn:
if self._member(conn, chat_id, user_id) is None:
return None
row = conn.execute(
"""
SELECT c.id, c.title, c.created_at,
array_agg(m.user_id ORDER BY m.ordinal) AS member_ids
FROM chats c
JOIN chat_members m ON m.chat_id = c.id
WHERE c.id = %s
GROUP BY c.id
""",
(chat_id,),
).fetchone()
except psycopg.OperationalError as exc:
_db_down(exc)
if row is None:
return None
return public_chat(row)
def list_chats(self, user_id, limit, cursor):
after = None
if cursor is not None:
created_at, item_id = decode_cursor(cursor, "chats:" + user_id)
after = (parse_time(created_at), uuid.UUID(item_id))
sql = """
SELECT c.id, c.title, c.created_at,
array_agg(m.user_id ORDER BY m.ordinal) AS member_ids
FROM chats c
JOIN chat_members mine ON mine.chat_id = c.id AND mine.user_id = %s
JOIN chat_members m ON m.chat_id = c.id
"""
params = [user_id]
if after is not None:
sql += " WHERE (c.created_at, c.id) > (%s, %s)"
params.extend(after)
sql += " GROUP BY c.id ORDER BY c.created_at, c.id LIMIT %s"
params.append(limit + 1)
try:
with self._connect() as conn:
rows = conn.execute(sql, params).fetchall()
except psycopg.OperationalError as exc:
_db_down(exc)
page = [public_chat(row) for row in rows[:limit]]
if len(rows) > limit and page:
last = page[-1]
return page, encode_cursor("chats:" + user_id, last["created_at"], last["id"])
return page, None
def _attachment_ids(self, conn, message_ids):
if not message_ids:
return {}
rows = conn.execute(
"""
SELECT message_id, attachment_id
FROM message_attachments
WHERE message_id = ANY(%s::uuid[])
ORDER BY ordinal
""",
(list(message_ids),),
).fetchall()
found = {}
for row in rows:
found.setdefault(str(row["message_id"]), []).append(str(row["attachment_id"]))
return found
def is_member(self, chat_id, user_id):
try:
with self._connect() as conn:
return self._member(conn, chat_id, user_id) is not None
except psycopg.OperationalError as exc:
_db_down(exc)
def save_attachment(self, chat_id, owner_id, filename, content_type, data):
from blobs import delete_quiet, object_key, put_bytes
attachment_id = uuid.uuid4()
key = object_key(chat_id, attachment_id)
digest = hashlib.sha256(data).hexdigest()
created = utc_now()
put_bytes(key, data, content_type, created)
try:
with self._connect() as conn:
with conn.transaction():
if self._member(conn, chat_id, owner_id) is None:
raise LookupError("chat")
row = conn.execute(
"""
INSERT INTO attachments (
id, chat_id, owner_id, filename, content_type,
size_bytes, sha256, object_key, status, created_at, updated_at
)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, 'ready', %s, %s)
RETURNING id, chat_id, owner_id, filename, content_type,
size_bytes, sha256, created_at, updated_at
""",
(
attachment_id,
chat_id,
owner_id,
filename,
content_type,
len(data),
digest,
key,
created,
created,
),
).fetchone()
except (LookupError, ForeignKeyViolation):
delete_quiet(key)
return None
except psycopg.OperationalError as exc:
delete_quiet(key)
_db_down(exc)
except Exception:
delete_quiet(key)
raise
return public_attachment(row)
def get_attachment(self, attachment_id, user_id):
try:
with self._connect() as conn:
row = conn.execute(
"""
SELECT a.id, a.chat_id, a.owner_id, a.filename, a.content_type,
a.size_bytes, a.sha256, a.created_at, a.updated_at
FROM attachments a
JOIN chat_members m ON m.chat_id = a.chat_id AND m.user_id = %s
WHERE a.id = %s
""",
(user_id, attachment_id),
).fetchone()
except psycopg.OperationalError as exc:
_db_down(exc)
if row is None:
return None
return public_attachment(row)
def open_attachment(self, attachment_id, user_id):
try:
with self._connect() as conn:
row = conn.execute(
"""
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 = %s
WHERE a.id = %s
""",
(user_id, attachment_id),
).fetchone()
except psycopg.OperationalError as exc:
_db_down(exc)
if row is None:
return None
return {
"object_key": row["object_key"],
"content_type": row["content_type"],
"size_bytes": int(row["size_bytes"]),
}
def add_message(self, chat_id, sender_id, text, idem_key, attachment_ids):
# Один ключ сериализуется между репликами через advisory lock в той же
# транзакции, где INSERT сообщения. Откат не оставляет ключ занятым.
path = chat_path(chat_id)
digest = message_fingerprint(text, attachment_ids)
lock_key = advisory_key(sender_id, path, idem_key)
message_id = uuid.uuid4()
try:
with self._connect() as conn:
with conn.transaction():
# Иначе lock_timeout сессии (3 с) оборвёт очередь одинаковых ключей.
conn.execute("SET LOCAL lock_timeout = '15s'")
conn.execute("SELECT pg_advisory_xact_lock(%s)", (lock_key,))
if self._member(conn, chat_id, sender_id) is None:
return None
existing = conn.execute(
"""
SELECT request_hash, message_id,
created_at >= now() - make_interval(secs => %s) AS fresh
FROM idempotency_keys
WHERE user_id = %s AND http_method = 'POST'
AND request_path = %s AND idem_key = %s
""",
(self.idem_ttl, sender_id, path, idem_key),
).fetchone()
if existing is not None and existing["fresh"]:
if existing["request_hash"] != digest:
raise IdempotencyConflict()
row = conn.execute(SQL_MESSAGE_BY_ID, (existing["message_id"],)).fetchone()
if row is None:
raise RuntimeError("idempotency target missing")
linked = self._attachment_ids(conn, [row["id"]]).get(str(row["id"]), [])
return public_message(row, linked)
if existing is not None:
conn.execute(
"""
DELETE FROM idempotency_keys
WHERE user_id = %s AND http_method = 'POST'
AND request_path = %s AND idem_key = %s
""",
(sender_id, path, idem_key),
)
if attachment_ids:
found = conn.execute(
"""
SELECT id, chat_id, status
FROM attachments
WHERE id = ANY(%s::uuid[])
""",
(list(attachment_ids),),
).fetchall()
by_id = {str(item["id"]): item for item in found}
for attachment_id in attachment_ids:
item = by_id.get(attachment_id)
if item is None or str(item["chat_id"]) != chat_id:
return None
if item["status"] != "ready":
raise AttachmentRejected()
row = conn.execute(
"""
INSERT INTO messages (id, chat_id, sender_id, body, created_at)
VALUES (%s, %s, %s, %s, clock_timestamp())
RETURNING id, chat_id, sender_id, body AS text, created_at
""",
(message_id, chat_id, sender_id, text),
).fetchone()
for ordinal, attachment_id in enumerate(attachment_ids):
conn.execute(
"""
INSERT INTO message_attachments (message_id, attachment_id, ordinal)
VALUES (%s, %s, %s)
""",
(row["id"], attachment_id, ordinal),
)
conn.execute(
"""
INSERT INTO idempotency_keys (
user_id, http_method, request_path, idem_key,
request_hash, message_id, created_at
)
VALUES (%s, 'POST', %s, %s, %s, %s, clock_timestamp())
""",
(sender_id, path, idem_key, digest, row["id"]),
)
return public_message(row, attachment_ids)
except CheckViolation as exc:
raise ValueError("message") from exc
except psycopg.OperationalError as exc:
_db_down(exc)
def list_messages(self, chat_id, user_id, limit, cursor):
after = None
if cursor is not None:
created_at, item_id = decode_cursor(cursor, chat_id)
after = (parse_time(created_at), uuid.UUID(item_id))
try:
with self._connect() as conn:
if self._member(conn, chat_id, user_id) is None:
return None
if after is None:
rows = conn.execute(SQL_MESSAGES_FIRST, (chat_id, limit + 1)).fetchall()
else:
rows = conn.execute(
SQL_MESSAGES_AFTER,
(chat_id, after[0], after[1], limit + 1),
).fetchall()
linked = self._attachment_ids(conn, [row["id"] for row in rows[:limit]])
except psycopg.OperationalError as exc:
_db_down(exc)
page = [public_message(row, linked.get(str(row["id"]), [])) for row in rows[:limit]]
if len(rows) > limit and page:
last = page[-1]
return page, encode_cursor(chat_id, last["created_at"], last["id"])
return page, None
+212
View File
@@ -0,0 +1,212 @@
"""Один прогон трека 2: сухие планы, применение, повтор и проверка живых файлов.
Запускать внутри API-контейнера: там есть ключ bucket и строка подключения,
а наружу они не печатаются.
"""
import base64
import json
import urllib.error
import urllib.request
import uuid
from datetime import datetime, timedelta, timezone
from io import BytesIO
import psycopg
from minio import Minio
from PIL import Image
from blobs import BUCKET, read_secret
from reconcile import plan
BASE = "http://127.0.0.1:8080"
def call(method, path, body=None, token=None, raw=None, content_type=None, status=200):
data = raw
headers = {}
if body is not None:
data = json.dumps(body).encode("utf-8")
headers["Content-Type"] = "application/json"
if raw is not None:
headers["Content-Type"] = content_type
if token:
headers["Authorization"] = "Bearer " + token
if method == "POST" and path.endswith("/messages"):
headers["Idempotency-Key"] = uuid.uuid4().hex
request = urllib.request.Request(BASE + path, data=data, headers=headers, method=method)
try:
with urllib.request.urlopen(request, timeout=30) as response:
payload = response.read()
code = response.status
mime = response.headers.get("Content-Type", "")
except urllib.error.HTTPError as exc:
payload = exc.read()
code = exc.status
mime = exc.headers.get("Content-Type", "")
if code != status:
raise SystemExit("expected {} got {} for {} {}".format(status, code, method, path))
if "application/json" in mime:
return json.loads(payload.decode("utf-8"))
return payload
def user():
name = "u" + uuid.uuid4().hex[:12]
password = "pw-" + uuid.uuid4().hex
created = call("POST", "/api/v1/users", {"username": name, "password": password, "display_name": name}, status=201)
basic = base64.b64encode((name + ":" + password).encode("utf-8")).decode("ascii")
request = urllib.request.Request(
BASE + "/api/v1/auth/sessions",
data=b"",
headers={"Authorization": "Basic " + basic},
method="POST",
)
with urllib.request.urlopen(request, timeout=30) as response:
session = json.loads(response.read().decode("utf-8"))
return created, session["token"]
def png(color):
image = Image.new("RGB", (32, 24), color)
buffer = BytesIO()
image.save(buffer, "PNG")
return buffer.getvalue()
def upload(token, chat_id, data, filename):
return call(
"POST",
"/api/v1/chats/" + chat_id + "/attachments?filename=" + filename,
token=token,
raw=data,
content_type="image/png",
status=201,
)
def main():
alice, alice_token = user()
bob, bob_token = user()
chat = call(
"POST",
"/api/v1/chats",
{"title": "track2", "member_ids": [alice["id"], bob["id"]]},
token=alice_token,
status=201,
)
picture_a = png((255, 0, 0))
picture_b = png((0, 255, 0))
picture_c = png((0, 0, 255))
picture_d = png((255, 255, 0))
attachment_a = upload(alice_token, chat["id"], picture_a, "used.png")
attachment_b = upload(alice_token, chat["id"], picture_b, "fresh.png")
attachment_c = upload(alice_token, chat["id"], picture_c, "stale.png")
attachment_d = upload(alice_token, chat["id"], picture_d, "linked-missing.png")
call(
"POST",
"/api/v1/chats/" + chat["id"] + "/messages",
{"text": "", "attachment_ids": [attachment_a["id"]]},
token=alice_token,
status=201,
)
call(
"POST",
"/api/v1/chats/" + chat["id"] + "/messages",
{"text": "used-missing", "attachment_ids": [attachment_d["id"]]},
token=alice_token,
status=201,
)
endpoint = "minio:9000"
storage = Minio(
endpoint,
access_key=read_secret("/run/secrets/s3_access_key"),
secret_key=read_secret("/run/secrets/s3_secret_key"),
secure=False,
)
with psycopg.connect(open("/run/secrets/database_url", encoding="utf-8").read().strip()) as conn:
keys = dict(conn.execute(
"SELECT id::text, object_key FROM attachments WHERE id = ANY(%s::uuid[])",
([attachment_c["id"], attachment_d["id"]],),
).fetchall())
conn.execute(
"""
UPDATE attachments
SET created_at = now() - interval '2 hours',
updated_at = now() - interval '2 hours'
WHERE id = ANY(%s::uuid[])
""",
([attachment_c["id"], attachment_d["id"]],),
)
conn.commit()
storage.remove_object(BUCKET, keys[attachment_c["id"]])
storage.remove_object(BUCKET, keys[attachment_d["id"]])
old_key = "chats/" + chat["id"] + "/attachments/" + str(uuid.uuid4()) + "/original"
fresh_key = "chats/" + chat["id"] + "/attachments/" + str(uuid.uuid4()) + "/original"
old_stamp = (datetime.now(timezone.utc) - timedelta(hours=2)).strftime("%Y-%m-%dT%H:%M:%SZ")
fresh_stamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
storage.put_object(
BUCKET, old_key, BytesIO(b"old-orphan"), 10, metadata={"created-at": old_stamp}
)
storage.put_object(
BUCKET, fresh_key, BytesIO(b"fresh-orphan"), 12, metadata={"created-at": fresh_stamp}
)
before = plan(120)
from reconcile import apply_plan
applied = apply_plan(dict(before))
after = plan(120)
downloaded_a = call("GET", "/api/v1/attachments/" + attachment_a["id"] + "/content", token=bob_token)
downloaded_b = call("GET", "/api/v1/attachments/" + attachment_b["id"] + "/content", token=bob_token)
call("GET", "/api/v1/attachments/" + attachment_d["id"], token=bob_token)
call("GET", "/api/v1/attachments/" + attachment_d["id"] + "/content", token=bob_token, status=404)
call("GET", "/api/v1/attachments/" + attachment_c["id"], token=bob_token, status=404)
try:
storage.stat_object(BUCKET, old_key)
old_gone = False
except Exception:
old_gone = True
try:
storage.stat_object(BUCKET, fresh_key)
fresh_kept = True
except Exception:
fresh_kept = False
delete_actions = [item["action"] for item in before["actions"]]
report = {
"dry_run_actions": delete_actions,
"applied_objects": applied.get("deleted_objects"),
"applied_rows": applied.get("deleted_rows"),
"second_run_actions": [item["action"] for item in after["actions"]],
"list_seconds": before["list_seconds"],
"objects_seen": before["objects"],
"rows_seen": before["rows"],
"preserved_reasons": sorted({item["reason"] for item in before["preserved"]}),
"used_file_same": downloaded_a == picture_a,
"fresh_file_same": downloaded_b == picture_b,
"old_orphan_removed": old_gone,
"fresh_orphan_kept": fresh_kept,
"in_use_missing_preserved": any(
item.get("attachment_id") == attachment_d["id"] for item in after["preserved"]
),
}
print(json.dumps(report, ensure_ascii=False, sort_keys=True))
checks = [
"delete_orphan_object" in delete_actions,
"delete_orphan_row" in delete_actions,
report["second_run_actions"] == [],
report["used_file_same"] and report["fresh_file_same"],
report["old_orphan_removed"] and report["fresh_orphan_kept"],
report["in_use_missing_preserved"],
"fresh_object" in report["preserved_reasons"],
"missing_but_in_use" in report["preserved_reasons"],
]
if not all(checks):
raise SystemExit(1)
if __name__ == "__main__":
main()