forked from mtusi2026/mtusi2026lab4
Реализовать lab4 на оценку 4: SeaweedFS, вложения и согласованность БД/S3.
Перенесён стенд lab3 (API, Redis-сессии, идемпотентность, HAProxy, реплики API). Добавлены приватный bucket SeaweedFS с отдельным ключом API, загрузка PNG/JPEG с лимитами и полной проверкой, компенсация и reconciler, плавная остановка API, тесты и evidence.
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""Messenger API for lab4 (LB + shared sessions + idempotent messages + S3 attachments)."""
|
||||
@@ -0,0 +1,36 @@
|
||||
"""Run the messenger HTTP server."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_SRC = Path(__file__).resolve().parents[1]
|
||||
if str(_SRC) not in sys.path:
|
||||
sys.path.insert(0, str(_SRC))
|
||||
|
||||
import uvicorn
|
||||
|
||||
from messenger import config, lifecycle
|
||||
|
||||
|
||||
def main() -> None:
|
||||
server = lifecycle.DrainingServer(
|
||||
uvicorn.Config(
|
||||
"messenger.app:app",
|
||||
host=config.app_host(),
|
||||
port=config.app_port(),
|
||||
log_level="info",
|
||||
access_log=False,
|
||||
timeout_keep_alive=5,
|
||||
timeout_graceful_shutdown=config.shutdown_timeout_seconds(),
|
||||
),
|
||||
drain_seconds=config.shutdown_drain_seconds(),
|
||||
)
|
||||
server.run()
|
||||
if not server.started:
|
||||
sys.exit(3)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,823 @@
|
||||
"""HTTP API: multi-replica messenger behind LB with attachments in private S3 (lab4)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import urllib.parse
|
||||
import uuid
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, List, Optional, Tuple
|
||||
|
||||
from fastapi import FastAPI, Header, Query, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse, Response, StreamingResponse
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
from starlette.requests import ClientDisconnect
|
||||
|
||||
from messenger import attachments, config, db, lifecycle, reconcile, s3, sessions
|
||||
from messenger.sessions import SessionStoreError
|
||||
from messenger.store import Attachment, AttachmentNotFound, IntentLost, Store, StoreUnavailable, format_ts
|
||||
|
||||
USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}\Z")
|
||||
UUID_RE = re.compile(
|
||||
r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\Z"
|
||||
)
|
||||
IDEMPOTENCY_KEY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}\Z")
|
||||
BODY_READ_TIMEOUT_S = 5.0
|
||||
PASSWORD_MIN = 12
|
||||
PASSWORD_MAX = 128
|
||||
|
||||
store = Store()
|
||||
ready = False
|
||||
upload_slots: Optional[asyncio.Semaphore] = None
|
||||
INSTANCE_ID = config.instance_id()
|
||||
VARIANT_NAMES = ("thumbnail", "crop", "optimized")
|
||||
UPLOAD_SLOT_WAIT_S = 5.0
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(message)s",
|
||||
)
|
||||
log = logging.getLogger("messenger")
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app: FastAPI):
|
||||
# SIGTERM/SIGINT are handled by lifecycle.DrainingServer: readiness goes 503 first,
|
||||
# requests are served through the drain window and this shutdown runs last.
|
||||
global ready, upload_slots
|
||||
db.init_pool()
|
||||
# Migrations run once via `python -m messenger.migrate` (compose migrate service).
|
||||
sessions.init_client()
|
||||
s3.init_client()
|
||||
attachments.prepare_spool_dir()
|
||||
upload_slots = asyncio.Semaphore(config.max_concurrent_uploads())
|
||||
reconcile.start_background()
|
||||
ready = True
|
||||
log.info("messenger started instance_id=%s", INSTANCE_ID)
|
||||
yield
|
||||
ready = False
|
||||
reconcile.stop_background()
|
||||
sessions.close_client()
|
||||
db.close_pool()
|
||||
log.info("messenger stopped")
|
||||
|
||||
|
||||
def request_id_from(request: Request) -> str:
|
||||
incoming = request.headers.get("x-request-id")
|
||||
if incoming and incoming.strip():
|
||||
return incoming.strip()[:128]
|
||||
return str(uuid.uuid4())
|
||||
|
||||
|
||||
def error_body(code: str, message: str, request_id: str) -> dict:
|
||||
return {"error": {"code": code, "message": message, "request_id": request_id}}
|
||||
|
||||
|
||||
def common_headers(request_id: str, extra: Optional[dict] = None) -> dict:
|
||||
headers = {"X-Request-Id": request_id, "X-Instance-Id": INSTANCE_ID}
|
||||
if extra:
|
||||
headers.update(extra)
|
||||
return headers
|
||||
|
||||
|
||||
def error_response(
|
||||
status: int,
|
||||
code: str,
|
||||
message: str,
|
||||
request_id: str,
|
||||
www_authenticate: Optional[str] = None,
|
||||
extra_headers: Optional[dict] = None,
|
||||
) -> JSONResponse:
|
||||
headers = common_headers(request_id, extra_headers)
|
||||
if www_authenticate:
|
||||
headers["WWW-Authenticate"] = www_authenticate
|
||||
return JSONResponse(
|
||||
status_code=status,
|
||||
content=error_body(code, message, request_id),
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
|
||||
def is_blank(value: str) -> bool:
|
||||
return value.strip() == ""
|
||||
|
||||
|
||||
def has_nul(value: str) -> bool:
|
||||
# Names/titles/passwords live in PostgreSQL TEXT, which cannot store U+0000.
|
||||
return "\x00" in value
|
||||
|
||||
|
||||
def has_lone_surrogate(value: str) -> bool:
|
||||
return any(0xD800 <= ord(ch) <= 0xDFFF for ch in value)
|
||||
|
||||
|
||||
def codepoint_len(value: str) -> int:
|
||||
return len(value)
|
||||
|
||||
|
||||
def parse_uuid(value: str) -> Optional[str]:
|
||||
if not isinstance(value, str) or not UUID_RE.match(value):
|
||||
return None
|
||||
try:
|
||||
return str(uuid.UUID(value))
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def encode_cursor(resource: str, created_at: datetime, item_id: str) -> str:
|
||||
raw = f"{resource}|{created_at.strftime('%Y-%m-%dT%H:%M:%SZ')}|{item_id}"
|
||||
return base64.urlsafe_b64encode(raw.encode("utf-8")).decode("ascii")
|
||||
|
||||
|
||||
def decode_cursor(cursor: str, expected_resource: str) -> Tuple[datetime, uuid.UUID]:
|
||||
try:
|
||||
raw = base64.urlsafe_b64decode(cursor.encode("ascii")).decode("utf-8")
|
||||
resource, ts, item_id = raw.split("|", 2)
|
||||
if resource != expected_resource:
|
||||
raise ValueError("wrong resource")
|
||||
created_at = datetime.strptime(ts, "%Y-%m-%dT%H:%M:%SZ").replace(
|
||||
tzinfo=timezone.utc
|
||||
)
|
||||
return created_at, uuid.UUID(item_id)
|
||||
except Exception as exc:
|
||||
raise ValueError("invalid cursor") from exc
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title="MTUSI Messenger lab4",
|
||||
docs_url=None,
|
||||
redoc_url=None,
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def add_request_id_and_gate(request: Request, call_next):
|
||||
rid = request_id_from(request)
|
||||
request.state.request_id = rid
|
||||
|
||||
path = request.url.path
|
||||
if not ready and path not in ("/health/live",):
|
||||
if path == "/health/ready":
|
||||
return error_response(503, "unavailable", "Shutting down", rid)
|
||||
return error_response(503, "unavailable", "Service unavailable", rid)
|
||||
|
||||
response = await call_next(request)
|
||||
if "X-Request-Id" not in response.headers:
|
||||
response.headers["X-Request-Id"] = rid
|
||||
response.headers["X-Instance-Id"] = INSTANCE_ID
|
||||
log.info(
|
||||
"%s %s -> %s request_id=%s instance_id=%s",
|
||||
request.method,
|
||||
path,
|
||||
response.status_code,
|
||||
rid,
|
||||
INSTANCE_ID,
|
||||
)
|
||||
return response
|
||||
|
||||
|
||||
class ApiError(Exception):
|
||||
def __init__(
|
||||
self,
|
||||
status: int,
|
||||
code: str,
|
||||
message: str,
|
||||
www_authenticate: Optional[str] = None,
|
||||
headers: Optional[dict] = None,
|
||||
):
|
||||
self.status = status
|
||||
self.code = code
|
||||
self.message = message
|
||||
self.www_authenticate = www_authenticate
|
||||
self.headers = headers
|
||||
|
||||
|
||||
@app.exception_handler(ApiError)
|
||||
async def api_error_handler(request: Request, exc: ApiError):
|
||||
rid = getattr(request.state, "request_id", None) or request_id_from(request)
|
||||
return error_response(
|
||||
exc.status,
|
||||
exc.code,
|
||||
exc.message,
|
||||
rid,
|
||||
www_authenticate=exc.www_authenticate,
|
||||
extra_headers=exc.headers,
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_handler(request: Request, exc: RequestValidationError):
|
||||
rid = getattr(request.state, "request_id", None) or request_id_from(request)
|
||||
return error_response(400, "invalid_request", "Invalid request", rid)
|
||||
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
|
||||
rid = getattr(request.state, "request_id", None) or request_id_from(request)
|
||||
if exc.status_code == 404:
|
||||
return error_response(404, "not_found", "Not found", rid)
|
||||
if exc.status_code == 405:
|
||||
return error_response(400, "invalid_request", "Method not allowed", rid)
|
||||
return error_response(exc.status_code, "invalid_request", "Request failed", rid)
|
||||
|
||||
|
||||
@app.exception_handler(StoreUnavailable)
|
||||
async def store_unavailable_handler(request: Request, exc: StoreUnavailable):
|
||||
rid = getattr(request.state, "request_id", None) or request_id_from(request)
|
||||
return error_response(503, "unavailable", "Database unavailable", rid)
|
||||
|
||||
|
||||
@app.exception_handler(SessionStoreError)
|
||||
async def session_store_unavailable_handler(request: Request, exc: SessionStoreError):
|
||||
rid = getattr(request.state, "request_id", None) or request_id_from(request)
|
||||
return error_response(503, "unavailable", "Session store unavailable", rid)
|
||||
|
||||
|
||||
@app.exception_handler(s3.S3Unavailable)
|
||||
async def s3_unavailable_handler(request: Request, exc: s3.S3Unavailable):
|
||||
rid = getattr(request.state, "request_id", None) or request_id_from(request)
|
||||
return error_response(503, "unavailable", "Attachment storage unavailable", rid)
|
||||
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def unhandled_handler(request: Request, exc: Exception):
|
||||
rid = getattr(request.state, "request_id", None) or request_id_from(request)
|
||||
log.exception("unhandled error request_id=%s", rid)
|
||||
return error_response(500, "internal_error", "Internal error", rid)
|
||||
|
||||
|
||||
async def read_json_object(request: Request) -> Any:
|
||||
content_type = request.headers.get("content-type", "")
|
||||
media = content_type.split(";")[0].strip().lower()
|
||||
if media and media != "application/json":
|
||||
raise ApiError(415, "unsupported_media_type", "Unsupported media type")
|
||||
try:
|
||||
body = await asyncio.wait_for(request.body(), timeout=BODY_READ_TIMEOUT_S)
|
||||
except asyncio.TimeoutError:
|
||||
raise ApiError(400, "invalid_request", "Request body timeout")
|
||||
if not body:
|
||||
raise ApiError(400, "invalid_request", "Empty body")
|
||||
try:
|
||||
text = body.decode("utf-8")
|
||||
# Reject trailing garbage after one JSON value (read to EOF).
|
||||
data, end = json.JSONDecoder().raw_decode(text)
|
||||
if text[end:].strip():
|
||||
raise ApiError(400, "invalid_request", "Malformed JSON")
|
||||
except ApiError:
|
||||
raise
|
||||
except (UnicodeDecodeError, json.JSONDecodeError, ValueError):
|
||||
raise ApiError(400, "invalid_request", "Malformed JSON")
|
||||
if not isinstance(data, dict):
|
||||
raise ApiError(400, "invalid_request", "JSON object required")
|
||||
return data
|
||||
|
||||
def require_bearer(authorization: Optional[str]) -> Tuple[str, str]:
|
||||
"""Return (user_id, token). X-User-Id is ignored."""
|
||||
bearer_challenge = 'Bearer realm="messenger"'
|
||||
if not authorization or not authorization.strip():
|
||||
raise ApiError(
|
||||
401, "unauthorized", "Missing bearer token", www_authenticate=bearer_challenge
|
||||
)
|
||||
parts = authorization.strip().split(None, 1)
|
||||
if len(parts) != 2 or parts[0].lower() != "bearer" or not parts[1].strip():
|
||||
# Basic on business endpoints must not work.
|
||||
raise ApiError(
|
||||
401, "unauthorized", "Invalid authorization", www_authenticate=bearer_challenge
|
||||
)
|
||||
token = parts[1].strip()
|
||||
try:
|
||||
session = sessions.get_session(token)
|
||||
except SessionStoreError:
|
||||
raise ApiError(503, "unavailable", "Session store unavailable")
|
||||
if session is None:
|
||||
raise ApiError(
|
||||
401, "unauthorized", "Invalid or expired session", www_authenticate=bearer_challenge
|
||||
)
|
||||
user_id = session["user_id"]
|
||||
user = store.get_user(user_id)
|
||||
if user is None:
|
||||
raise ApiError(
|
||||
401, "unauthorized", "Invalid or expired session", www_authenticate=bearer_challenge
|
||||
)
|
||||
return user_id, token
|
||||
|
||||
|
||||
def require_chat_member(chat_id_raw: str, user_id: str):
|
||||
chat_id = parse_uuid(chat_id_raw)
|
||||
if chat_id is None:
|
||||
raise ApiError(400, "invalid_request", "Invalid chat_id")
|
||||
chat = store.get_chat(chat_id)
|
||||
if chat is None or user_id not in chat.member_ids:
|
||||
raise ApiError(404, "not_found", "Chat not found")
|
||||
return chat
|
||||
|
||||
|
||||
def parse_limit(limit: Optional[int]) -> int:
|
||||
if limit is None:
|
||||
return 50
|
||||
if not isinstance(limit, int) or isinstance(limit, bool) or limit < 1 or limit > 100:
|
||||
raise ApiError(400, "invalid_request", "Invalid limit")
|
||||
return limit
|
||||
|
||||
|
||||
def validate_display_text(value: Any, field: str, max_len: int) -> str:
|
||||
if not isinstance(value, str) or is_blank(value) or has_nul(value):
|
||||
raise ApiError(400, "invalid_request", f"Invalid {field}")
|
||||
if has_lone_surrogate(value):
|
||||
raise ApiError(400, "invalid_request", f"Invalid {field}")
|
||||
length = codepoint_len(value)
|
||||
if length < 1 or length > max_len:
|
||||
raise ApiError(400, "invalid_request", f"Invalid {field}")
|
||||
return value
|
||||
|
||||
|
||||
def validate_password(value: Any) -> str:
|
||||
# Required strings must not be whitespace-only (contracts/README).
|
||||
if not isinstance(value, str) or is_blank(value) or has_nul(value):
|
||||
raise ApiError(400, "invalid_request", "Invalid password")
|
||||
if has_lone_surrogate(value):
|
||||
raise ApiError(400, "invalid_request", "Invalid password")
|
||||
length = codepoint_len(value)
|
||||
if length < PASSWORD_MIN or length > PASSWORD_MAX:
|
||||
raise ApiError(400, "invalid_request", "Invalid password")
|
||||
return value
|
||||
|
||||
|
||||
def parse_basic_credentials(authorization: Optional[str]) -> Tuple[str, str]:
|
||||
challenge = 'Basic realm="messenger", charset="UTF-8"'
|
||||
if not authorization or not authorization.strip():
|
||||
raise ApiError(
|
||||
401, "unauthorized", "Invalid credentials", www_authenticate=challenge
|
||||
)
|
||||
parts = authorization.strip().split(None, 1)
|
||||
if len(parts) != 2 or parts[0].lower() != "basic":
|
||||
raise ApiError(
|
||||
401, "unauthorized", "Invalid credentials", www_authenticate=challenge
|
||||
)
|
||||
try:
|
||||
decoded = base64.b64decode(parts[1].strip(), validate=True).decode("utf-8")
|
||||
except Exception:
|
||||
raise ApiError(
|
||||
401, "unauthorized", "Invalid credentials", www_authenticate=challenge
|
||||
)
|
||||
if ":" not in decoded:
|
||||
raise ApiError(
|
||||
401, "unauthorized", "Invalid credentials", www_authenticate=challenge
|
||||
)
|
||||
username, password = decoded.split(":", 1)
|
||||
# Username ASCII-only per contract; password may contain ':'.
|
||||
if not username or any(ord(ch) > 127 for ch in username):
|
||||
raise ApiError(
|
||||
401, "unauthorized", "Invalid credentials", www_authenticate=challenge
|
||||
)
|
||||
return username, password
|
||||
|
||||
|
||||
@app.get("/health/live")
|
||||
async def liveness(request: Request):
|
||||
rid = request.state.request_id
|
||||
return JSONResponse(content={"status": "ok"}, headers=common_headers(rid))
|
||||
|
||||
|
||||
@app.get("/health/ready")
|
||||
async def readiness(request: Request):
|
||||
rid = request.state.request_id
|
||||
if not ready:
|
||||
return error_response(503, "unavailable", "Not ready", rid)
|
||||
if lifecycle.draining:
|
||||
# Only readiness reflects the drain: other endpoints keep serving until the
|
||||
# LB has stopped routing here and the listener is closed.
|
||||
return error_response(503, "unavailable", "Shutting down", rid)
|
||||
# Mandatory synchronous path in lab4 = sessions + metadata + attachment bytes,
|
||||
# so PostgreSQL, Redis and S3 are all readiness dependencies.
|
||||
if not await run_in_threadpool(_dependencies_ok):
|
||||
return error_response(503, "unavailable", "Dependency unavailable", rid)
|
||||
return JSONResponse(content={"status": "ok"}, headers=common_headers(rid))
|
||||
|
||||
|
||||
def _dependencies_ok() -> bool:
|
||||
return db.ping() and sessions.ping() and s3.ping()
|
||||
|
||||
|
||||
@app.post("/api/v1/users")
|
||||
async def register_user(request: Request):
|
||||
rid = request.state.request_id
|
||||
data = await read_json_object(request)
|
||||
allowed = {"username", "display_name", "password"}
|
||||
if set(data.keys()) - allowed:
|
||||
raise ApiError(400, "invalid_request", "Unexpected fields")
|
||||
if "username" not in data or "display_name" not in data or "password" not in data:
|
||||
raise ApiError(400, "invalid_request", "Missing required fields")
|
||||
username = data["username"]
|
||||
display_name = data["display_name"]
|
||||
if (
|
||||
not isinstance(username, str)
|
||||
or is_blank(username)
|
||||
or has_lone_surrogate(username)
|
||||
or not USERNAME_RE.match(username)
|
||||
):
|
||||
raise ApiError(400, "invalid_request", "Invalid username")
|
||||
display_name = validate_display_text(display_name, "display_name", 100)
|
||||
password = validate_password(data["password"])
|
||||
try:
|
||||
user = store.create_user(username, display_name, password)
|
||||
except KeyError:
|
||||
raise ApiError(409, "conflict", "Username already taken")
|
||||
return JSONResponse(
|
||||
status_code=201,
|
||||
content=user.to_dict(),
|
||||
headers=common_headers(rid),
|
||||
)
|
||||
|
||||
|
||||
@app.post("/api/v1/auth/sessions")
|
||||
async def create_session(request: Request):
|
||||
rid = request.state.request_id
|
||||
challenge = 'Basic realm="messenger", charset="UTF-8"'
|
||||
# Contract: Basic only, no JSON body (even with valid credentials).
|
||||
try:
|
||||
raw_body = await asyncio.wait_for(request.body(), timeout=BODY_READ_TIMEOUT_S)
|
||||
except asyncio.TimeoutError:
|
||||
raise ApiError(400, "invalid_request", "Request body timeout")
|
||||
if raw_body and raw_body.strip():
|
||||
raise ApiError(400, "invalid_request", "Login must not include a body")
|
||||
username, password = parse_basic_credentials(
|
||||
request.headers.get("authorization")
|
||||
)
|
||||
# Uniform 401 for wrong user / wrong password (no user enumeration).
|
||||
user = store.get_user_by_username(username)
|
||||
if user is None or not store.verify_password(user.password_hash, password):
|
||||
raise ApiError(
|
||||
401, "unauthorized", "Invalid credentials", www_authenticate=challenge
|
||||
)
|
||||
try:
|
||||
session = sessions.create_session(user.id)
|
||||
except SessionStoreError:
|
||||
raise ApiError(503, "unavailable", "Session store unavailable")
|
||||
body = {
|
||||
"token": session["token"],
|
||||
"token_type": "Bearer",
|
||||
"expires_at": session["expires_at"],
|
||||
"user": user.to_dict(),
|
||||
}
|
||||
return JSONResponse(
|
||||
status_code=201, content=body, headers=common_headers(rid)
|
||||
)
|
||||
|
||||
|
||||
@app.delete("/api/v1/auth/sessions/current")
|
||||
async def logout(
|
||||
request: Request,
|
||||
authorization: Optional[str] = Header(default=None, alias="Authorization"),
|
||||
):
|
||||
rid = request.state.request_id
|
||||
_user_id, token = require_bearer(authorization)
|
||||
try:
|
||||
sessions.revoke_session(token)
|
||||
except SessionStoreError:
|
||||
raise ApiError(503, "unavailable", "Session store unavailable")
|
||||
return Response(status_code=204, headers=common_headers(rid))
|
||||
|
||||
|
||||
@app.get("/api/v1/users/me")
|
||||
async def current_user(
|
||||
request: Request,
|
||||
authorization: Optional[str] = Header(default=None, alias="Authorization"),
|
||||
):
|
||||
rid = request.state.request_id
|
||||
user_id, _token = require_bearer(authorization)
|
||||
user = store.get_user(user_id)
|
||||
assert user is not None
|
||||
return JSONResponse(content=user.to_dict(), headers=common_headers(rid))
|
||||
|
||||
|
||||
@app.post("/api/v1/chats")
|
||||
async def create_chat(
|
||||
request: Request,
|
||||
authorization: Optional[str] = Header(default=None, alias="Authorization"),
|
||||
):
|
||||
rid = request.state.request_id
|
||||
user_id, _token = require_bearer(authorization)
|
||||
data = await read_json_object(request)
|
||||
allowed = {"title", "member_ids"}
|
||||
if set(data.keys()) - allowed:
|
||||
raise ApiError(400, "invalid_request", "Unexpected fields")
|
||||
if "title" not in data or "member_ids" not in data:
|
||||
raise ApiError(400, "invalid_request", "Missing required fields")
|
||||
title = validate_display_text(data["title"], "title", 100)
|
||||
member_ids = data["member_ids"]
|
||||
if not isinstance(member_ids, list) or not member_ids or len(member_ids) > 100:
|
||||
raise ApiError(400, "invalid_request", "Invalid member_ids")
|
||||
parsed: List[str] = []
|
||||
seen = set()
|
||||
for mid in member_ids:
|
||||
if not isinstance(mid, str):
|
||||
raise ApiError(400, "invalid_request", "Invalid member_ids")
|
||||
uid = parse_uuid(mid)
|
||||
if uid is None:
|
||||
raise ApiError(400, "invalid_request", "Invalid member_ids")
|
||||
if uid in seen:
|
||||
raise ApiError(400, "invalid_request", "Duplicate member_ids")
|
||||
seen.add(uid)
|
||||
parsed.append(uid)
|
||||
if user_id not in seen:
|
||||
raise ApiError(400, "invalid_request", "Caller must be a member")
|
||||
try:
|
||||
chat = store.create_chat(title, parsed)
|
||||
except KeyError:
|
||||
raise ApiError(400, "invalid_request", "Unknown member")
|
||||
return JSONResponse(
|
||||
status_code=201,
|
||||
content=chat.to_dict(),
|
||||
headers=common_headers(rid),
|
||||
)
|
||||
|
||||
|
||||
@app.get("/api/v1/chats")
|
||||
async def list_chats(
|
||||
request: Request,
|
||||
authorization: Optional[str] = Header(default=None, alias="Authorization"),
|
||||
limit: Optional[int] = Query(default=None),
|
||||
cursor: Optional[str] = Query(default=None),
|
||||
):
|
||||
rid = request.state.request_id
|
||||
user_id, _token = require_bearer(authorization)
|
||||
lim = parse_limit(limit)
|
||||
resource = f"chats:{user_id}"
|
||||
cursor_key = None
|
||||
if cursor is not None:
|
||||
if not cursor:
|
||||
raise ApiError(400, "invalid_request", "Invalid cursor")
|
||||
try:
|
||||
cursor_ts, cursor_id = decode_cursor(cursor, resource)
|
||||
except ValueError:
|
||||
raise ApiError(400, "invalid_request", "Invalid cursor")
|
||||
if not store.chat_exists_for_user(user_id, cursor_ts, cursor_id):
|
||||
raise ApiError(400, "invalid_request", "Invalid cursor")
|
||||
cursor_key = (cursor_ts, cursor_id)
|
||||
chats, more = store.list_chats_for_user(user_id, lim, cursor_key)
|
||||
next_cursor = None
|
||||
if more and chats:
|
||||
last = chats[-1]
|
||||
next_cursor = encode_cursor(resource, last.created_at, last.id)
|
||||
return JSONResponse(
|
||||
content={"items": [c.to_dict() for c in chats], "next_cursor": next_cursor},
|
||||
headers=common_headers(rid),
|
||||
)
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}")
|
||||
async def get_chat(
|
||||
chat_id: str,
|
||||
request: Request,
|
||||
authorization: Optional[str] = Header(default=None, alias="Authorization"),
|
||||
):
|
||||
rid = request.state.request_id
|
||||
user_id, _token = require_bearer(authorization)
|
||||
chat = require_chat_member(chat_id, user_id)
|
||||
return JSONResponse(content=chat.to_dict(), headers=common_headers(rid))
|
||||
|
||||
|
||||
def parse_attachment_ids(raw: Any) -> List[str]:
|
||||
if not isinstance(raw, list) or len(raw) > 10:
|
||||
raise ApiError(400, "invalid_request", "Invalid attachment_ids")
|
||||
parsed: List[str] = []
|
||||
for item in raw:
|
||||
aid = parse_uuid(item) if isinstance(item, str) else None
|
||||
if aid is None or aid in parsed:
|
||||
raise ApiError(400, "invalid_request", "Invalid attachment_ids")
|
||||
parsed.append(aid)
|
||||
return parsed
|
||||
|
||||
|
||||
def parse_idempotency_key(raw: Optional[str]) -> str:
|
||||
if raw is None or not raw.strip() or not IDEMPOTENCY_KEY_RE.match(raw.strip()):
|
||||
raise ApiError(400, "invalid_request", "Invalid or missing Idempotency-Key")
|
||||
return raw.strip()
|
||||
|
||||
|
||||
@app.post("/api/v1/chats/{chat_id}/messages")
|
||||
async def create_message(
|
||||
chat_id: str,
|
||||
request: Request,
|
||||
authorization: Optional[str] = Header(default=None, alias="Authorization"),
|
||||
idempotency_key: Optional[str] = Header(default=None, alias="Idempotency-Key"),
|
||||
):
|
||||
rid = request.state.request_id
|
||||
user_id, _token = require_bearer(authorization)
|
||||
chat = require_chat_member(chat_id, user_id)
|
||||
key = parse_idempotency_key(idempotency_key)
|
||||
data = await read_json_object(request)
|
||||
allowed = {"text", "attachment_ids"}
|
||||
if set(data.keys()) - allowed:
|
||||
raise ApiError(400, "invalid_request", "Unexpected fields")
|
||||
if "text" not in data:
|
||||
raise ApiError(400, "invalid_request", "Missing text")
|
||||
attachment_ids = parse_attachment_ids(data.get("attachment_ids", []))
|
||||
text = data["text"]
|
||||
# U+0000 is a valid code point of message text (stored as UTF-8 bytes, see 004 migration).
|
||||
if (
|
||||
not isinstance(text, str)
|
||||
or has_lone_surrogate(text)
|
||||
or codepoint_len(text) > 4000
|
||||
):
|
||||
raise ApiError(400, "invalid_request", "Invalid text")
|
||||
# Empty/whitespace text is allowed only together with at least one attachment.
|
||||
if not attachment_ids and is_blank(text):
|
||||
raise ApiError(400, "invalid_request", "Invalid text")
|
||||
path = f"/api/v1/chats/{chat.id}/messages"
|
||||
try:
|
||||
message, _replayed = store.create_message_idempotent(
|
||||
chat.id, user_id, text, attachment_ids, "POST", path, key
|
||||
)
|
||||
except KeyError:
|
||||
raise ApiError(409, "conflict", "Idempotency-Key reused with different body")
|
||||
except AttachmentNotFound:
|
||||
raise ApiError(404, "not_found", "Attachment not found")
|
||||
except ValueError:
|
||||
raise ApiError(400, "invalid_request", "Invalid text")
|
||||
return JSONResponse(
|
||||
status_code=201,
|
||||
content=message.to_dict(),
|
||||
headers=common_headers(rid),
|
||||
)
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}/messages")
|
||||
async def list_messages(
|
||||
chat_id: str,
|
||||
request: Request,
|
||||
authorization: Optional[str] = Header(default=None, alias="Authorization"),
|
||||
limit: Optional[int] = Query(default=None),
|
||||
cursor: Optional[str] = Query(default=None),
|
||||
):
|
||||
rid = request.state.request_id
|
||||
user_id, _token = require_bearer(authorization)
|
||||
chat = require_chat_member(chat_id, user_id)
|
||||
lim = parse_limit(limit)
|
||||
resource = f"messages:{chat.id}"
|
||||
cursor_key = None
|
||||
if cursor is not None:
|
||||
if not cursor:
|
||||
raise ApiError(400, "invalid_request", "Invalid cursor")
|
||||
try:
|
||||
cursor_ts, cursor_id = decode_cursor(cursor, resource)
|
||||
except ValueError:
|
||||
raise ApiError(400, "invalid_request", "Invalid cursor")
|
||||
if not store.message_exists(chat.id, cursor_ts, cursor_id):
|
||||
raise ApiError(400, "invalid_request", "Invalid cursor")
|
||||
cursor_key = (cursor_ts, cursor_id)
|
||||
messages, has_more = store.list_messages(chat.id, lim, cursor_key)
|
||||
next_cursor = None
|
||||
if has_more and messages:
|
||||
last = messages[-1]
|
||||
next_cursor = encode_cursor(resource, last.created_at, last.id)
|
||||
return JSONResponse(
|
||||
content={
|
||||
"items": [m.to_dict() for m in messages],
|
||||
"next_cursor": next_cursor,
|
||||
},
|
||||
headers=common_headers(rid),
|
||||
)
|
||||
|
||||
|
||||
def parse_content_length(raw: Optional[str]) -> Optional[int]:
|
||||
if raw is None:
|
||||
return None
|
||||
if not raw.strip().isdigit():
|
||||
raise ApiError(400, "invalid_request", "Invalid Content-Length")
|
||||
return int(raw.strip())
|
||||
|
||||
|
||||
def require_attachment(attachment_id_raw: str, user_id: str) -> Attachment:
|
||||
attachment_id = parse_uuid(attachment_id_raw)
|
||||
if attachment_id is None:
|
||||
raise ApiError(400, "invalid_request", "Invalid attachment_id")
|
||||
att = store.get_attachment_for_user(attachment_id, user_id)
|
||||
if att is None:
|
||||
# Unknown and foreign attachments are indistinguishable.
|
||||
raise ApiError(404, "not_found", "Attachment not found")
|
||||
return att
|
||||
|
||||
|
||||
@app.post("/api/v1/chats/{chat_id}/attachments")
|
||||
async def upload_attachment(
|
||||
chat_id: str,
|
||||
request: Request,
|
||||
authorization: Optional[str] = Header(default=None, alias="Authorization"),
|
||||
):
|
||||
rid = request.state.request_id
|
||||
user_id, _token = require_bearer(authorization)
|
||||
# Input is validated before the chat lookup: a bad filename never reaches S3/DB queries.
|
||||
try:
|
||||
filename = attachments.validate_filename(attachments.query_filename(request.scope.get("query_string", b"")))
|
||||
content_type = attachments.declared_type(request.headers.get("content-type"))
|
||||
except attachments.UploadRejected as exc:
|
||||
raise ApiError(exc.status, exc.code, exc.message)
|
||||
chat = require_chat_member(chat_id, user_id)
|
||||
length = parse_content_length(request.headers.get("content-length"))
|
||||
if length is not None and length > config.max_upload_bytes():
|
||||
# Rejected before taking an upload slot; the body is drained (bounded), not stored.
|
||||
await attachments.drain_oversized(request.stream(), length)
|
||||
raise ApiError(413, "payload_too_large", "File exceeds 10 MiB")
|
||||
|
||||
assert upload_slots is not None
|
||||
try:
|
||||
await asyncio.wait_for(upload_slots.acquire(), timeout=UPLOAD_SLOT_WAIT_S)
|
||||
except asyncio.TimeoutError:
|
||||
raise ApiError(503, "unavailable", "Too many concurrent uploads", headers={"Retry-After": "1"})
|
||||
spooled = None
|
||||
try:
|
||||
try:
|
||||
spooled = await attachments.spool_upload(request.stream(), content_type, length)
|
||||
except attachments.UploadRejected as exc:
|
||||
raise ApiError(exc.status, exc.code, exc.message)
|
||||
except (attachments.ClientGone, ClientDisconnect):
|
||||
raise ApiError(400, "invalid_request", "Upload interrupted or timed out")
|
||||
try:
|
||||
att = await run_in_threadpool(
|
||||
attachments.persist,
|
||||
store,
|
||||
spooled,
|
||||
chat_id=chat.id,
|
||||
owner_id=user_id,
|
||||
filename=filename,
|
||||
instance=INSTANCE_ID,
|
||||
)
|
||||
except IntentLost:
|
||||
raise ApiError(503, "unavailable", "Upload expired, retry")
|
||||
finally:
|
||||
attachments.discard(spooled)
|
||||
upload_slots.release()
|
||||
return JSONResponse(
|
||||
status_code=201,
|
||||
content=att.to_dict(),
|
||||
headers=common_headers(rid, {"Location": f"/api/v1/attachments/{att.id}"}),
|
||||
)
|
||||
|
||||
|
||||
@app.get("/api/v1/attachments/{attachment_id}")
|
||||
async def get_attachment(
|
||||
attachment_id: str,
|
||||
request: Request,
|
||||
authorization: Optional[str] = Header(default=None, alias="Authorization"),
|
||||
):
|
||||
rid = request.state.request_id
|
||||
user_id, _token = require_bearer(authorization)
|
||||
att = require_attachment(attachment_id, user_id)
|
||||
return JSONResponse(content=att.to_dict(), headers=common_headers(rid))
|
||||
|
||||
|
||||
@app.get("/api/v1/attachments/{attachment_id}/content")
|
||||
async def download_attachment(
|
||||
attachment_id: str,
|
||||
request: Request,
|
||||
authorization: Optional[str] = Header(default=None, alias="Authorization"),
|
||||
variant: Optional[str] = Query(default=None),
|
||||
):
|
||||
rid = request.state.request_id
|
||||
user_id, _token = require_bearer(authorization)
|
||||
att = require_attachment(attachment_id, user_id)
|
||||
if variant is not None and variant != "original":
|
||||
if variant in VARIANT_NAMES:
|
||||
raise ApiError(404, "not_found", "Variant not found")
|
||||
raise ApiError(400, "invalid_request", "Invalid variant")
|
||||
try:
|
||||
length, chunks, body = await run_in_threadpool(s3.open_object, att.object_key)
|
||||
except s3.S3ObjectMissing:
|
||||
log.error("original missing in S3 attachment_id=%s request_id=%s", att.id, rid)
|
||||
raise ApiError(503, "unavailable", "Attachment content unavailable")
|
||||
if length != att.size_bytes:
|
||||
body.close()
|
||||
log.error("original size mismatch attachment_id=%s request_id=%s", att.id, rid)
|
||||
raise ApiError(503, "unavailable", "Attachment content unavailable")
|
||||
|
||||
def stream():
|
||||
try:
|
||||
yield from chunks
|
||||
finally:
|
||||
body.close()
|
||||
|
||||
headers = common_headers(
|
||||
rid,
|
||||
{
|
||||
"Content-Length": str(att.size_bytes),
|
||||
"ETag": f'"{att.sha256}"',
|
||||
"Cache-Control": "private, no-store",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
"Content-Disposition": "inline; filename*=UTF-8''" + urllib.parse.quote(att.filename, safe=""),
|
||||
},
|
||||
)
|
||||
return StreamingResponse(stream(), media_type=att.content_type, headers=headers)
|
||||
|
||||
|
||||
def create_app() -> FastAPI:
|
||||
return app
|
||||
@@ -0,0 +1,326 @@
|
||||
"""Attachment upload pipeline: bounded streaming intake, then intent → S3 PUT → metadata commit."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
import time
|
||||
import unicodedata
|
||||
import urllib.parse
|
||||
import uuid
|
||||
from dataclasses import dataclass
|
||||
from typing import AsyncIterator, Callable, Optional
|
||||
|
||||
from messenger import config, images, s3
|
||||
from messenger.store import Attachment, CommitUncertain, Store, StoreUnavailable, utc_now
|
||||
|
||||
log = logging.getLogger("messenger.attachments")
|
||||
|
||||
ALLOWED_TYPES = ("image/png", "image/jpeg")
|
||||
# Rejected bodies are drained (never stored) up to this many bytes so that the
|
||||
# client can read the error response instead of a connection reset.
|
||||
DRAIN_FACTOR = 2
|
||||
DECODE_TIMEOUT_S = 15
|
||||
DECODE_MEMORY_BYTES = 384 * 1024 * 1024
|
||||
_decode_slots = asyncio.Semaphore(1)
|
||||
|
||||
|
||||
class UploadRejected(Exception):
|
||||
def __init__(self, status: int, code: str, message: str):
|
||||
super().__init__(message)
|
||||
self.status = status
|
||||
self.code = code
|
||||
self.message = message
|
||||
|
||||
|
||||
class ClientGone(Exception):
|
||||
"""Client disconnected or stalled mid-upload; nothing was written to S3/DB."""
|
||||
|
||||
|
||||
class SimulatedCrash(BaseException):
|
||||
"""Fault-injection only: bypasses compensation like a killed process would."""
|
||||
|
||||
|
||||
def query_filename(query_string: bytes) -> Optional[str]:
|
||||
"""The single `filename` query value, percent-decoded strictly.
|
||||
|
||||
Starlette's query_params replace invalid UTF-8 with U+FFFD; such a name must be
|
||||
rejected, not silently rewritten.
|
||||
"""
|
||||
try:
|
||||
pairs = urllib.parse.parse_qsl(
|
||||
query_string.decode("ascii"), keep_blank_values=True, encoding="utf-8", errors="strict"
|
||||
)
|
||||
except (UnicodeDecodeError, ValueError):
|
||||
raise UploadRejected(400, "invalid_request", "Invalid filename") from None
|
||||
values = [v for k, v in pairs if k == "filename"]
|
||||
if len(values) > 1:
|
||||
raise UploadRejected(400, "invalid_request", "Invalid filename")
|
||||
return values[0] if values else None
|
||||
|
||||
|
||||
def validate_filename(value: Optional[str]) -> str:
|
||||
if value is None or not isinstance(value, str):
|
||||
raise UploadRejected(400, "invalid_request", "filename is required")
|
||||
if not 1 <= len(value) <= 255 or value.strip() == "" or value in (".", ".."):
|
||||
raise UploadRejected(400, "invalid_request", "Invalid filename")
|
||||
for ch in value:
|
||||
if ch in "/\\" or 0xD800 <= ord(ch) <= 0xDFFF:
|
||||
raise UploadRejected(400, "invalid_request", "Invalid filename")
|
||||
# Cc: NUL/control characters; Cf: bidi overrides (U+202E) and other invisible format chars.
|
||||
if unicodedata.category(ch) in ("Cc", "Cf"):
|
||||
raise UploadRejected(400, "invalid_request", "Invalid filename")
|
||||
return value
|
||||
|
||||
|
||||
def declared_type(header: Optional[str]) -> str:
|
||||
media = (header or "").split(";")[0].strip().lower()
|
||||
if media not in ALLOWED_TYPES:
|
||||
raise UploadRejected(415, "unsupported_media_type", "Only image/png and image/jpeg are accepted")
|
||||
return media
|
||||
|
||||
|
||||
def new_object_key() -> str:
|
||||
# Random, server-generated; carries no user input (filename/chat title).
|
||||
return s3.ORIGINAL_PREFIX + uuid.uuid4().hex
|
||||
|
||||
|
||||
@dataclass
|
||||
class Spooled:
|
||||
path: str
|
||||
size: int
|
||||
sha256: str
|
||||
content_type: str
|
||||
width: int
|
||||
height: int
|
||||
|
||||
|
||||
def prepare_spool_dir() -> None:
|
||||
"""Remove leftovers of requests interrupted by a crash; buffers never outlive a request."""
|
||||
root = config.spool_dir()
|
||||
if root.exists():
|
||||
shutil.rmtree(root, ignore_errors=True)
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
|
||||
async def _next_chunk(it: AsyncIterator[bytes], timeout: float) -> Optional[bytes]:
|
||||
try:
|
||||
return await asyncio.wait_for(it.__anext__(), timeout=timeout)
|
||||
except StopAsyncIteration:
|
||||
return None
|
||||
|
||||
|
||||
async def _drain(it: AsyncIterator[bytes], already: int, cap: int, deadline: float) -> None:
|
||||
"""Discard the rest of a rejected body (bounded) so the error reaches the client."""
|
||||
received = already
|
||||
try:
|
||||
while received <= cap and time.monotonic() < deadline:
|
||||
chunk = await _next_chunk(it, min(2.0, max(0.1, deadline - time.monotonic())))
|
||||
if chunk is None:
|
||||
return
|
||||
received += len(chunk)
|
||||
except Exception:
|
||||
return
|
||||
|
||||
|
||||
async def drain_oversized(stream: AsyncIterator[bytes], content_length: int) -> None:
|
||||
cap = config.max_upload_bytes() * DRAIN_FACTOR
|
||||
if content_length <= cap:
|
||||
await _drain(stream.__aiter__(), 0, cap, time.monotonic() + 30)
|
||||
|
||||
|
||||
async def spool_upload(
|
||||
stream: AsyncIterator[bytes],
|
||||
content_type: str,
|
||||
content_length: Optional[int],
|
||||
) -> Spooled:
|
||||
"""Read the body chunk by chunk into a private temp file while validating it.
|
||||
|
||||
Memory per upload is bounded by the transport chunk size (≈64 KiB) plus small
|
||||
parser state; size and pixel limits are enforced before the body is fully read.
|
||||
"""
|
||||
max_bytes = config.max_upload_bytes()
|
||||
idle = float(config.upload_idle_timeout_seconds())
|
||||
deadline = time.monotonic() + config.upload_deadline_seconds()
|
||||
it = stream.__aiter__()
|
||||
drain_cap = max_bytes * DRAIN_FACTOR
|
||||
|
||||
if content_length is not None and content_length > max_bytes:
|
||||
await drain_oversized(it, content_length)
|
||||
raise UploadRejected(413, "payload_too_large", "File exceeds 10 MiB")
|
||||
|
||||
validator = images.validator_for(content_type, config.max_image_pixels())
|
||||
digest = hashlib.sha256()
|
||||
size = 0
|
||||
prefix = b""
|
||||
fd, path = tempfile.mkstemp(prefix="up-", dir=str(config.spool_dir()))
|
||||
ok = False
|
||||
try:
|
||||
with os.fdopen(fd, "wb") as out:
|
||||
while True:
|
||||
if time.monotonic() > deadline:
|
||||
raise ClientGone("upload deadline exceeded")
|
||||
try:
|
||||
chunk = await _next_chunk(it, idle)
|
||||
except asyncio.TimeoutError:
|
||||
raise ClientGone("client stalled") from None
|
||||
if chunk is None:
|
||||
break
|
||||
if not chunk:
|
||||
continue
|
||||
size += len(chunk)
|
||||
if size > max_bytes:
|
||||
await _drain(it, size, drain_cap, min(deadline, time.monotonic() + 30))
|
||||
raise UploadRejected(413, "payload_too_large", "File exceeds 10 MiB")
|
||||
try:
|
||||
if len(prefix) < 8:
|
||||
# MIME is decided by content: the declared type must match the magic bytes.
|
||||
prefix = (prefix + chunk)[:8]
|
||||
sniffed = images.sniff(prefix) if len(prefix) >= 3 else None
|
||||
if (len(prefix) >= 8 or sniffed == "image/jpeg") and sniffed != content_type:
|
||||
raise images.ImageRejected(415, "unsupported_media_type", "Content does not match declared image type")
|
||||
validator.feed(chunk)
|
||||
except images.ImageRejected:
|
||||
await _drain(it, size, drain_cap, min(deadline, time.monotonic() + 30))
|
||||
raise
|
||||
digest.update(chunk)
|
||||
out.write(chunk)
|
||||
if size == 0:
|
||||
raise UploadRejected(400, "invalid_request", "Empty body")
|
||||
if len(prefix) < 8 and images.sniff(prefix) != content_type:
|
||||
raise UploadRejected(415, "unsupported_media_type", "Content does not match declared image type")
|
||||
try:
|
||||
width, height = validator.finish()
|
||||
except images.ImageRejected as exc:
|
||||
raise UploadRejected(exc.status, exc.code, exc.message) from None
|
||||
if content_type == "image/jpeg":
|
||||
await verify_jpeg(path)
|
||||
ok = True
|
||||
return Spooled(path, size, digest.hexdigest(), content_type, width, height)
|
||||
except images.ImageRejected as exc:
|
||||
raise UploadRejected(exc.status, exc.code, exc.message) from None
|
||||
finally:
|
||||
if not ok:
|
||||
_unlink(path)
|
||||
|
||||
|
||||
async def verify_jpeg(path: str) -> None:
|
||||
"""Fully entropy-decode the JPEG with libjpeg-turbo; any corruption warning is fatal.
|
||||
|
||||
`-scale 1/8` keeps the output tiny, but every Huffman-coded block is still decoded.
|
||||
Progressive JPEGs need a whole-image coefficient buffer (≈2 bytes/pixel/component,
|
||||
≈310 MiB for a 40 Mpx CMYK image), so decodes run one at a time per replica in a
|
||||
separate process with an address-space cap and a wall-clock timeout.
|
||||
"""
|
||||
async with _decode_slots:
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
"prlimit", f"--as={DECODE_MEMORY_BYTES}", "--",
|
||||
"djpeg", "-strict", "-scale", "1/8", "-outfile", os.devnull, path,
|
||||
stdin=asyncio.subprocess.DEVNULL,
|
||||
stdout=asyncio.subprocess.DEVNULL,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
try:
|
||||
_, err = await asyncio.wait_for(proc.communicate(), DECODE_TIMEOUT_S)
|
||||
except asyncio.TimeoutError:
|
||||
proc.kill()
|
||||
await proc.wait()
|
||||
log.warning("jpeg verification timed out")
|
||||
raise UploadRejected(503, "unavailable", "Image verification timed out, retry later") from None
|
||||
if proc.returncode == 0:
|
||||
return
|
||||
message = err.decode("utf-8", "replace")
|
||||
if proc.returncode < 0 or "Insufficient memory" in message:
|
||||
log.warning("jpeg verification aborted rc=%s", proc.returncode)
|
||||
raise UploadRejected(503, "unavailable", "Image verification failed, retry later")
|
||||
raise UploadRejected(415, "unsupported_media_type", "Corrupted JPEG image data")
|
||||
|
||||
|
||||
def _unlink(path: str) -> None:
|
||||
try:
|
||||
os.unlink(path)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
except OSError as exc:
|
||||
log.warning("spool cleanup failed: %s", type(exc).__name__)
|
||||
|
||||
|
||||
def persist(
|
||||
store: Store,
|
||||
spooled: Spooled,
|
||||
*,
|
||||
chat_id: str,
|
||||
owner_id: str,
|
||||
filename: str,
|
||||
instance: str,
|
||||
fault: Optional[Callable[[str, str], None]] = None,
|
||||
) -> Attachment:
|
||||
"""Durably store bytes + metadata. Blocking: run in a worker thread.
|
||||
|
||||
`fault` is a fault-injection hook used only by messenger.selfcheck; it is
|
||||
called with (step, object_key) and may raise to simulate failures.
|
||||
"""
|
||||
attachment_id = str(uuid.uuid4())
|
||||
key = new_object_key()
|
||||
now = utc_now()
|
||||
att = Attachment(
|
||||
id=attachment_id,
|
||||
chat_id=chat_id,
|
||||
owner_id=owner_id,
|
||||
filename=filename,
|
||||
content_type=spooled.content_type,
|
||||
size_bytes=spooled.size,
|
||||
sha256=spooled.sha256,
|
||||
width=spooled.width,
|
||||
height=spooled.height,
|
||||
object_key=key,
|
||||
status="uploading",
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
# 1. Intent first: if PostgreSQL is down nothing reaches S3 (fast 503).
|
||||
store.record_intent(key, attachment_id, chat_id, instance)
|
||||
try:
|
||||
if fault:
|
||||
fault("before_put", key)
|
||||
# 2. Bytes to the private bucket.
|
||||
with open(spooled.path, "rb") as body:
|
||||
s3.put_object(key, body, spooled.size, spooled.content_type, spooled.sha256)
|
||||
if fault:
|
||||
fault("after_put", key)
|
||||
# 3. Metadata + intent removal in one transaction.
|
||||
committed = store.commit_attachment(att)
|
||||
if fault:
|
||||
fault("after_commit", key)
|
||||
return committed
|
||||
except CommitUncertain:
|
||||
# The row may be committed: deleting the object could leave `ready` metadata
|
||||
# without bytes. The intent (if the commit was lost) lets the reconciler decide.
|
||||
log.warning("commit outcome unknown, object kept key_suffix=%s", key[-8:])
|
||||
raise
|
||||
except Exception as exc:
|
||||
# 4. Compensation. Any step may fail again; the intent row then lets the
|
||||
# reconciler finish the cleanup after the grace period.
|
||||
log.warning("upload failed, compensating key_suffix=%s err=%s", key[-8:], type(exc).__name__)
|
||||
_compensate(store, key)
|
||||
raise
|
||||
|
||||
|
||||
def _compensate(store: Store, key: str) -> None:
|
||||
try:
|
||||
s3.delete_object(key)
|
||||
except s3.S3Unavailable:
|
||||
return
|
||||
try:
|
||||
store.drop_intent(key)
|
||||
except StoreUnavailable:
|
||||
pass
|
||||
|
||||
|
||||
def discard(spooled: Optional[Spooled]) -> None:
|
||||
if spooled is not None:
|
||||
_unlink(spooled.path)
|
||||
@@ -0,0 +1,161 @@
|
||||
"""Runtime configuration from environment / secret files."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import socket
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _read_secret(env_key: str, file_key: str, default: str | None = None) -> str:
|
||||
file_path = os.environ.get(file_key, "").strip()
|
||||
if file_path:
|
||||
path = Path(file_path)
|
||||
if path.is_file():
|
||||
return path.read_text(encoding="utf-8").strip()
|
||||
value = os.environ.get(env_key, "").strip()
|
||||
if value:
|
||||
return value
|
||||
if default is not None:
|
||||
return default
|
||||
raise RuntimeError(f"Missing secret: set {env_key} or {file_key}")
|
||||
|
||||
|
||||
def _int_env(key: str, default: int, minimum: int = 1) -> int:
|
||||
raw = os.environ.get(key, str(default)).strip()
|
||||
try:
|
||||
value = int(raw)
|
||||
except ValueError as exc:
|
||||
raise RuntimeError(f"{key} must be an integer") from exc
|
||||
if value < minimum:
|
||||
raise RuntimeError(f"{key} must be >= {minimum}")
|
||||
return value
|
||||
|
||||
|
||||
def database_url() -> str:
|
||||
return _read_secret("DATABASE_URL", "DATABASE_URL_FILE")
|
||||
|
||||
|
||||
def cache_url() -> str:
|
||||
return _read_secret("CACHE_URL", "CACHE_URL_FILE")
|
||||
|
||||
|
||||
def session_ttl_seconds() -> int:
|
||||
return _int_env("SESSION_TTL_SECONDS", 3600)
|
||||
|
||||
|
||||
def idempotency_ttl_seconds() -> int:
|
||||
return _int_env("IDEMPOTENCY_TTL_SECONDS", 86400)
|
||||
|
||||
|
||||
def instance_id() -> str:
|
||||
"""Stable for process lifetime; used as X-Instance-Id (maps to container hostname)."""
|
||||
override = os.environ.get("INSTANCE_ID", "").strip()
|
||||
if override:
|
||||
return override[:128]
|
||||
return socket.gethostname()[:128]
|
||||
|
||||
|
||||
def app_host() -> str:
|
||||
return os.environ.get("APP_HOST", "0.0.0.0")
|
||||
|
||||
|
||||
def app_port() -> int:
|
||||
return int(os.environ.get("APP_PORT", "8080"))
|
||||
|
||||
|
||||
def migrations_dir() -> Path:
|
||||
override = os.environ.get("MIGRATIONS_DIR", "").strip()
|
||||
if override:
|
||||
return Path(override)
|
||||
here = Path(__file__).resolve()
|
||||
candidates = [
|
||||
Path("/app/migrations"),
|
||||
here.parents[2] / "migrations",
|
||||
Path.cwd() / "migrations",
|
||||
]
|
||||
for path in candidates:
|
||||
if path.is_dir():
|
||||
return path
|
||||
return candidates[0]
|
||||
|
||||
|
||||
# --- S3 / attachments (lab4) -------------------------------------------------
|
||||
|
||||
CONTRACT_MAX_UPLOAD_BYTES = 10 * 1024 * 1024
|
||||
CONTRACT_MAX_IMAGE_PIXELS = 40_000_000
|
||||
|
||||
|
||||
def s3_endpoint() -> str:
|
||||
return os.environ.get("S3_ENDPOINT", "http://s3:9000").strip()
|
||||
|
||||
|
||||
def s3_region() -> str:
|
||||
return os.environ.get("S3_REGION", "us-east-1").strip()
|
||||
|
||||
|
||||
def s3_bucket() -> str:
|
||||
return os.environ.get("S3_BUCKET", "messenger-attachments").strip()
|
||||
|
||||
|
||||
def s3_access_key_id() -> str:
|
||||
return _read_secret("S3_ACCESS_KEY_ID", "S3_ACCESS_KEY_ID_FILE")
|
||||
|
||||
|
||||
def s3_secret_access_key() -> str:
|
||||
return _read_secret("S3_SECRET_ACCESS_KEY", "S3_SECRET_ACCESS_KEY_FILE")
|
||||
|
||||
|
||||
def s3_admin_access_key_id() -> str:
|
||||
return _read_secret("S3_ADMIN_ACCESS_KEY_ID", "S3_ADMIN_ACCESS_KEY_ID_FILE")
|
||||
|
||||
|
||||
def s3_admin_secret_access_key() -> str:
|
||||
return _read_secret("S3_ADMIN_SECRET_ACCESS_KEY", "S3_ADMIN_SECRET_ACCESS_KEY_FILE")
|
||||
|
||||
|
||||
def max_upload_bytes() -> int:
|
||||
# The contract caps uploads at 10 MiB; the environment may only lower it.
|
||||
return min(_int_env("MAX_UPLOAD_BYTES", CONTRACT_MAX_UPLOAD_BYTES), CONTRACT_MAX_UPLOAD_BYTES)
|
||||
|
||||
|
||||
def max_image_pixels() -> int:
|
||||
return min(_int_env("MAX_IMAGE_PIXELS", CONTRACT_MAX_IMAGE_PIXELS), CONTRACT_MAX_IMAGE_PIXELS)
|
||||
|
||||
|
||||
def max_concurrent_uploads() -> int:
|
||||
return _int_env("MAX_CONCURRENT_UPLOADS", 8)
|
||||
|
||||
|
||||
def upload_idle_timeout_seconds() -> int:
|
||||
return _int_env("UPLOAD_IDLE_TIMEOUT_SECONDS", 10)
|
||||
|
||||
|
||||
def upload_deadline_seconds() -> int:
|
||||
return _int_env("UPLOAD_DEADLINE_SECONDS", 120)
|
||||
|
||||
|
||||
def upload_grace_seconds() -> int:
|
||||
value = _int_env("UPLOAD_GRACE_SECONDS", 900)
|
||||
if value < 2 * upload_deadline_seconds():
|
||||
raise RuntimeError("UPLOAD_GRACE_SECONDS must be >= 2 * UPLOAD_DEADLINE_SECONDS")
|
||||
return value
|
||||
|
||||
|
||||
def reconcile_interval_seconds() -> int:
|
||||
return _int_env("RECONCILE_INTERVAL_SECONDS", 300, minimum=0)
|
||||
|
||||
|
||||
def shutdown_drain_seconds() -> int:
|
||||
# After SIGTERM: readiness 503 but normal requests served, until HAProxy
|
||||
# (inter 1s, fall 2) has taken the replica out of rotation.
|
||||
return _int_env("SHUTDOWN_DRAIN_SECONDS", 3, minimum=0)
|
||||
|
||||
|
||||
def shutdown_timeout_seconds() -> int:
|
||||
# Upper bound for in-flight requests once the listener is closed.
|
||||
return _int_env("SHUTDOWN_TIMEOUT_SECONDS", 8)
|
||||
|
||||
|
||||
def spool_dir() -> Path:
|
||||
return Path(os.environ.get("UPLOAD_SPOOL_DIR", "/tmp/messenger-spool"))
|
||||
@@ -0,0 +1,218 @@
|
||||
"""PostgreSQL connection pool and versioned migrations."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import itertools
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import socket
|
||||
import threading
|
||||
import time
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from typing import Dict, Iterator, List, Optional, Tuple
|
||||
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg_pool import ConnectionPool, PoolTimeout
|
||||
|
||||
from messenger import config
|
||||
|
||||
log = logging.getLogger("messenger.db")
|
||||
|
||||
# statement_timeout is enforced by the server and does nothing when the server is
|
||||
# frozen (docker pause, stuck host): the client would wait forever. The watchdog
|
||||
# bounds every borrowed connection on the client side instead.
|
||||
QUERY_DEADLINE_S = 6.0
|
||||
POOL_WAIT_S = 3.0
|
||||
BREAKER_OPEN_S = 3.0
|
||||
|
||||
_pool: Optional[ConnectionPool] = None
|
||||
_guarded: Optional["GuardedPool"] = None
|
||||
|
||||
|
||||
class _Watchdog:
|
||||
"""One thread; shuts down the socket of a connection that outlives its deadline."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._lock = threading.Lock()
|
||||
self._armed: Dict[int, Tuple[float, psycopg.Connection]] = {}
|
||||
self._fired: set = set()
|
||||
self._ids = itertools.count()
|
||||
self._thread: Optional[threading.Thread] = None
|
||||
|
||||
def arm(self, conn: psycopg.Connection, deadline_s: float) -> int:
|
||||
token = next(self._ids)
|
||||
with self._lock:
|
||||
self._armed[token] = (time.monotonic() + deadline_s, conn)
|
||||
if self._thread is None:
|
||||
self._thread = threading.Thread(target=self._run, name="db-watchdog", daemon=True)
|
||||
self._thread.start()
|
||||
return token
|
||||
|
||||
def disarm(self, token: int) -> bool:
|
||||
with self._lock:
|
||||
self._armed.pop(token, None)
|
||||
if token in self._fired:
|
||||
self._fired.discard(token)
|
||||
return True
|
||||
return False
|
||||
|
||||
def _run(self) -> None:
|
||||
while True:
|
||||
time.sleep(0.25)
|
||||
now = time.monotonic()
|
||||
# Kill under the lock: the borrower must disarm (same lock) before the
|
||||
# connection goes back to the pool, so its fd cannot be closed and reused
|
||||
# by the event loop while we touch it.
|
||||
with self._lock:
|
||||
overdue = [(t, c) for t, (d, c) in self._armed.items() if d <= now]
|
||||
for token, conn in overdue:
|
||||
self._armed.pop(token, None)
|
||||
self._fired.add(token)
|
||||
_kill_socket(conn)
|
||||
|
||||
|
||||
def _kill_socket(conn: psycopg.Connection) -> None:
|
||||
# The blocked libpq call sees EOF, psycopg raises OperationalError and marks the
|
||||
# connection broken; the pool then discards it instead of reusing a stuck one.
|
||||
try:
|
||||
sock = socket.socket(fileno=os.dup(conn.pgconn.socket))
|
||||
except Exception:
|
||||
return
|
||||
# The socket object owns the dup'ed fd and closes it exactly once.
|
||||
with sock:
|
||||
try:
|
||||
sock.shutdown(socket.SHUT_RDWR)
|
||||
except OSError:
|
||||
pass
|
||||
log.warning("postgres call exceeded its deadline; connection aborted")
|
||||
|
||||
|
||||
_watchdog = _Watchdog()
|
||||
|
||||
|
||||
class GuardedPool:
|
||||
"""Pool facade: bounded wait for a connection, bounded time per borrow, breaker."""
|
||||
|
||||
def __init__(self, pool: ConnectionPool):
|
||||
self.raw = pool
|
||||
self._open_until = 0.0
|
||||
|
||||
def _trip(self) -> None:
|
||||
self._open_until = time.monotonic() + BREAKER_OPEN_S
|
||||
|
||||
@contextmanager
|
||||
def connection(self, deadline: Optional[float] = QUERY_DEADLINE_S) -> Iterator[psycopg.Connection]:
|
||||
if time.monotonic() < self._open_until:
|
||||
# Fail fast while PostgreSQL recently hung or vanished; a later call probes again.
|
||||
raise psycopg.OperationalError("database circuit open")
|
||||
try:
|
||||
with self.raw.connection(timeout=POOL_WAIT_S) as conn:
|
||||
token = _watchdog.arm(conn, deadline) if deadline else None
|
||||
try:
|
||||
yield conn
|
||||
except psycopg.Error:
|
||||
if conn.broken:
|
||||
self._trip()
|
||||
raise
|
||||
finally:
|
||||
if token is not None and _watchdog.disarm(token):
|
||||
self._trip()
|
||||
except PoolTimeout:
|
||||
self._trip()
|
||||
raise
|
||||
|
||||
|
||||
def get_pool() -> GuardedPool:
|
||||
if _guarded is None:
|
||||
raise RuntimeError("Database pool is not initialized")
|
||||
return _guarded
|
||||
|
||||
|
||||
def init_pool() -> GuardedPool:
|
||||
global _pool, _guarded
|
||||
if _guarded is not None:
|
||||
return _guarded
|
||||
url = config.database_url()
|
||||
_pool = ConnectionPool(
|
||||
conninfo=url,
|
||||
min_size=1,
|
||||
max_size=10,
|
||||
kwargs={
|
||||
"row_factory": dict_row,
|
||||
"connect_timeout": 3,
|
||||
"options": "-c statement_timeout=5000",
|
||||
},
|
||||
open=True,
|
||||
timeout=POOL_WAIT_S,
|
||||
)
|
||||
_guarded = GuardedPool(_pool)
|
||||
return _guarded
|
||||
|
||||
|
||||
def close_pool() -> None:
|
||||
global _pool, _guarded
|
||||
if _pool is not None:
|
||||
# Bounded: the whole shutdown must fit into the container's stop_grace_period.
|
||||
_pool.close(timeout=1.0)
|
||||
_pool = None
|
||||
_guarded = None
|
||||
|
||||
|
||||
def _split_sql(script: str) -> List[str]:
|
||||
"""Split SQL file into statements (no procedure bodies in our migrations)."""
|
||||
# Drop line comments.
|
||||
cleaned = re.sub(r"--[^\n]*", "", script)
|
||||
parts = []
|
||||
for chunk in cleaned.split(";"):
|
||||
stmt = chunk.strip()
|
||||
if stmt:
|
||||
parts.append(stmt)
|
||||
return parts
|
||||
|
||||
|
||||
def apply_migrations(migrations_path: Optional[Path] = None) -> None:
|
||||
path = migrations_path or config.migrations_dir()
|
||||
sql_files = sorted(path.glob("*.sql"))
|
||||
if not sql_files:
|
||||
raise RuntimeError(f"No migrations found in {path}")
|
||||
pool = get_pool()
|
||||
with pool.connection(deadline=None) as conn:
|
||||
with conn.transaction():
|
||||
conn.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version TEXT PRIMARY KEY,
|
||||
applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
)
|
||||
"""
|
||||
)
|
||||
for sql_file in sql_files:
|
||||
version = sql_file.name
|
||||
row = conn.execute(
|
||||
"SELECT 1 AS ok FROM schema_migrations WHERE version = %s",
|
||||
(version,),
|
||||
).fetchone()
|
||||
if row:
|
||||
log.info("migration already applied: %s", version)
|
||||
continue
|
||||
script = sql_file.read_text(encoding="utf-8")
|
||||
for stmt in _split_sql(script):
|
||||
conn.execute(stmt)
|
||||
conn.execute(
|
||||
"INSERT INTO schema_migrations (version) VALUES (%s)",
|
||||
(version,),
|
||||
)
|
||||
log.info("applied migration: %s", version)
|
||||
|
||||
|
||||
def ping() -> bool:
|
||||
try:
|
||||
with get_pool().connection(deadline=1.5) as conn:
|
||||
conn.execute("SELECT 1")
|
||||
return True
|
||||
except Exception as exc:
|
||||
log.warning("postgres ping failed: %s", type(exc).__name__)
|
||||
return False
|
||||
@@ -0,0 +1,391 @@
|
||||
"""Incremental PNG/JPEG validation with bounded memory.
|
||||
|
||||
The validators consume the upload chunk by chunk. Dimensions are taken from the
|
||||
header (PNG IHDR, JPEG SOFn) and the pixel limit is enforced as soon as they are
|
||||
known, before the rest of the body is read.
|
||||
|
||||
PNG is decoded here in full except for the arithmetic unfiltering step (which
|
||||
cannot fail): chunk CRCs, PLTE rules, the whole zlib stream inflated in bounded
|
||||
slices, its exact size for the declared geometry (incl. Adam7) and the filter
|
||||
type byte of every scanline. JPEG is only checked structurally here; the entropy
|
||||
coded data is verified afterwards by a real decoder (see attachments.verify_jpeg).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import struct
|
||||
import zlib
|
||||
from typing import Optional, Tuple
|
||||
|
||||
PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
|
||||
JPEG_SOI = b"\xff\xd8\xff"
|
||||
|
||||
_INFLATE_SLICE = 64 * 1024
|
||||
_MAX_PNG_CHUNK = 0x7FFFFFFF
|
||||
_PNG_CHANNELS = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}
|
||||
_PNG_DEPTHS = {0: (1, 2, 4, 8, 16), 2: (8, 16), 3: (1, 2, 4, 8), 4: (8, 16), 6: (8, 16)}
|
||||
_ADAM7 = ((0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4, 4), (0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2))
|
||||
# Baseline, extended sequential and progressive Huffman JPEG: what browsers decode.
|
||||
_JPEG_SOF_SUPPORTED = {0xC0, 0xC1, 0xC2}
|
||||
_JPEG_SOF_ALL = {0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF}
|
||||
|
||||
|
||||
class ImageRejected(Exception):
|
||||
"""Upload content is not an acceptable image; maps to an HTTP status."""
|
||||
|
||||
def __init__(self, status: int, code: str, message: str):
|
||||
super().__init__(message)
|
||||
self.status = status
|
||||
self.code = code
|
||||
self.message = message
|
||||
|
||||
|
||||
def _unsupported(message: str) -> ImageRejected:
|
||||
return ImageRejected(415, "unsupported_media_type", message)
|
||||
|
||||
|
||||
def sniff(prefix: bytes) -> Optional[str]:
|
||||
if prefix.startswith(PNG_SIGNATURE):
|
||||
return "image/png"
|
||||
if prefix.startswith(JPEG_SOI):
|
||||
return "image/jpeg"
|
||||
return None
|
||||
|
||||
|
||||
class _Validator:
|
||||
content_type = ""
|
||||
|
||||
def __init__(self, max_pixels: int):
|
||||
self.max_pixels = max_pixels
|
||||
self.width: Optional[int] = None
|
||||
self.height: Optional[int] = None
|
||||
|
||||
def _set_dimensions(self, width: int, height: int) -> None:
|
||||
if width < 1 or height < 1:
|
||||
raise _unsupported("Invalid image dimensions")
|
||||
if width * height > self.max_pixels:
|
||||
raise ImageRejected(413, "payload_too_large", "Image has too many pixels")
|
||||
self.width, self.height = width, height
|
||||
|
||||
def feed(self, data: bytes) -> None:
|
||||
raise NotImplementedError
|
||||
|
||||
def finish(self) -> Tuple[int, int]:
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
class PngValidator(_Validator):
|
||||
content_type = "image/png"
|
||||
|
||||
def __init__(self, max_pixels: int):
|
||||
super().__init__(max_pixels)
|
||||
self._buf = bytearray()
|
||||
self._state = "signature"
|
||||
self._chunk_type = b""
|
||||
self._chunk_left = 0
|
||||
self._chunk_small = bytearray()
|
||||
self._crc = 0
|
||||
self._seen_plte = False
|
||||
self._seen_idat = False
|
||||
self._idat_done = False
|
||||
self._color_type = 0
|
||||
self._depth = 0
|
||||
self._expected_raw = 0
|
||||
# (start, end, row_len) of every pass in the inflated stream; a scanline
|
||||
# starts with its filter type byte (0..4).
|
||||
self._rows: list = []
|
||||
self._raw = 0
|
||||
self._inflater = zlib.decompressobj()
|
||||
|
||||
def _layout(self, width: int, height: int, depth: int, color: int, interlace: int) -> None:
|
||||
bpp = _PNG_CHANNELS[color] * depth
|
||||
|
||||
def row_bytes(w: int) -> int:
|
||||
return 1 + (w * bpp + 7) // 8
|
||||
|
||||
passes = [(0, 0, 1, 1)] if interlace == 0 else _ADAM7
|
||||
offset = 0
|
||||
for x0, y0, dx, dy in passes:
|
||||
pw = (width - x0 + dx - 1) // dx if width > x0 else 0
|
||||
ph = (height - y0 + dy - 1) // dy if height > y0 else 0
|
||||
if pw and ph:
|
||||
size = ph * row_bytes(pw)
|
||||
self._rows.append((offset, offset + size, row_bytes(pw)))
|
||||
offset += size
|
||||
self._expected_raw = offset
|
||||
|
||||
def _check_filters(self, out: bytes, base: int) -> None:
|
||||
end = base + len(out)
|
||||
for start, stop, row_len in self._rows:
|
||||
lo, hi = max(start, base), min(stop, end)
|
||||
if lo >= hi:
|
||||
continue
|
||||
first = start + -(-(lo - start) // row_len) * row_len
|
||||
if first < hi and max(out[first - base:hi - base:row_len]) > 4:
|
||||
raise _unsupported("Invalid PNG scanline filter")
|
||||
|
||||
def _inflate(self, data: bytes) -> None:
|
||||
if self._inflater.eof:
|
||||
if data:
|
||||
raise _unsupported("Data after end of PNG image stream")
|
||||
return
|
||||
try:
|
||||
out = self._inflater.decompress(data, _INFLATE_SLICE)
|
||||
self._check_filters(out, self._raw)
|
||||
self._raw += len(out)
|
||||
while self._inflater.unconsumed_tail and self._raw <= self._expected_raw:
|
||||
out = self._inflater.decompress(self._inflater.unconsumed_tail, _INFLATE_SLICE)
|
||||
self._check_filters(out, self._raw)
|
||||
self._raw += len(out)
|
||||
except zlib.error:
|
||||
raise _unsupported("Corrupted PNG image data") from None
|
||||
if self._raw > self._expected_raw:
|
||||
raise _unsupported("PNG image data larger than declared dimensions")
|
||||
if self._inflater.eof and self._inflater.unused_data:
|
||||
raise _unsupported("Data after end of PNG image stream")
|
||||
|
||||
def _begin_chunk(self, length: int, ctype: bytes) -> None:
|
||||
if length > _MAX_PNG_CHUNK or not ctype.isalpha():
|
||||
raise _unsupported("Corrupted PNG chunk")
|
||||
if self.width is None and ctype != b"IHDR":
|
||||
raise _unsupported("PNG must start with IHDR")
|
||||
# Uppercase first letter = critical: a decoder must not skip one it does not know.
|
||||
if ctype[:1].isupper() and ctype not in (b"IHDR", b"PLTE", b"IDAT", b"IEND"):
|
||||
raise _unsupported("Unknown critical PNG chunk")
|
||||
if ctype == b"IHDR" and (self.width is not None or length != 13):
|
||||
raise _unsupported("Invalid PNG IHDR")
|
||||
if ctype == b"IDAT":
|
||||
if self._idat_done:
|
||||
raise _unsupported("Non-consecutive PNG IDAT chunks")
|
||||
if self._color_type == 3 and not self._seen_plte:
|
||||
raise _unsupported("Palette PNG without PLTE")
|
||||
self._seen_idat = True
|
||||
elif self._seen_idat:
|
||||
self._idat_done = True
|
||||
if ctype == b"PLTE":
|
||||
entries, rest = divmod(length, 3)
|
||||
if (
|
||||
self._seen_plte
|
||||
or self._seen_idat
|
||||
or self._color_type in (0, 4)
|
||||
or rest
|
||||
or not 1 <= entries <= 256
|
||||
or (self._color_type == 3 and entries > 1 << self._depth)
|
||||
):
|
||||
raise _unsupported("Invalid PNG palette")
|
||||
self._seen_plte = True
|
||||
if ctype == b"IEND" and length != 0:
|
||||
raise _unsupported("Invalid PNG IEND")
|
||||
self._chunk_type = ctype
|
||||
self._chunk_left = length
|
||||
self._chunk_small = bytearray()
|
||||
self._crc = zlib.crc32(ctype)
|
||||
|
||||
def _end_chunk(self) -> None:
|
||||
ctype = self._chunk_type
|
||||
if ctype == b"IHDR":
|
||||
width, height, depth, color, comp, filt, interlace = struct.unpack(">IIBBBBB", bytes(self._chunk_small))
|
||||
if color not in _PNG_DEPTHS or depth not in _PNG_DEPTHS[color] or comp != 0 or filt != 0 or interlace not in (0, 1):
|
||||
raise _unsupported("Unsupported PNG header")
|
||||
if width > _MAX_PNG_CHUNK or height > _MAX_PNG_CHUNK:
|
||||
raise _unsupported("Invalid image dimensions")
|
||||
self._set_dimensions(width, height)
|
||||
self._color_type = color
|
||||
self._depth = depth
|
||||
self._layout(width, height, depth, color, interlace)
|
||||
elif ctype == b"IEND":
|
||||
self._state = "end"
|
||||
|
||||
def feed(self, data: bytes) -> None:
|
||||
view = memoryview(data)
|
||||
pos = 0
|
||||
while pos < len(view):
|
||||
if self._state == "end":
|
||||
raise _unsupported("Data after PNG IEND")
|
||||
if self._state == "signature":
|
||||
need = 8 - len(self._buf)
|
||||
self._buf += view[pos:pos + need]
|
||||
pos += min(need, len(view) - pos)
|
||||
if len(self._buf) == 8:
|
||||
if bytes(self._buf) != PNG_SIGNATURE:
|
||||
raise _unsupported("Not a PNG image")
|
||||
self._buf.clear()
|
||||
self._state = "header"
|
||||
elif self._state == "header":
|
||||
need = 8 - len(self._buf)
|
||||
self._buf += view[pos:pos + need]
|
||||
pos += min(need, len(view) - pos)
|
||||
if len(self._buf) == 8:
|
||||
length, ctype = struct.unpack(">I4s", bytes(self._buf))
|
||||
self._buf.clear()
|
||||
self._begin_chunk(length, ctype)
|
||||
self._state = "data" if length else "crc"
|
||||
elif self._state == "data":
|
||||
take = min(self._chunk_left, len(view) - pos)
|
||||
piece = view[pos:pos + take]
|
||||
pos += take
|
||||
self._chunk_left -= take
|
||||
self._crc = zlib.crc32(piece, self._crc)
|
||||
if self._chunk_type == b"IDAT":
|
||||
self._inflate(bytes(piece))
|
||||
elif self._chunk_type == b"IHDR":
|
||||
self._chunk_small += piece
|
||||
if self._chunk_left == 0:
|
||||
self._state = "crc"
|
||||
elif self._state == "crc":
|
||||
need = 4 - len(self._buf)
|
||||
self._buf += view[pos:pos + need]
|
||||
pos += min(need, len(view) - pos)
|
||||
if len(self._buf) == 4:
|
||||
(crc,) = struct.unpack(">I", bytes(self._buf))
|
||||
self._buf.clear()
|
||||
if crc != (self._crc & 0xFFFFFFFF):
|
||||
raise _unsupported("PNG chunk checksum mismatch")
|
||||
self._state = "header"
|
||||
self._end_chunk()
|
||||
|
||||
def finish(self) -> Tuple[int, int]:
|
||||
if self._state != "end" or self.width is None or self.height is None:
|
||||
raise _unsupported("Truncated PNG image")
|
||||
if not self._seen_idat or not self._inflater.eof or self._raw != self._expected_raw:
|
||||
raise _unsupported("Incomplete PNG image data")
|
||||
return self.width, self.height
|
||||
|
||||
|
||||
class JpegValidator(_Validator):
|
||||
content_type = "image/jpeg"
|
||||
|
||||
def __init__(self, max_pixels: int):
|
||||
super().__init__(max_pixels)
|
||||
self._buf = bytearray()
|
||||
self._state = "soi"
|
||||
self._marker = 0
|
||||
self._seg_left = 0
|
||||
self._seg_small = bytearray()
|
||||
self._pending_ff = False
|
||||
self._seen_sof = False
|
||||
self._seen_sos = False
|
||||
self._done = False
|
||||
|
||||
def _begin_segment(self, marker: int, length: int) -> None:
|
||||
if length < 2:
|
||||
raise _unsupported("Corrupted JPEG segment")
|
||||
if marker in _JPEG_SOF_ALL:
|
||||
if marker not in _JPEG_SOF_SUPPORTED:
|
||||
raise _unsupported("Unsupported JPEG coding")
|
||||
if self._seen_sof:
|
||||
raise _unsupported("Multiple JPEG frames")
|
||||
if marker == 0xDA and not self._seen_sof:
|
||||
raise _unsupported("JPEG scan before frame header")
|
||||
self._marker = marker
|
||||
self._seg_left = length - 2
|
||||
self._seg_small = bytearray()
|
||||
|
||||
def _end_segment(self) -> None:
|
||||
marker = self._marker
|
||||
if marker in _JPEG_SOF_SUPPORTED:
|
||||
seg = bytes(self._seg_small)
|
||||
if len(seg) < 6:
|
||||
raise _unsupported("Corrupted JPEG frame header")
|
||||
precision, height, width, components = struct.unpack(">BHHB", seg[:6])
|
||||
# 8-bit only: what browsers and the verifying decoder (libjpeg-turbo 2.1) support.
|
||||
if precision != 8 or components not in (1, 3, 4) or len(seg) != 6 + 3 * components:
|
||||
raise _unsupported("Unsupported JPEG frame header")
|
||||
if height == 0:
|
||||
raise _unsupported("JPEG without explicit height is not supported")
|
||||
self._set_dimensions(width, height)
|
||||
self._seen_sof = True
|
||||
if marker == 0xDA:
|
||||
self._seen_sos = True
|
||||
self._state = "entropy"
|
||||
else:
|
||||
self._state = "marker"
|
||||
|
||||
def feed(self, data: bytes) -> None:
|
||||
pos = 0
|
||||
n = len(data)
|
||||
while pos < n:
|
||||
if self._done:
|
||||
# Bytes after EOI are tolerated but never interpreted.
|
||||
return
|
||||
state = self._state
|
||||
if state == "soi":
|
||||
need = 2 - len(self._buf)
|
||||
self._buf += data[pos:pos + need]
|
||||
pos += min(need, n - pos)
|
||||
if len(self._buf) == 2:
|
||||
if bytes(self._buf) != b"\xff\xd8":
|
||||
raise _unsupported("Not a JPEG image")
|
||||
self._buf.clear()
|
||||
self._state = "marker"
|
||||
elif state == "marker":
|
||||
byte = data[pos]
|
||||
pos += 1
|
||||
if not self._pending_ff:
|
||||
if byte != 0xFF:
|
||||
raise _unsupported("Corrupted JPEG marker")
|
||||
self._pending_ff = True
|
||||
continue
|
||||
if byte == 0xFF:
|
||||
continue
|
||||
self._pending_ff = False
|
||||
if byte == 0xD9:
|
||||
if not self._seen_sos:
|
||||
raise _unsupported("JPEG without image data")
|
||||
self._done = True
|
||||
elif byte == 0x01 or 0xD0 <= byte <= 0xD7:
|
||||
continue
|
||||
elif byte in (0x00, 0xD8):
|
||||
raise _unsupported("Corrupted JPEG marker")
|
||||
else:
|
||||
self._marker = byte
|
||||
self._state = "length"
|
||||
elif state == "length":
|
||||
need = 2 - len(self._buf)
|
||||
self._buf += data[pos:pos + need]
|
||||
pos += min(need, n - pos)
|
||||
if len(self._buf) == 2:
|
||||
(length,) = struct.unpack(">H", bytes(self._buf))
|
||||
self._buf.clear()
|
||||
self._begin_segment(self._marker, length)
|
||||
self._state = "segment"
|
||||
if self._seg_left == 0:
|
||||
self._end_segment()
|
||||
elif state == "segment":
|
||||
take = min(self._seg_left, n - pos)
|
||||
if self._marker in _JPEG_SOF_SUPPORTED:
|
||||
self._seg_small += data[pos:pos + take]
|
||||
pos += take
|
||||
self._seg_left -= take
|
||||
if self._seg_left == 0:
|
||||
self._end_segment()
|
||||
elif state == "entropy":
|
||||
if self._pending_ff:
|
||||
byte = data[pos]
|
||||
if byte == 0x00 or 0xD0 <= byte <= 0xD7:
|
||||
pos += 1
|
||||
self._pending_ff = False
|
||||
elif byte == 0xFF:
|
||||
pos += 1
|
||||
else:
|
||||
# A real marker ends the scan; reprocess it in marker state.
|
||||
self._state = "marker"
|
||||
continue
|
||||
idx = data.find(b"\xff", pos)
|
||||
if idx < 0:
|
||||
return
|
||||
pos = idx + 1
|
||||
self._pending_ff = True
|
||||
|
||||
def finish(self) -> Tuple[int, int]:
|
||||
if not self._done or self.width is None or self.height is None:
|
||||
raise _unsupported("Truncated JPEG image")
|
||||
return self.width, self.height
|
||||
|
||||
|
||||
def validator_for(content_type: str, max_pixels: int) -> _Validator:
|
||||
if content_type == "image/png":
|
||||
return PngValidator(max_pixels)
|
||||
if content_type == "image/jpeg":
|
||||
return JpegValidator(max_pixels)
|
||||
raise _unsupported("Only image/png and image/jpeg are accepted")
|
||||
@@ -0,0 +1,50 @@
|
||||
"""Graceful shutdown: readiness drain window before uvicorn stops accepting connections.
|
||||
|
||||
Plain uvicorn closes its listening socket on the first SIGTERM, while HAProxy keeps
|
||||
routing to the replica until `/health/ready` fails `fall` times (inter 1s, fall 2).
|
||||
Here the first SIGTERM/SIGINT only switches readiness to 503; the replica keeps
|
||||
serving normally for SHUTDOWN_DRAIN_SECONDS, then uvicorn closes the listener and
|
||||
waits up to SHUTDOWN_TIMEOUT_SECONDS for in-flight requests before the lifespan
|
||||
shutdown (reconciler, Redis, DB pool).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
from types import FrameType
|
||||
from typing import Optional
|
||||
|
||||
import uvicorn
|
||||
|
||||
log = logging.getLogger("messenger")
|
||||
|
||||
draining = False
|
||||
|
||||
|
||||
class DrainingServer(uvicorn.Server):
|
||||
def __init__(self, config: uvicorn.Config, drain_seconds: float) -> None:
|
||||
super().__init__(config)
|
||||
self.drain_seconds = drain_seconds
|
||||
self._drain_until: Optional[float] = None
|
||||
self._drain_logged = False
|
||||
|
||||
def handle_exit(self, sig: int, frame: Optional[FrameType]) -> None:
|
||||
global draining
|
||||
draining = True
|
||||
if self._drain_until is None and not self.should_exit and self.drain_seconds > 0:
|
||||
# Runs as a signal handler: only set flags, logging happens in on_tick.
|
||||
self._drain_until = time.monotonic() + self.drain_seconds
|
||||
return
|
||||
# A second signal ends the drain window at once; a repeated SIGINT forces exit.
|
||||
super().handle_exit(sig, frame)
|
||||
|
||||
async def on_tick(self, counter: int) -> bool:
|
||||
if self._drain_until is not None and not self.should_exit:
|
||||
if not self._drain_logged:
|
||||
self._drain_logged = True
|
||||
log.info("shutdown signal: readiness 503, serving for %ss drain window", self.drain_seconds)
|
||||
if time.monotonic() >= self._drain_until:
|
||||
log.info("drain window over; closing listener, waiting for in-flight requests")
|
||||
self.should_exit = True
|
||||
return await super().on_tick(counter)
|
||||
@@ -0,0 +1,28 @@
|
||||
"""One-shot migrations entrypoint (run once before API replicas)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import sys
|
||||
|
||||
from messenger import db
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(message)s",
|
||||
)
|
||||
log = logging.getLogger("messenger.migrate")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
db.init_pool()
|
||||
try:
|
||||
db.apply_migrations()
|
||||
log.info("migrations complete")
|
||||
return 0
|
||||
finally:
|
||||
db.close_pool()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,222 @@
|
||||
"""DB/S3 reconciler: removes objects of interrupted uploads after a safe grace period.
|
||||
|
||||
Rules (never violated, also with --grace-seconds 0):
|
||||
* an object whose key is in `attachments` is never deleted;
|
||||
* metadata is never deleted (a missing original is only reported);
|
||||
* an intent is resolved under FOR UPDATE SKIP LOCKED, so it cannot race with the
|
||||
commit transaction of the same upload (that one locks the intent too).
|
||||
The grace period protects uploads that are still in flight from being aborted.
|
||||
|
||||
CLI: python -m messenger.reconcile [--dry-run] [--grace-seconds N] [--check-missing]
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import logging
|
||||
import random
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
from messenger import config, db, s3
|
||||
|
||||
log = logging.getLogger("messenger.reconcile")
|
||||
|
||||
LOCK_KEY = 0x4C414234 # "LAB4": one reconciler at a time across replicas
|
||||
BATCH = 500
|
||||
|
||||
|
||||
def _referenced(conn, keys: List[str]) -> set:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT object_key FROM attachments WHERE object_key = ANY(%s)
|
||||
UNION
|
||||
SELECT object_key FROM upload_intents WHERE object_key = ANY(%s)
|
||||
""",
|
||||
(keys, keys),
|
||||
).fetchall()
|
||||
return {r["object_key"] for r in rows}
|
||||
|
||||
|
||||
def _resolve_intents(conn, grace: int, dry_run: bool, report: Dict[str, int]) -> None:
|
||||
if dry_run:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT i.object_key, (a.id IS NOT NULL) AS committed
|
||||
FROM upload_intents i LEFT JOIN attachments a ON a.object_key = i.object_key
|
||||
WHERE i.created_at < now() - make_interval(secs => %s)
|
||||
""",
|
||||
(grace,),
|
||||
).fetchall()
|
||||
report["stale_intents"] += len(rows)
|
||||
report["intent_objects_deleted"] += sum(1 for r in rows if not r["committed"])
|
||||
return
|
||||
while True:
|
||||
with conn.transaction():
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT object_key FROM upload_intents
|
||||
WHERE created_at < now() - make_interval(secs => %s)
|
||||
ORDER BY created_at
|
||||
LIMIT %s
|
||||
FOR UPDATE SKIP LOCKED
|
||||
""",
|
||||
(grace, BATCH),
|
||||
).fetchall()
|
||||
if not rows:
|
||||
return
|
||||
for row in rows:
|
||||
key = row["object_key"]
|
||||
report["stale_intents"] += 1
|
||||
committed = conn.execute(
|
||||
"SELECT 1 AS ok FROM attachments WHERE object_key = %s", (key,)
|
||||
).fetchone()
|
||||
if not committed:
|
||||
s3.delete_object(key)
|
||||
report["intent_objects_deleted"] += 1
|
||||
conn.execute("DELETE FROM upload_intents WHERE object_key = %s", (key,))
|
||||
if len(rows) < BATCH:
|
||||
return
|
||||
|
||||
|
||||
def _sweep_objects(conn, grace: int, dry_run: bool, check_missing: bool, report: Dict[str, int]) -> None:
|
||||
db_now = conn.execute("SELECT now() AS now").fetchone()["now"]
|
||||
listed = set() if check_missing else None
|
||||
page: List[dict] = []
|
||||
|
||||
def flush() -> None:
|
||||
keys = [o["Key"] for o in page]
|
||||
refs = _referenced(conn, keys)
|
||||
for obj in page:
|
||||
key = obj["Key"]
|
||||
if key in refs:
|
||||
report["referenced_objects"] += 1
|
||||
continue
|
||||
age = (db_now - obj["LastModified"]).total_seconds()
|
||||
if age < grace:
|
||||
report["fresh_unreferenced_skipped"] += 1
|
||||
continue
|
||||
report["orphans_found"] += 1
|
||||
if not dry_run:
|
||||
# Re-check under the reconciler lock right before deleting.
|
||||
if not _referenced(conn, [key]):
|
||||
s3.delete_object(key)
|
||||
report["orphans_deleted"] += 1
|
||||
page.clear()
|
||||
|
||||
for obj in s3.list_objects():
|
||||
report["objects_scanned"] += 1
|
||||
if listed is not None:
|
||||
listed.add(obj["Key"])
|
||||
page.append(obj)
|
||||
if len(page) >= BATCH:
|
||||
flush()
|
||||
if page:
|
||||
flush()
|
||||
|
||||
if listed is not None:
|
||||
rows = conn.execute(
|
||||
"SELECT object_key FROM attachments WHERE created_at < %s", (db_now,)
|
||||
).fetchall()
|
||||
report["missing_originals"] = sum(1 for r in rows if r["object_key"] not in listed)
|
||||
|
||||
|
||||
def run(
|
||||
grace_seconds: int,
|
||||
dry_run: bool = False,
|
||||
check_missing: bool = False,
|
||||
resolve_intents: bool = True,
|
||||
) -> dict:
|
||||
started = time.monotonic()
|
||||
report: Dict[str, int] = {
|
||||
"stale_intents": 0,
|
||||
"intent_objects_deleted": 0,
|
||||
"objects_scanned": 0,
|
||||
"referenced_objects": 0,
|
||||
"fresh_unreferenced_skipped": 0,
|
||||
"orphans_found": 0,
|
||||
"orphans_deleted": 0,
|
||||
}
|
||||
# Holds the session advisory lock across the whole S3 listing: no per-borrow deadline.
|
||||
with db.get_pool().connection(deadline=None) as conn:
|
||||
conn.autocommit = True
|
||||
locked = conn.execute("SELECT pg_try_advisory_lock(%s) AS ok", (LOCK_KEY,)).fetchone()["ok"]
|
||||
if not locked:
|
||||
return {"skipped": "another reconciler holds the lock"}
|
||||
try:
|
||||
if resolve_intents:
|
||||
_resolve_intents(conn, grace_seconds, dry_run, report)
|
||||
_sweep_objects(conn, grace_seconds, dry_run, check_missing, report)
|
||||
finally:
|
||||
conn.execute("SELECT pg_advisory_unlock(%s)", (LOCK_KEY,))
|
||||
conn.autocommit = False
|
||||
result = {"dry_run": dry_run, "grace_seconds": grace_seconds, **report}
|
||||
result["duration_ms"] = round((time.monotonic() - started) * 1000, 1)
|
||||
return result
|
||||
|
||||
|
||||
_stop = threading.Event()
|
||||
_thread: Optional[threading.Thread] = None
|
||||
|
||||
|
||||
def _loop(interval: int, grace: int) -> None:
|
||||
# Jitter spreads replicas; the advisory lock still guarantees one runner.
|
||||
if _stop.wait(random.uniform(5, 15)):
|
||||
return
|
||||
while not _stop.is_set():
|
||||
try:
|
||||
result = run(grace)
|
||||
if result.get("intent_objects_deleted") or result.get("orphans_deleted"):
|
||||
log.info("reconcile %s", json.dumps(result))
|
||||
except Exception as exc:
|
||||
log.warning("reconcile failed: %s", type(exc).__name__)
|
||||
if _stop.wait(interval * random.uniform(0.8, 1.2)):
|
||||
return
|
||||
|
||||
|
||||
def start_background() -> Optional[threading.Thread]:
|
||||
global _thread
|
||||
interval = config.reconcile_interval_seconds()
|
||||
if interval == 0:
|
||||
return None
|
||||
grace = config.upload_grace_seconds()
|
||||
_stop.clear()
|
||||
_thread = threading.Thread(target=_loop, args=(interval, grace), name="reconciler", daemon=True)
|
||||
_thread.start()
|
||||
return _thread
|
||||
|
||||
|
||||
def stop_background(timeout: float = 1.0) -> None:
|
||||
# A pass cut short by process exit is safe (intents and the lock are re-checked
|
||||
# next time); the bounded join only lets a nearly finished pass release its connection.
|
||||
_stop.set()
|
||||
if _thread is not None:
|
||||
_thread.join(timeout)
|
||||
if _thread.is_alive():
|
||||
log.info("reconciler still running at shutdown; leaving it to the next pass")
|
||||
|
||||
|
||||
def main(argv: Optional[List[str]] = None) -> int:
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument("--dry-run", action="store_true", help="report only, change nothing")
|
||||
parser.add_argument("--grace-seconds", type=int, default=None,
|
||||
help="override UPLOAD_GRACE_SECONDS (lab demos only; in-flight uploads younger than this survive)")
|
||||
parser.add_argument("--check-missing", action="store_true", help="also report metadata whose original is absent")
|
||||
args = parser.parse_args(argv)
|
||||
grace = config.upload_grace_seconds() if args.grace_seconds is None else args.grace_seconds
|
||||
if grace < 0:
|
||||
parser.error("--grace-seconds must be >= 0")
|
||||
db.init_pool()
|
||||
try:
|
||||
print(json.dumps(run(grace, dry_run=args.dry_run, check_missing=args.check_missing)))
|
||||
finally:
|
||||
db.close_pool()
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,161 @@
|
||||
"""Private S3 bucket access (SeaweedFS S3 gateway) with bounded timeouts."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
from typing import BinaryIO, Iterator, Optional, Tuple
|
||||
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
|
||||
from messenger import config
|
||||
|
||||
log = logging.getLogger("messenger.s3")
|
||||
|
||||
_client = None
|
||||
|
||||
ORIGINAL_PREFIX = "original/"
|
||||
DOWNLOAD_CHUNK = 64 * 1024
|
||||
|
||||
|
||||
class S3Unavailable(Exception):
|
||||
"""S3 is unreachable, timed out or refused the request."""
|
||||
|
||||
|
||||
class S3ObjectMissing(Exception):
|
||||
"""Object referenced by metadata does not exist in the bucket."""
|
||||
|
||||
|
||||
# Worst case per call: 2 attempts × (2 s connect + 5 s read) + backoff ≈ 15 s, well
|
||||
# under the LB `timeout server` (45 s), so clients get a JSON 503, not an LB 504.
|
||||
CONNECT_TIMEOUT_S = 2
|
||||
READ_TIMEOUT_S = 5
|
||||
TOTAL_ATTEMPTS = 2
|
||||
PING_TTL_S = 1.0
|
||||
|
||||
_ping_client = None
|
||||
_ping_lock = threading.Lock()
|
||||
_ping_cache: Tuple[float, bool] = (0.0, False)
|
||||
|
||||
|
||||
def build_client(access_key: str, secret_key: str, *, connect: float = CONNECT_TIMEOUT_S,
|
||||
read: float = READ_TIMEOUT_S, attempts: int = TOTAL_ATTEMPTS):
|
||||
return boto3.client(
|
||||
"s3",
|
||||
endpoint_url=config.s3_endpoint(),
|
||||
region_name=config.s3_region(),
|
||||
aws_access_key_id=access_key,
|
||||
aws_secret_access_key=secret_key,
|
||||
config=Config(
|
||||
signature_version="s3v4",
|
||||
s3={"addressing_style": "path"},
|
||||
connect_timeout=connect,
|
||||
read_timeout=read,
|
||||
retries={"total_max_attempts": attempts, "mode": "standard"},
|
||||
max_pool_connections=32,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def init_client():
|
||||
global _client, _ping_client
|
||||
if _client is None:
|
||||
access, secret = config.s3_access_key_id(), config.s3_secret_access_key()
|
||||
_client = build_client(access, secret)
|
||||
_ping_client = build_client(access, secret, connect=1, read=1.5, attempts=1)
|
||||
return _client
|
||||
|
||||
|
||||
def client():
|
||||
return init_client()
|
||||
|
||||
|
||||
def _error_code(exc: ClientError) -> str:
|
||||
return str(exc.response.get("Error", {}).get("Code", ""))
|
||||
|
||||
|
||||
def put_object(key: str, body: BinaryIO, size: int, content_type: str, sha256_hex: str) -> None:
|
||||
try:
|
||||
client().put_object(
|
||||
Bucket=config.s3_bucket(),
|
||||
Key=key,
|
||||
Body=body,
|
||||
ContentLength=size,
|
||||
ContentType=content_type,
|
||||
Metadata={"sha256": sha256_hex},
|
||||
)
|
||||
except (BotoCoreError, ClientError) as exc:
|
||||
log.warning("s3 put failed: %s", type(exc).__name__)
|
||||
raise S3Unavailable("s3 put failed") from exc
|
||||
|
||||
|
||||
def delete_object(key: str) -> None:
|
||||
"""Idempotent: deleting an absent key succeeds."""
|
||||
try:
|
||||
client().delete_object(Bucket=config.s3_bucket(), Key=key)
|
||||
except (BotoCoreError, ClientError) as exc:
|
||||
log.warning("s3 delete failed: %s", type(exc).__name__)
|
||||
raise S3Unavailable("s3 delete failed") from exc
|
||||
|
||||
|
||||
def head_object(key: str) -> Optional[dict]:
|
||||
try:
|
||||
return client().head_object(Bucket=config.s3_bucket(), Key=key)
|
||||
except ClientError as exc:
|
||||
if _error_code(exc) in ("404", "NoSuchKey", "NotFound"):
|
||||
return None
|
||||
raise S3Unavailable("s3 head failed") from exc
|
||||
except BotoCoreError as exc:
|
||||
raise S3Unavailable("s3 head failed") from exc
|
||||
|
||||
|
||||
def open_object(key: str) -> Tuple[int, Iterator[bytes], object]:
|
||||
"""Start a GET before response headers are sent so failures can still map to JSON errors."""
|
||||
try:
|
||||
resp = client().get_object(Bucket=config.s3_bucket(), Key=key)
|
||||
except ClientError as exc:
|
||||
if _error_code(exc) in ("404", "NoSuchKey", "NotFound"):
|
||||
raise S3ObjectMissing(key) from exc
|
||||
raise S3Unavailable("s3 get failed") from exc
|
||||
except BotoCoreError as exc:
|
||||
raise S3Unavailable("s3 get failed") from exc
|
||||
body = resp["Body"]
|
||||
return int(resp["ContentLength"]), body.iter_chunks(DOWNLOAD_CHUNK), body
|
||||
|
||||
|
||||
def list_objects(prefix: str = ORIGINAL_PREFIX) -> Iterator[dict]:
|
||||
token = None
|
||||
while True:
|
||||
kwargs = {"Bucket": config.s3_bucket(), "Prefix": prefix, "MaxKeys": 1000}
|
||||
if token:
|
||||
kwargs["ContinuationToken"] = token
|
||||
try:
|
||||
page = client().list_objects_v2(**kwargs)
|
||||
except (BotoCoreError, ClientError) as exc:
|
||||
raise S3Unavailable("s3 list failed") from exc
|
||||
for item in page.get("Contents", []) or []:
|
||||
yield item
|
||||
if not page.get("IsTruncated"):
|
||||
return
|
||||
token = page.get("NextContinuationToken")
|
||||
|
||||
|
||||
def ping() -> bool:
|
||||
"""Readiness probe: one short request, result shared for PING_TTL_S across callers."""
|
||||
global _ping_cache
|
||||
with _ping_lock:
|
||||
checked_at, ok = _ping_cache
|
||||
if time.monotonic() - checked_at < PING_TTL_S:
|
||||
return ok
|
||||
init_client()
|
||||
try:
|
||||
_ping_client.list_objects_v2(Bucket=config.s3_bucket(), Prefix=ORIGINAL_PREFIX, MaxKeys=1)
|
||||
ok = True
|
||||
except Exception as exc:
|
||||
log.warning("s3 ping failed: %s", type(exc).__name__)
|
||||
ok = False
|
||||
_ping_cache = (time.monotonic(), ok)
|
||||
return ok
|
||||
@@ -0,0 +1,67 @@
|
||||
"""Idempotent bucket bootstrap (one-shot `s3-init` service, admin credentials).
|
||||
|
||||
Creates the private bucket if absent; re-running is a no-op. Access rights are
|
||||
not stored in the bucket: SeaweedFS reads identities (admin / messenger-api, no
|
||||
anonymous identity) from the s3 config secret, so the bucket stays private.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
|
||||
from messenger import config, s3
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||
log = logging.getLogger("messenger.s3bootstrap")
|
||||
|
||||
|
||||
def _anonymous_status(url: str) -> int:
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=5) as resp:
|
||||
return resp.status
|
||||
except urllib.error.HTTPError as exc:
|
||||
return exc.code
|
||||
|
||||
|
||||
def main() -> int:
|
||||
bucket = config.s3_bucket()
|
||||
admin = s3.build_client(config.s3_admin_access_key_id(), config.s3_admin_secret_access_key())
|
||||
deadline = time.monotonic() + 90
|
||||
while True:
|
||||
try:
|
||||
admin.head_bucket(Bucket=bucket)
|
||||
log.info("bucket exists: %s", bucket)
|
||||
break
|
||||
except ClientError as exc:
|
||||
status = exc.response.get("ResponseMetadata", {}).get("HTTPStatusCode")
|
||||
if status != 404:
|
||||
raise
|
||||
try:
|
||||
admin.create_bucket(Bucket=bucket)
|
||||
log.info("bucket created: %s", bucket)
|
||||
except ClientError as create_exc:
|
||||
code = create_exc.response.get("Error", {}).get("Code", "")
|
||||
if code not in ("BucketAlreadyOwnedByYou", "BucketAlreadyExists"):
|
||||
raise
|
||||
log.info("bucket appeared concurrently: %s", bucket)
|
||||
except BotoCoreError as exc:
|
||||
if time.monotonic() > deadline:
|
||||
raise
|
||||
log.info("waiting for S3 (%s)", type(exc).__name__)
|
||||
time.sleep(2)
|
||||
status = _anonymous_status(config.s3_endpoint().rstrip("/") + "/" + bucket + "?list-type=2")
|
||||
if status != 403:
|
||||
log.error("bucket is not private: anonymous list returned %s", status)
|
||||
return 1
|
||||
log.info("anonymous access denied (HTTP %s); bootstrap complete", status)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,283 @@
|
||||
"""Operator self-checks executed inside an API container (docker compose exec api ...).
|
||||
|
||||
python -m messenger.selfcheck s3 private bucket + least-privilege API key
|
||||
python -m messenger.selfcheck consistency fault injection between S3 PUT and DB commit
|
||||
python -m messenger.selfcheck spool upload buffers left on the API container
|
||||
|
||||
Prints one JSON document; exit code 1 if any check fails. Never prints credentials.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import struct
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import uuid
|
||||
import zlib
|
||||
from typing import Callable, Dict, List
|
||||
|
||||
from botocore.exceptions import ClientError
|
||||
|
||||
from messenger import attachments, config, db, reconcile, s3
|
||||
from messenger.store import CommitUncertain, Store
|
||||
|
||||
INTERNAL_SEAWEED_PORTS = (8333, 18333, 8888, 18888, 9333, 19333, 8080, 18080)
|
||||
|
||||
|
||||
def _png(width: int = 4, height: int = 3) -> bytes:
|
||||
def chunk(kind: bytes, data: bytes) -> bytes:
|
||||
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)
|
||||
|
||||
raw = b"".join(b"\x00" + bytes((x * 40) % 256 for x in range(width * 3)) for _ in range(height))
|
||||
ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
|
||||
return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"")
|
||||
|
||||
|
||||
class Checks:
|
||||
def __init__(self) -> None:
|
||||
self.results: List[Dict[str, object]] = []
|
||||
|
||||
def check(self, name: str, ok: bool, detail: object = "") -> bool:
|
||||
self.results.append({"check": name, "ok": bool(ok), "detail": detail})
|
||||
return ok
|
||||
|
||||
def expect_denied(self, name: str, fn: Callable[[], object]) -> None:
|
||||
try:
|
||||
fn()
|
||||
self.check(name, False, "allowed")
|
||||
except ClientError as exc:
|
||||
code = exc.response.get("Error", {}).get("Code", "")
|
||||
status = exc.response.get("ResponseMetadata", {}).get("HTTPStatusCode")
|
||||
self.check(name, status in (403, 400, 405) and code != "", f"{status} {code}")
|
||||
|
||||
def report(self, title: str) -> int:
|
||||
ok = all(r["ok"] for r in self.results)
|
||||
print(json.dumps({"selfcheck": title, "passed": ok, "results": self.results}, ensure_ascii=False, indent=1))
|
||||
return 0 if ok else 1
|
||||
|
||||
|
||||
def _anonymous_get(url: str) -> object:
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=5) as resp:
|
||||
return resp.status
|
||||
except urllib.error.HTTPError as exc:
|
||||
return exc.code
|
||||
except OSError as exc:
|
||||
return type(exc).__name__
|
||||
|
||||
|
||||
def _port_open(host: str, port: int) -> bool:
|
||||
try:
|
||||
with socket.create_connection((host, port), timeout=2):
|
||||
return True
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def check_s3() -> int:
|
||||
c = Checks()
|
||||
bucket = config.s3_bucket()
|
||||
endpoint = config.s3_endpoint().rstrip("/")
|
||||
host = urllib.parse.urlparse(endpoint).hostname or "s3"
|
||||
app = s3.client()
|
||||
key = s3.ORIGINAL_PREFIX + "selfcheck-" + uuid.uuid4().hex
|
||||
body = _png()
|
||||
|
||||
app.put_object(Bucket=bucket, Key=key, Body=body, ContentType="image/png")
|
||||
c.check("api_key_put_object", True)
|
||||
got = app.get_object(Bucket=bucket, Key=key)["Body"].read()
|
||||
c.check("api_key_get_object", got == body)
|
||||
|
||||
status = _anonymous_get(f"{endpoint}/{bucket}/{key}")
|
||||
c.check("anonymous_get_object_denied", status == 403, status)
|
||||
status = _anonymous_get(f"{endpoint}/{bucket}/{key}?x-id=GetObject")
|
||||
c.check("anonymous_get_object_query_denied", status == 403, status)
|
||||
status = _anonymous_get(f"{endpoint}/{bucket}?list-type=2")
|
||||
c.check("anonymous_list_bucket_denied", status == 403, status)
|
||||
status = _anonymous_get(f"{endpoint}/")
|
||||
c.check("anonymous_list_buckets_denied", status == 403, status)
|
||||
|
||||
c.expect_denied("api_key_list_buckets_denied", lambda: app.list_buckets())
|
||||
c.expect_denied("api_key_create_bucket_denied", lambda: app.create_bucket(Bucket="lab4-escalation-" + uuid.uuid4().hex[:8]))
|
||||
c.expect_denied("api_key_delete_bucket_denied", lambda: app.delete_bucket(Bucket=bucket))
|
||||
c.expect_denied("api_key_put_bucket_acl_denied", lambda: app.put_bucket_acl(Bucket=bucket, ACL="public-read"))
|
||||
c.expect_denied("api_key_put_object_acl_denied", lambda: app.put_object_acl(Bucket=bucket, Key=key, ACL="public-read"))
|
||||
c.expect_denied("api_key_other_bucket_denied", lambda: app.put_object(Bucket="lab4-other", Key="x", Body=b"x"))
|
||||
status = _anonymous_get(f"{endpoint}/{bucket}/{key}")
|
||||
c.check("anonymous_get_still_denied_after_acl_attempts", status == 403, status)
|
||||
|
||||
wrong = s3.build_client(config.s3_access_key_id(), "wrong-" + uuid.uuid4().hex)
|
||||
c.expect_denied("wrong_secret_denied", lambda: wrong.get_object(Bucket=bucket, Key=key))
|
||||
|
||||
open_ports = [p for p in INTERNAL_SEAWEED_PORTS if _port_open(host, p)]
|
||||
c.check("seaweed_admin_and_grpc_ports_unreachable", not open_ports, {"open": open_ports, "probed": list(INTERNAL_SEAWEED_PORTS)})
|
||||
c.check("s3_api_port_reachable", _port_open(host, urllib.parse.urlparse(endpoint).port or 80))
|
||||
|
||||
app.delete_object(Bucket=bucket, Key=key)
|
||||
c.check("api_key_delete_object", s3.head_object(key) is None)
|
||||
return c.report("s3")
|
||||
|
||||
|
||||
def _reconcile(**kwargs) -> dict:
|
||||
for _ in range(20):
|
||||
result = reconcile.run(**kwargs)
|
||||
if "skipped" not in result:
|
||||
return result
|
||||
time.sleep(0.5)
|
||||
raise RuntimeError("reconciler lock busy")
|
||||
|
||||
|
||||
def _intent_exists(key: str) -> bool:
|
||||
with db.get_pool().connection() as conn:
|
||||
return conn.execute("SELECT 1 AS ok FROM upload_intents WHERE object_key = %s", (key,)).fetchone() is not None
|
||||
|
||||
|
||||
def _attachment_exists(key: str) -> bool:
|
||||
with db.get_pool().connection() as conn:
|
||||
return conn.execute("SELECT 1 AS ok FROM attachments WHERE object_key = %s", (key,)).fetchone() is not None
|
||||
|
||||
|
||||
def _spool(body: bytes) -> attachments.Spooled:
|
||||
config.spool_dir().mkdir(parents=True, exist_ok=True)
|
||||
fd, path = tempfile.mkstemp(prefix="selfcheck-", dir=str(config.spool_dir()))
|
||||
with os.fdopen(fd, "wb") as out:
|
||||
out.write(body)
|
||||
return attachments.Spooled(path, len(body), hashlib.sha256(body).hexdigest(), "image/png", 4, 3)
|
||||
|
||||
|
||||
def check_consistency() -> int:
|
||||
c = Checks()
|
||||
db.init_pool()
|
||||
store = Store()
|
||||
grace = config.upload_grace_seconds()
|
||||
suffix = uuid.uuid4().hex[:10]
|
||||
user = store.create_user("selfcheck_" + suffix, "Selfcheck", "Selfcheck-" + uuid.uuid4().hex)
|
||||
chat = store.create_chat("selfcheck", [user.id])
|
||||
body = _png()
|
||||
keys: Dict[str, str] = {}
|
||||
|
||||
def persist(fault=None):
|
||||
spooled = _spool(body)
|
||||
try:
|
||||
return attachments.persist(store, spooled, chat_id=chat.id, owner_id=user.id,
|
||||
filename="selfcheck.png", instance="selfcheck", fault=fault)
|
||||
finally:
|
||||
attachments.discard(spooled)
|
||||
|
||||
# A. S3 PUT fails: intent is dropped, nothing stays in the bucket.
|
||||
def fail_put(step: str, key: str) -> None:
|
||||
keys["put"] = key
|
||||
if step == "before_put":
|
||||
raise s3.S3Unavailable("injected")
|
||||
|
||||
try:
|
||||
persist(fail_put)
|
||||
c.check("A_s3_put_failure_raises", False)
|
||||
except s3.S3Unavailable:
|
||||
c.check("A_s3_put_failure_raises", True)
|
||||
k = keys["put"]
|
||||
c.check("A_no_object_no_intent_no_metadata",
|
||||
s3.head_object(k) is None and not _intent_exists(k) and not _attachment_exists(k))
|
||||
|
||||
# B. PUT succeeded, DB commit fails: compensation deletes the object at once.
|
||||
def fail_commit(step: str, key: str) -> None:
|
||||
keys["commit"] = key
|
||||
if step == "after_put":
|
||||
raise RuntimeError("injected commit failure")
|
||||
|
||||
try:
|
||||
persist(fail_commit)
|
||||
c.check("B_commit_failure_raises", False)
|
||||
except RuntimeError:
|
||||
c.check("B_commit_failure_raises", True)
|
||||
k = keys["commit"]
|
||||
c.check("B_compensation_removed_object_and_intent",
|
||||
s3.head_object(k) is None and not _intent_exists(k) and not _attachment_exists(k))
|
||||
|
||||
# C. Process dies after PUT (no compensation): object + intent remain until grace expires.
|
||||
def crash(step: str, key: str) -> None:
|
||||
keys["crash"] = key
|
||||
if step == "after_put":
|
||||
raise attachments.SimulatedCrash()
|
||||
|
||||
try:
|
||||
persist(crash)
|
||||
except attachments.SimulatedCrash:
|
||||
pass
|
||||
k = keys["crash"]
|
||||
c.check("C_crash_leaves_object_and_intent", s3.head_object(k) is not None and _intent_exists(k))
|
||||
first = _reconcile(grace_seconds=grace)
|
||||
c.check("C_fresh_intent_survives_reconcile", s3.head_object(k) is not None and _intent_exists(k), first)
|
||||
with db.get_pool().connection() as conn:
|
||||
with conn.transaction():
|
||||
conn.execute(
|
||||
"UPDATE upload_intents SET created_at = now() - make_interval(secs => %s) WHERE object_key = %s",
|
||||
(grace + 60, k),
|
||||
)
|
||||
second = _reconcile(grace_seconds=grace)
|
||||
c.check("C_stale_intent_object_deleted", s3.head_object(k) is None and not _intent_exists(k), second)
|
||||
again = _reconcile(grace_seconds=grace)
|
||||
c.check("C_rerun_is_noop", s3.head_object(k) is None, again)
|
||||
|
||||
# D. Orphan object without intent/metadata (e.g. intent lost): only the age rule applies.
|
||||
orphan = attachments.new_object_key()
|
||||
s3.client().put_object(Bucket=config.s3_bucket(), Key=orphan, Body=body, ContentType="image/png")
|
||||
dry = _reconcile(grace_seconds=grace, resolve_intents=False, dry_run=True)
|
||||
c.check("D_fresh_orphan_not_deleted", s3.head_object(orphan) is not None, dry)
|
||||
time.sleep(3)
|
||||
swept = _reconcile(grace_seconds=2, resolve_intents=False)
|
||||
c.check("D_old_orphan_deleted_by_sweep", s3.head_object(orphan) is None, swept)
|
||||
|
||||
# F. COMMIT succeeded but its result was lost: the object must NOT be compensated.
|
||||
def lose_commit_reply(step: str, key: str) -> None:
|
||||
keys["uncertain"] = key
|
||||
if step == "after_commit":
|
||||
raise CommitUncertain("injected lost COMMIT reply")
|
||||
|
||||
try:
|
||||
persist(lose_commit_reply)
|
||||
c.check("F_uncertain_commit_raises", False)
|
||||
except CommitUncertain:
|
||||
c.check("F_uncertain_commit_raises", True)
|
||||
k = keys["uncertain"]
|
||||
c.check("F_uncertain_commit_keeps_object_and_metadata",
|
||||
s3.head_object(k) is not None and _attachment_exists(k) and not _intent_exists(k))
|
||||
swept = _reconcile(grace_seconds=0, resolve_intents=False, check_missing=True)
|
||||
c.check("F_reconcile_keeps_committed_object", s3.head_object(k) is not None, swept)
|
||||
|
||||
# E. Committed attachments are never touched, even with grace 0.
|
||||
att = persist()
|
||||
c.check("E_upload_committed", _attachment_exists(att.object_key) and not _intent_exists(att.object_key))
|
||||
swept = _reconcile(grace_seconds=0, resolve_intents=False, check_missing=True)
|
||||
c.check("E_referenced_object_kept", s3.head_object(att.object_key) is not None, swept)
|
||||
c.check("E_no_missing_originals", swept.get("missing_originals") == 0, swept.get("missing_originals"))
|
||||
db.close_pool()
|
||||
return c.report("consistency")
|
||||
|
||||
|
||||
def check_spool() -> int:
|
||||
c = Checks()
|
||||
root = config.spool_dir()
|
||||
files = [p.name for p in root.iterdir()] if root.exists() else []
|
||||
c.check("spool_dir_empty", not files, {"dir": str(root), "files": len(files)})
|
||||
return c.report("spool")
|
||||
|
||||
|
||||
def main(argv: List[str]) -> int:
|
||||
commands = {"s3": check_s3, "consistency": check_consistency, "spool": check_spool}
|
||||
if len(argv) != 1 or argv[0] not in commands:
|
||||
print(__doc__)
|
||||
return 2
|
||||
return commands[argv[0]]()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
@@ -0,0 +1,136 @@
|
||||
"""Opaque Bearer sessions in Redis with TTL (durable via Redis AOF)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import secrets
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Optional
|
||||
|
||||
import redis
|
||||
|
||||
from messenger import config
|
||||
|
||||
log = logging.getLogger("messenger.sessions")
|
||||
|
||||
_client: Optional[redis.Redis] = None
|
||||
|
||||
TOKEN_BYTES = 32 # 256-bit entropy
|
||||
KEY_PREFIX = "sess:"
|
||||
|
||||
|
||||
def utc_now() -> datetime:
|
||||
return datetime.now(timezone.utc).replace(microsecond=0)
|
||||
|
||||
|
||||
def format_ts(value: datetime) -> str:
|
||||
if value.tzinfo is None:
|
||||
value = value.replace(tzinfo=timezone.utc)
|
||||
return value.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
|
||||
|
||||
def parse_ts(value: str) -> datetime:
|
||||
return datetime.strptime(value, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc)
|
||||
|
||||
|
||||
def init_client() -> redis.Redis:
|
||||
global _client
|
||||
if _client is not None:
|
||||
return _client
|
||||
url = config.cache_url()
|
||||
_client = redis.Redis.from_url(
|
||||
url,
|
||||
decode_responses=True,
|
||||
socket_connect_timeout=3,
|
||||
socket_timeout=3,
|
||||
health_check_interval=30,
|
||||
)
|
||||
return _client
|
||||
|
||||
|
||||
def close_client() -> None:
|
||||
global _client
|
||||
if _client is not None:
|
||||
try:
|
||||
_client.close()
|
||||
except Exception:
|
||||
pass
|
||||
_client = None
|
||||
|
||||
|
||||
def get_client() -> redis.Redis:
|
||||
if _client is None:
|
||||
raise RuntimeError("Redis client is not initialized")
|
||||
return _client
|
||||
|
||||
|
||||
def ping() -> bool:
|
||||
try:
|
||||
return bool(get_client().ping())
|
||||
except Exception as exc:
|
||||
log.warning("redis ping failed: %s", type(exc).__name__)
|
||||
return False
|
||||
|
||||
|
||||
class SessionStoreError(Exception):
|
||||
"""Raised when Redis is unavailable for session operations."""
|
||||
|
||||
|
||||
def create_session(user_id: str) -> dict:
|
||||
ttl = config.session_ttl_seconds()
|
||||
token = secrets.token_urlsafe(TOKEN_BYTES)
|
||||
now = utc_now()
|
||||
expires_at = now + timedelta(seconds=ttl)
|
||||
payload = {
|
||||
"user_id": user_id,
|
||||
"expires_at": format_ts(expires_at),
|
||||
"created_at": format_ts(now),
|
||||
}
|
||||
key = KEY_PREFIX + token
|
||||
try:
|
||||
client = get_client()
|
||||
# SET with EX: Redis is sole session store; AOF keeps it across restart.
|
||||
client.set(key, json.dumps(payload), ex=ttl)
|
||||
except redis.RedisError as exc:
|
||||
raise SessionStoreError("session store unavailable") from exc
|
||||
return {
|
||||
"token": token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": payload["expires_at"],
|
||||
"user_id": user_id,
|
||||
}
|
||||
|
||||
|
||||
def get_session(token: str) -> Optional[dict]:
|
||||
if not token:
|
||||
return None
|
||||
key = KEY_PREFIX + token
|
||||
try:
|
||||
raw = get_client().get(key)
|
||||
except redis.RedisError as exc:
|
||||
raise SessionStoreError("session store unavailable") from exc
|
||||
if not raw:
|
||||
return None
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
expires_at = parse_ts(data["expires_at"])
|
||||
except (ValueError, KeyError, TypeError, json.JSONDecodeError):
|
||||
return None
|
||||
if expires_at <= utc_now():
|
||||
try:
|
||||
get_client().delete(key)
|
||||
except redis.RedisError:
|
||||
pass
|
||||
return None
|
||||
return data
|
||||
|
||||
|
||||
def revoke_session(token: str) -> bool:
|
||||
if not token:
|
||||
return False
|
||||
key = KEY_PREFIX + token
|
||||
try:
|
||||
return bool(get_client().delete(key))
|
||||
except redis.RedisError as exc:
|
||||
raise SessionStoreError("session store unavailable") from exc
|
||||
@@ -0,0 +1,645 @@
|
||||
"""PostgreSQL repository: users, chats, membership, messages, idempotency, attachment metadata."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import uuid
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any, List, Optional, Tuple
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import VerifyMismatchError
|
||||
from psycopg import Error as PsycopgError
|
||||
from psycopg import errors as pg_errors
|
||||
from psycopg.types.json import Json
|
||||
|
||||
from messenger import config
|
||||
from messenger.db import get_pool
|
||||
|
||||
_ph = PasswordHasher()
|
||||
|
||||
|
||||
class StoreUnavailable(Exception):
|
||||
"""Raised when PostgreSQL is unreachable or timed out."""
|
||||
|
||||
|
||||
def utc_now() -> datetime:
|
||||
return datetime.now(timezone.utc).replace(microsecond=0)
|
||||
|
||||
|
||||
def format_ts(value: datetime) -> str:
|
||||
if value.tzinfo is None:
|
||||
value = value.replace(tzinfo=timezone.utc)
|
||||
return value.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
|
||||
|
||||
@dataclass
|
||||
class User:
|
||||
id: str
|
||||
username: str
|
||||
display_name: str
|
||||
created_at: datetime
|
||||
password_hash: str = ""
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"id": self.id,
|
||||
"username": self.username,
|
||||
"display_name": self.display_name,
|
||||
"created_at": format_ts(self.created_at),
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class Chat:
|
||||
id: str
|
||||
title: str
|
||||
member_ids: List[str]
|
||||
created_at: datetime
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"id": self.id,
|
||||
"title": self.title,
|
||||
"member_ids": list(self.member_ids),
|
||||
"created_at": format_ts(self.created_at),
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class Message:
|
||||
id: str
|
||||
chat_id: str
|
||||
sender_id: str
|
||||
text: str
|
||||
created_at: datetime
|
||||
attachment_ids: List[str] = field(default_factory=list)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"id": self.id,
|
||||
"chat_id": self.chat_id,
|
||||
"sender_id": self.sender_id,
|
||||
"text": self.text,
|
||||
"created_at": format_ts(self.created_at),
|
||||
"attachment_ids": list(self.attachment_ids),
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class Attachment:
|
||||
id: str
|
||||
chat_id: str
|
||||
owner_id: str
|
||||
filename: str
|
||||
content_type: str
|
||||
size_bytes: int
|
||||
sha256: str
|
||||
width: int
|
||||
height: int
|
||||
object_key: str
|
||||
status: str
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
# object_key is internal: the public API never exposes bucket keys.
|
||||
return {
|
||||
"id": self.id,
|
||||
"chat_id": self.chat_id,
|
||||
"owner_id": self.owner_id,
|
||||
"filename": self.filename,
|
||||
"content_type": self.content_type,
|
||||
"size_bytes": self.size_bytes,
|
||||
"sha256": self.sha256,
|
||||
"status": self.status,
|
||||
"variants": [],
|
||||
"error_code": None,
|
||||
"created_at": format_ts(self.created_at),
|
||||
"updated_at": format_ts(self.updated_at),
|
||||
}
|
||||
|
||||
|
||||
class AttachmentNotFound(Exception):
|
||||
"""Referenced attachment is unknown, not ready or belongs to another chat."""
|
||||
|
||||
|
||||
class IntentLost(Exception):
|
||||
"""Upload intent vanished (reconciled) before metadata commit."""
|
||||
|
||||
|
||||
class CommitUncertain(StoreUnavailable):
|
||||
"""COMMIT was sent but its result is unknown: the row may or may not exist."""
|
||||
|
||||
|
||||
def _row_user(row: dict) -> User:
|
||||
return User(
|
||||
id=str(row["id"]),
|
||||
username=row["username"],
|
||||
display_name=row["display_name"],
|
||||
created_at=row["created_at"],
|
||||
password_hash=row.get("password_hash", ""),
|
||||
)
|
||||
|
||||
|
||||
def _row_message(row: dict) -> Message:
|
||||
return Message(
|
||||
id=str(row["id"]),
|
||||
chat_id=str(row["chat_id"]),
|
||||
sender_id=str(row["sender_id"]),
|
||||
text=bytes(row["text"]).decode("utf-8"),
|
||||
created_at=row["created_at"],
|
||||
attachment_ids=[str(a) for a in (row.get("attachment_ids") or [])],
|
||||
)
|
||||
|
||||
|
||||
def _row_attachment(row: dict) -> Attachment:
|
||||
return Attachment(
|
||||
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"],
|
||||
width=int(row["width"]),
|
||||
height=int(row["height"]),
|
||||
object_key=row["object_key"],
|
||||
status=row["status"],
|
||||
created_at=row["created_at"],
|
||||
updated_at=row["updated_at"],
|
||||
)
|
||||
|
||||
|
||||
_ATTACHMENT_COLUMNS = (
|
||||
"a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, a.sha256, "
|
||||
"a.width, a.height, a.object_key, a.status, a.created_at, a.updated_at"
|
||||
)
|
||||
_MESSAGE_ATTACHMENTS = (
|
||||
"ARRAY(SELECT ma.attachment_id FROM message_attachments ma "
|
||||
"WHERE ma.message_id = m.id ORDER BY ma.position) AS attachment_ids"
|
||||
)
|
||||
|
||||
|
||||
class Store:
|
||||
def hash_password(self, password: str) -> str:
|
||||
return _ph.hash(password)
|
||||
|
||||
def verify_password(self, password_hash: str, password: str) -> bool:
|
||||
try:
|
||||
return _ph.verify(password_hash, password)
|
||||
except VerifyMismatchError:
|
||||
return False
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def create_user(self, username: str, display_name: str, password: str) -> User:
|
||||
user_id = uuid.uuid4()
|
||||
created = utc_now()
|
||||
password_hash = self.hash_password(password)
|
||||
try:
|
||||
with get_pool().connection() as conn:
|
||||
with conn.transaction():
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES (%s, %s, %s, %s, %s)
|
||||
""",
|
||||
(user_id, username, display_name, password_hash, created),
|
||||
)
|
||||
except (pg_errors.UniqueViolation, pg_errors.IntegrityError) as exc:
|
||||
raise KeyError("username_taken") from exc
|
||||
except PsycopgError as exc:
|
||||
raise StoreUnavailable("database unavailable") from exc
|
||||
return User(
|
||||
id=str(user_id),
|
||||
username=username,
|
||||
display_name=display_name,
|
||||
created_at=created,
|
||||
)
|
||||
|
||||
def get_user(self, user_id: str) -> Optional[User]:
|
||||
try:
|
||||
with get_pool().connection() as conn:
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT id, username, display_name, password_hash, created_at
|
||||
FROM users WHERE id = %s
|
||||
""",
|
||||
(user_id,),
|
||||
).fetchone()
|
||||
except PsycopgError as exc:
|
||||
raise StoreUnavailable("database unavailable") from exc
|
||||
return _row_user(row) if row else None
|
||||
|
||||
def get_user_by_username(self, username: str) -> Optional[User]:
|
||||
try:
|
||||
with get_pool().connection() as conn:
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT id, username, display_name, password_hash, created_at
|
||||
FROM users WHERE username = %s
|
||||
""",
|
||||
(username,),
|
||||
).fetchone()
|
||||
except PsycopgError as exc:
|
||||
raise StoreUnavailable("database unavailable") from exc
|
||||
return _row_user(row) if row else None
|
||||
|
||||
def create_chat(self, title: str, member_ids: List[str]) -> Chat:
|
||||
chat_id = uuid.uuid4()
|
||||
created = utc_now()
|
||||
try:
|
||||
with get_pool().connection() as conn:
|
||||
with conn.transaction():
|
||||
# Atomic membership check + insert; rollback if any member missing.
|
||||
rows = conn.execute(
|
||||
"SELECT id FROM users WHERE id = ANY(%s::uuid[])",
|
||||
(member_ids,),
|
||||
).fetchall()
|
||||
found = {str(r["id"]) for r in rows}
|
||||
if found != set(member_ids):
|
||||
raise KeyError("unknown_member")
|
||||
conn.execute(
|
||||
"INSERT INTO chats (id, title, created_at) VALUES (%s, %s, %s)",
|
||||
(chat_id, title, created),
|
||||
)
|
||||
for mid in member_ids:
|
||||
conn.execute(
|
||||
"INSERT INTO chat_members (chat_id, user_id) VALUES (%s, %s)",
|
||||
(chat_id, mid),
|
||||
)
|
||||
except KeyError:
|
||||
raise
|
||||
except PsycopgError as exc:
|
||||
raise StoreUnavailable("database unavailable") from exc
|
||||
return Chat(
|
||||
id=str(chat_id),
|
||||
title=title,
|
||||
member_ids=list(member_ids),
|
||||
created_at=created,
|
||||
)
|
||||
|
||||
def get_chat(self, chat_id: str) -> Optional[Chat]:
|
||||
try:
|
||||
with get_pool().connection() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT id, title, created_at FROM chats WHERE id = %s",
|
||||
(chat_id,),
|
||||
).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
members = conn.execute(
|
||||
"""
|
||||
SELECT user_id FROM chat_members
|
||||
WHERE chat_id = %s
|
||||
ORDER BY user_id
|
||||
""",
|
||||
(chat_id,),
|
||||
).fetchall()
|
||||
except PsycopgError as exc:
|
||||
raise StoreUnavailable("database unavailable") from exc
|
||||
return Chat(
|
||||
id=str(row["id"]),
|
||||
title=row["title"],
|
||||
member_ids=[str(m["user_id"]) for m in members],
|
||||
created_at=row["created_at"],
|
||||
)
|
||||
|
||||
def list_chats_for_user(
|
||||
self,
|
||||
user_id: str,
|
||||
limit: int,
|
||||
cursor: Optional[Tuple[datetime, uuid.UUID]],
|
||||
) -> Tuple[List[Chat], Optional[str]]:
|
||||
params: list = [user_id]
|
||||
where = "cm.user_id = %s"
|
||||
if cursor is not None:
|
||||
where += " AND (c.created_at, c.id) > (%s, %s)"
|
||||
params.extend([cursor[0], cursor[1]])
|
||||
params.append(limit + 1)
|
||||
try:
|
||||
with get_pool().connection() as conn:
|
||||
rows = conn.execute(
|
||||
f"""
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members cm ON cm.chat_id = c.id
|
||||
WHERE {where}
|
||||
ORDER BY c.created_at ASC, c.id ASC
|
||||
LIMIT %s
|
||||
""",
|
||||
params,
|
||||
).fetchall()
|
||||
chats: List[Chat] = []
|
||||
for row in rows[:limit]:
|
||||
members = conn.execute(
|
||||
"""
|
||||
SELECT user_id FROM chat_members
|
||||
WHERE chat_id = %s
|
||||
ORDER BY user_id
|
||||
""",
|
||||
(row["id"],),
|
||||
).fetchall()
|
||||
chats.append(
|
||||
Chat(
|
||||
id=str(row["id"]),
|
||||
title=row["title"],
|
||||
member_ids=[str(m["user_id"]) for m in members],
|
||||
created_at=row["created_at"],
|
||||
)
|
||||
)
|
||||
except PsycopgError as exc:
|
||||
raise StoreUnavailable("database unavailable") from exc
|
||||
has_more = len(rows) > limit
|
||||
return chats, "more" if has_more else None
|
||||
|
||||
@staticmethod
|
||||
def request_hash_for_message(text: str, attachment_ids: List[str]) -> str:
|
||||
# Canonical form: sorted keys; absent attachment_ids ≡ []; array order is significant.
|
||||
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 create_message_idempotent(
|
||||
self,
|
||||
chat_id: str,
|
||||
sender_id: str,
|
||||
text: str,
|
||||
attachment_ids: List[str],
|
||||
method: str,
|
||||
path: str,
|
||||
idem_key: str,
|
||||
) -> Tuple[Message, bool]:
|
||||
"""
|
||||
Create message with shared idempotency across replicas.
|
||||
Returns (message, replayed).
|
||||
Raises KeyError('conflict') when same key was used with another body,
|
||||
AttachmentNotFound when an attachment is unknown or belongs to another chat.
|
||||
"""
|
||||
req_hash = self.request_hash_for_message(text, attachment_ids)
|
||||
ttl = timedelta(seconds=config.idempotency_ttl_seconds())
|
||||
# Transaction-scoped advisory lock serializes same-key concurrent POSTs.
|
||||
lock_material = f"{sender_id}|{method}|{path}|{idem_key}"
|
||||
lock_key = int(
|
||||
hashlib.sha256(lock_material.encode("utf-8")).hexdigest()[:15], 16
|
||||
)
|
||||
|
||||
def _load_existing(conn) -> Optional[dict]:
|
||||
return conn.execute(
|
||||
"""
|
||||
SELECT request_hash, response_status, response_body, created_at
|
||||
FROM idempotency_records
|
||||
WHERE user_id = %s AND method = %s AND path = %s AND idem_key = %s
|
||||
""",
|
||||
(sender_id, method, path, idem_key),
|
||||
).fetchone()
|
||||
|
||||
def _message_from_body(body: Any) -> Message:
|
||||
return Message(
|
||||
id=str(body["id"]),
|
||||
chat_id=str(body["chat_id"]),
|
||||
sender_id=str(body["sender_id"]),
|
||||
text=body["text"],
|
||||
created_at=datetime.strptime(
|
||||
body["created_at"], "%Y-%m-%dT%H:%M:%SZ"
|
||||
).replace(tzinfo=timezone.utc),
|
||||
attachment_ids=[str(a) for a in body.get("attachment_ids", [])],
|
||||
)
|
||||
|
||||
try:
|
||||
with get_pool().connection() as conn:
|
||||
with conn.transaction():
|
||||
conn.execute("SELECT pg_advisory_xact_lock(%s)", (lock_key,))
|
||||
existing = _load_existing(conn)
|
||||
if existing is not None:
|
||||
if existing["created_at"] >= utc_now() - ttl:
|
||||
if existing["request_hash"] != req_hash:
|
||||
raise KeyError("conflict")
|
||||
return _message_from_body(existing["response_body"]), True
|
||||
conn.execute(
|
||||
"""
|
||||
DELETE FROM idempotency_records
|
||||
WHERE user_id = %s AND method = %s AND path = %s AND idem_key = %s
|
||||
""",
|
||||
(sender_id, method, path, idem_key),
|
||||
)
|
||||
|
||||
if attachment_ids:
|
||||
# Only ready attachments of THIS chat may be referenced; others look absent.
|
||||
found = conn.execute(
|
||||
"""
|
||||
SELECT id FROM attachments
|
||||
WHERE id = ANY(%s::uuid[]) AND chat_id = %s AND status = 'ready'
|
||||
FOR SHARE
|
||||
""",
|
||||
(attachment_ids, chat_id),
|
||||
).fetchall()
|
||||
if {str(r["id"]) for r in found} != set(attachment_ids):
|
||||
raise AttachmentNotFound()
|
||||
|
||||
msg_id = uuid.uuid4()
|
||||
created = utc_now()
|
||||
message = Message(
|
||||
id=str(msg_id),
|
||||
chat_id=chat_id,
|
||||
sender_id=sender_id,
|
||||
text=text,
|
||||
created_at=created,
|
||||
attachment_ids=list(attachment_ids),
|
||||
)
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES (%s, %s, %s, %s, %s)
|
||||
""",
|
||||
(msg_id, chat_id, sender_id, text.encode("utf-8"), created),
|
||||
)
|
||||
for position, attachment_id in enumerate(attachment_ids):
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO message_attachments (message_id, attachment_id, position)
|
||||
VALUES (%s, %s, %s)
|
||||
""",
|
||||
(msg_id, attachment_id, position),
|
||||
)
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO idempotency_records (
|
||||
user_id, method, path, idem_key,
|
||||
request_hash, response_status, response_body, created_at
|
||||
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
||||
""",
|
||||
(
|
||||
sender_id,
|
||||
method,
|
||||
path,
|
||||
idem_key,
|
||||
req_hash,
|
||||
201,
|
||||
Json(message.to_dict()),
|
||||
created,
|
||||
),
|
||||
)
|
||||
return message, False
|
||||
except (KeyError, AttachmentNotFound):
|
||||
raise
|
||||
except pg_errors.DataError as exc:
|
||||
raise ValueError("invalid_text") from exc
|
||||
except PsycopgError as exc:
|
||||
raise StoreUnavailable("database unavailable") from exc
|
||||
|
||||
def list_messages(
|
||||
self,
|
||||
chat_id: str,
|
||||
limit: int,
|
||||
cursor: Optional[Tuple[datetime, uuid.UUID]],
|
||||
) -> Tuple[List[Message], bool]:
|
||||
params: list = [chat_id]
|
||||
where = "m.chat_id = %s"
|
||||
if cursor is not None:
|
||||
where += " AND (m.created_at, m.id) > (%s, %s)"
|
||||
params.extend([cursor[0], cursor[1]])
|
||||
params.append(limit + 1)
|
||||
try:
|
||||
with get_pool().connection() as conn:
|
||||
rows = conn.execute(
|
||||
f"""
|
||||
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
||||
{_MESSAGE_ATTACHMENTS}
|
||||
FROM messages m
|
||||
WHERE {where}
|
||||
ORDER BY m.created_at ASC, m.id ASC
|
||||
LIMIT %s
|
||||
""",
|
||||
params,
|
||||
).fetchall()
|
||||
except PsycopgError as exc:
|
||||
raise StoreUnavailable("database unavailable") from exc
|
||||
messages = [_row_message(r) for r in rows[:limit]]
|
||||
return messages, len(rows) > limit
|
||||
|
||||
def message_exists(self, chat_id: str, created_at: datetime, item_id: uuid.UUID) -> bool:
|
||||
try:
|
||||
with get_pool().connection() as conn:
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT 1 AS ok FROM messages
|
||||
WHERE chat_id = %s AND created_at = %s AND id = %s
|
||||
""",
|
||||
(chat_id, created_at, item_id),
|
||||
).fetchone()
|
||||
except PsycopgError as exc:
|
||||
raise StoreUnavailable("database unavailable") from exc
|
||||
return bool(row)
|
||||
|
||||
def chat_exists_for_user(
|
||||
self, user_id: str, created_at: datetime, item_id: uuid.UUID
|
||||
) -> bool:
|
||||
try:
|
||||
with get_pool().connection() as conn:
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT 1 AS ok
|
||||
FROM chats c
|
||||
JOIN chat_members cm ON cm.chat_id = c.id
|
||||
WHERE cm.user_id = %s AND c.created_at = %s AND c.id = %s
|
||||
""",
|
||||
(user_id, created_at, item_id),
|
||||
).fetchone()
|
||||
except PsycopgError as exc:
|
||||
raise StoreUnavailable("database unavailable") from exc
|
||||
return bool(row)
|
||||
|
||||
# --- attachments (lab4) ---------------------------------------------------
|
||||
#
|
||||
# Write protocol (see REPORT.md, "Согласованность БД/S3"):
|
||||
# 1. record_intent() — durable intent row BEFORE any byte reaches S3;
|
||||
# 2. S3 PUT of a server-generated key;
|
||||
# 3. commit_attachment() — one transaction locks the intent, inserts the
|
||||
# ready metadata and deletes the intent;
|
||||
# 4. on failure: compensate (S3 DELETE + drop intent); whatever survives a
|
||||
# crash is collected by messenger.reconcile after the grace period.
|
||||
|
||||
def record_intent(self, object_key: str, attachment_id: str, chat_id: str, instance: str) -> None:
|
||||
try:
|
||||
with get_pool().connection() as conn:
|
||||
with conn.transaction():
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO upload_intents (object_key, attachment_id, chat_id, instance_id, created_at)
|
||||
VALUES (%s, %s, %s, %s, now())
|
||||
""",
|
||||
(object_key, attachment_id, chat_id, instance),
|
||||
)
|
||||
except PsycopgError as exc:
|
||||
raise StoreUnavailable("database unavailable") from exc
|
||||
|
||||
def drop_intent(self, object_key: str) -> None:
|
||||
try:
|
||||
with get_pool().connection() as conn:
|
||||
with conn.transaction():
|
||||
conn.execute("DELETE FROM upload_intents WHERE object_key = %s", (object_key,))
|
||||
except PsycopgError as exc:
|
||||
raise StoreUnavailable("database unavailable") from exc
|
||||
|
||||
def commit_attachment(self, att: Attachment) -> Attachment:
|
||||
committing = False
|
||||
try:
|
||||
with get_pool().connection() as conn:
|
||||
with conn.transaction():
|
||||
intent = conn.execute(
|
||||
"SELECT object_key FROM upload_intents WHERE object_key = %s FOR UPDATE",
|
||||
(att.object_key,),
|
||||
).fetchone()
|
||||
if intent is None:
|
||||
raise IntentLost(att.object_key)
|
||||
row = conn.execute(
|
||||
"""
|
||||
INSERT INTO attachments (
|
||||
id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||||
width, height, object_key, status, created_at, updated_at
|
||||
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, 'ready', now(), now())
|
||||
RETURNING created_at, updated_at
|
||||
""",
|
||||
(
|
||||
att.id, att.chat_id, att.owner_id, att.filename, att.content_type,
|
||||
att.size_bytes, att.sha256, att.width, att.height, att.object_key,
|
||||
),
|
||||
).fetchone()
|
||||
conn.execute("DELETE FROM upload_intents WHERE object_key = %s", (att.object_key,))
|
||||
# Leaving the block sends COMMIT; a failure from here on is ambiguous.
|
||||
committing = True
|
||||
except IntentLost:
|
||||
raise
|
||||
except PsycopgError as exc:
|
||||
if committing:
|
||||
raise CommitUncertain("commit outcome unknown") from exc
|
||||
raise StoreUnavailable("database unavailable") from exc
|
||||
att.status = "ready"
|
||||
att.created_at = row["created_at"]
|
||||
att.updated_at = row["updated_at"]
|
||||
return att
|
||||
|
||||
def get_attachment_for_user(self, attachment_id: str, user_id: str) -> Optional[Attachment]:
|
||||
"""Return the attachment only if user_id is a member of its chat (else None → 404)."""
|
||||
try:
|
||||
with get_pool().connection() as conn:
|
||||
row = conn.execute(
|
||||
f"""
|
||||
SELECT {_ATTACHMENT_COLUMNS}
|
||||
FROM attachments a
|
||||
JOIN chat_members cm ON cm.chat_id = a.chat_id AND cm.user_id = %s
|
||||
WHERE a.id = %s
|
||||
""",
|
||||
(user_id, attachment_id),
|
||||
).fetchone()
|
||||
except PsycopgError as exc:
|
||||
raise StoreUnavailable("database unavailable") from exc
|
||||
return _row_attachment(row) if row else None
|
||||
Reference in New Issue
Block a user