Реализовать lab5 на оценку 4: async attachments, outbox, worker и variants.

This commit is contained in:
Mikhail Verkovykh
2026-11-19 20:47:08 +03:00
parent 276dbdad8a
commit 92c67c23c0
86 changed files with 10148 additions and 30 deletions
+1
View File
@@ -0,0 +1 @@
"""Messenger API for lab4 (LB + shared sessions + idempotent messages + S3 attachments)."""
+36
View File
@@ -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()
+909
View File
@@ -0,0 +1,909 @@
"""HTTP API: multi-replica messenger behind LB with async attachments (lab5)."""
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.outbox import OutboxPublisher
from messenger.sessions import SessionStoreError
from messenger.store import (
Attachment,
AttachmentFailed,
AttachmentNotFound,
CommitUncertain,
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
outbox_publisher: Optional[OutboxPublisher] = 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, outbox_publisher
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())
outbox_publisher = OutboxPublisher(store)
outbox_publisher.start()
reconcile.start_background()
ready = True
log.info("messenger started instance_id=%s", INSTANCE_ID)
yield
ready = False
reconcile.stop_background()
if outbox_publisher is not None:
outbox_publisher.stop()
outbox_publisher = None
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"),
):
"""Revoke the presented Bearer token.
Does not require a live Redis lookup: knowing the token is enough to revoke it.
Revocation is durable in PostgreSQL so a later Redis restore cannot resurrect it.
"""
rid = request.state.request_id
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():
raise ApiError(
401, "unauthorized", "Invalid authorization", www_authenticate=bearer_challenge
)
token = parts[1].strip()
try:
revoked = sessions.revoke_session(token)
except SessionStoreError:
raise ApiError(503, "unavailable", "Session store unavailable")
if not revoked:
raise ApiError(
401, "unauthorized", "Invalid or expired session", www_authenticate=bearer_challenge
)
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 AttachmentFailed:
raise ApiError(409, "conflict", "Attachment is failed")
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")
except (StoreUnavailable, CommitUncertain):
raise ApiError(503, "unavailable", "Upload temporarily unavailable")
except Exception:
log.exception("upload persist failed request_id=%s", rid)
raise ApiError(503, "unavailable", "Upload temporarily unavailable")
finally:
attachments.discard(spooled)
upload_slots.release()
return JSONResponse(
status_code=202,
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)
name = "original" if variant in (None, "original") else variant
if name != "original" and name not in VARIANT_NAMES:
raise ApiError(400, "invalid_request", "Invalid variant")
if att.status in ("queued", "processing"):
raise ApiError(409, "conflict", "Attachment is not ready yet")
if att.status == "failed":
raise ApiError(409, "conflict", "Attachment processing failed")
if name == "original":
if not att.object_key:
raise ApiError(503, "unavailable", "Attachment content unavailable")
object_key = att.object_key
media_type = att.content_type
size_bytes = att.size_bytes
digest = att.sha256
filename = att.filename
else:
matches = [v for v in att.variants if v.name == name]
if not matches:
raise ApiError(404, "not_found", "Variant not found")
chosen = matches[0]
object_key = chosen.object_key
media_type = chosen.content_type
size_bytes = chosen.size_bytes
digest = chosen.sha256
filename = f"{name}-{att.filename}"
try:
length, chunks, body = await run_in_threadpool(s3.open_object, object_key)
except s3.S3ObjectMissing:
log.error("object missing in S3 attachment_id=%s variant=%s request_id=%s", att.id, name, rid)
raise ApiError(503, "unavailable", "Attachment content unavailable")
if length != size_bytes:
body.close()
log.error("size mismatch attachment_id=%s variant=%s request_id=%s", att.id, name, rid)
raise ApiError(503, "unavailable", "Attachment content unavailable")
def stream():
try:
yield from chunks
finally:
body.close()
headers = common_headers(
rid,
{
"Content-Length": str(size_bytes),
"ETag": f'"{digest}"',
"Cache-Control": "private, no-store",
"X-Content-Type-Options": "nosniff",
"Content-Disposition": "inline; filename*=UTF-8''" + urllib.parse.quote(filename, safe=""),
},
)
return StreamingResponse(stream(), media_type=media_type, headers=headers)
@app.post("/internal/v1/dead-letters/{dead_letter_id}/replay")
async def replay_dead_letter(
dead_letter_id: int,
request: Request,
authorization: Optional[str] = Header(default=None, alias="Authorization"),
):
"""Operator replay of a failed job. Requires a valid bearer session (lab admin demo)."""
rid = request.state.request_id
require_bearer(authorization)
try:
result = await run_in_threadpool(store.replay_dead_letter, dead_letter_id)
except StoreUnavailable:
raise ApiError(503, "unavailable", "Database unavailable")
if result is None:
raise ApiError(404, "not_found", "Dead letter not found")
if outbox_publisher is not None:
await run_in_threadpool(outbox_publisher.flush_once)
return JSONResponse(
content={"result": result, "dead_letter_id": dead_letter_id},
headers=common_headers(rid),
)
def create_app() -> FastAPI:
return app
+342
View File
@@ -0,0 +1,342 @@
"""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
def new_staging_key() -> str:
return s3.STAGING_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:
"""Accept upload into durable staging + queued job (lab5). Blocking.
Returns Attachment with status=queued. Broker publish is via transactional outbox.
"""
from messenger.store import format_ts # local import avoids cycles at module load
attachment_id = str(uuid.uuid4())
job_id = str(uuid.uuid4())
staging_key = new_staging_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=None,
status="queued",
created_at=now,
updated_at=now,
staging_key=staging_key,
error_code=None,
pipeline_version=1,
variants=[],
)
job_payload = {
"schema_version": 1,
"job_id": job_id,
"type": "attachment.process.v1",
"attachment_id": attachment_id,
"pipeline_version": 1,
"attempt": 1,
"created_at": format_ts(now),
}
# 1. Intent first: if PostgreSQL is down nothing reaches S3 (fast 503).
store.record_intent(staging_key, attachment_id, chat_id, instance)
try:
if fault:
fault("before_put", staging_key)
with open(spooled.path, "rb") as body:
s3.put_object(staging_key, body, spooled.size, spooled.content_type, spooled.sha256)
if fault:
fault("after_put", staging_key)
# 2. Queued metadata + job + outbox in one COMMIT (durable handoff before 202).
committed = store.commit_queued_attachment(
att, job_id=job_id, staging_key=staging_key, job_payload=job_payload
)
if fault:
fault("after_commit", staging_key)
return committed
except CommitUncertain:
log.warning("commit outcome unknown, staging kept key_suffix=%s", staging_key[-8:])
raise
except Exception as exc:
log.warning("upload failed, compensating key_suffix=%s err=%s", staging_key[-8:], type(exc).__name__)
_compensate(store, staging_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)
+141
View File
@@ -0,0 +1,141 @@
"""RabbitMQ helpers: durable queue, publisher confirms, consumer ack."""
from __future__ import annotations
import json
import logging
import time
from typing import Any, Callable, Optional
import pika
from pika.exceptions import AMQPConnectionError, AMQPError, ChannelClosedByBroker, StreamLostError
from messenger import config
log = logging.getLogger("messenger.broker")
EXCHANGE = ""
QUEUE = "attachment.process"
DLQ = "attachment.process.dlq"
def _params(url: Optional[str] = None) -> pika.URLParameters:
params = pika.URLParameters(url or config.broker_url())
params.heartbeat = 30
params.blocked_connection_timeout = 30
params.connection_attempts = 3
params.retry_delay = 1
return params
def connect(url: Optional[str] = None) -> pika.BlockingConnection:
return pika.BlockingConnection(_params(url))
def declare_topology(channel: pika.channel.Channel) -> None:
channel.queue_declare(queue=DLQ, durable=True)
channel.queue_declare(
queue=QUEUE,
durable=True,
arguments={
"x-dead-letter-exchange": EXCHANGE,
"x-dead-letter-routing-key": DLQ,
},
)
def publish_job(payload: dict[str, Any], *, connection: Optional[pika.BlockingConnection] = None) -> None:
"""Publish one job with delivery_mode=2 and wait for publisher confirm."""
own = connection is None
conn = connection or connect()
try:
channel = conn.channel()
channel.confirm_delivery()
declare_topology(channel)
body = json.dumps(payload, separators=(",", ":"), sort_keys=True).encode("utf-8")
channel.basic_publish(
exchange=EXCHANGE,
routing_key=QUEUE,
body=body,
properties=pika.BasicProperties(
delivery_mode=2,
content_type="application/json",
message_id=str(payload.get("job_id", "")),
type=str(payload.get("type", "attachment.process.v1")),
),
mandatory=True,
)
finally:
if own:
try:
conn.close()
except Exception:
pass
def ping(url: Optional[str] = None) -> bool:
try:
conn = connect(url)
try:
ch = conn.channel()
declare_topology(ch)
return True
finally:
conn.close()
except (AMQPConnectionError, AMQPError, OSError) as exc:
log.warning("broker ping failed: %s", type(exc).__name__)
return False
def consume_forever(
handler: Callable[[dict[str, Any], Callable[[], None], Callable[[bool], None]], None],
*,
prefetch: int,
stop_flag: Callable[[], bool],
) -> None:
"""Block consuming QUEUE. handler(payload, ack, nack(requeue))."""
while not stop_flag():
try:
conn = connect()
channel = conn.channel()
declare_topology(channel)
channel.basic_qos(prefetch_count=max(1, prefetch))
for method, _props, body in channel.consume(QUEUE, inactivity_timeout=1.0):
if stop_flag():
break
if method is None:
continue
try:
payload = json.loads(body.decode("utf-8"))
except (UnicodeDecodeError, json.JSONDecodeError):
log.error("dropping malformed broker message")
channel.basic_nack(method.delivery_tag, requeue=False)
continue
acked = False
def ack() -> None:
nonlocal acked
channel.basic_ack(method.delivery_tag)
acked = True
def nack(requeue: bool) -> None:
nonlocal acked
channel.basic_nack(method.delivery_tag, requeue=requeue)
acked = True
try:
handler(payload, ack, nack)
except Exception:
log.exception("consumer handler crashed")
if not acked:
channel.basic_nack(method.delivery_tag, requeue=True)
try:
channel.cancel()
except Exception:
pass
conn.close()
except (AMQPConnectionError, StreamLostError, ChannelClosedByBroker, OSError) as exc:
log.warning("broker consumer reconnecting after %s", type(exc).__name__)
time.sleep(1.0)
+235
View File
@@ -0,0 +1,235 @@
"""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"))
# --- Broker / worker (lab5) ---------------------------------------------------
def broker_url() -> str:
return _read_secret("BROKER_URL", "BROKER_URL_FILE")
def worker_concurrency() -> int:
return _int_env("WORKER_CONCURRENCY", 2)
def job_max_attempts() -> int:
return _int_env("JOB_MAX_ATTEMPTS", 5)
def job_timeout_seconds() -> int:
return _int_env("JOB_TIMEOUT_SECONDS", 60)
def job_backoff_base_seconds() -> float:
raw = os.environ.get("JOB_BACKOFF_BASE_SECONDS", "1").strip()
try:
value = float(raw)
except ValueError as exc:
raise RuntimeError("JOB_BACKOFF_BASE_SECONDS must be a number") from exc
if value <= 0:
raise RuntimeError("JOB_BACKOFF_BASE_SECONDS must be > 0")
return value
def job_backoff_max_seconds() -> float:
raw = os.environ.get("JOB_BACKOFF_MAX_SECONDS", "60").strip()
try:
value = float(raw)
except ValueError as exc:
raise RuntimeError("JOB_BACKOFF_MAX_SECONDS must be a number") from exc
if value < job_backoff_base_seconds():
raise RuntimeError("JOB_BACKOFF_MAX_SECONDS must be >= JOB_BACKOFF_BASE_SECONDS")
return value
def outbox_poll_seconds() -> float:
raw = os.environ.get("OUTBOX_POLL_SECONDS", "0.5").strip()
try:
value = float(raw)
except ValueError as exc:
raise RuntimeError("OUTBOX_POLL_SECONDS must be a number") from exc
if value <= 0:
raise RuntimeError("OUTBOX_POLL_SECONDS must be > 0")
return value
def staging_retention_seconds() -> int:
return _int_env("STAGING_RETENTION_SECONDS", 86400)
def worker_process_timeout_seconds() -> int:
# Wall-clock budget for decode+encode inside the worker for one job.
return _int_env("WORKER_PROCESS_TIMEOUT_SECONDS", 45)
def webp_quality() -> int:
return _int_env("WEBP_QUALITY", 80, minimum=1)
def crash_after_side_effect() -> bool:
"""Fault injection: worker exits after durable side effects, before ack."""
return os.environ.get("WORKER_CRASH_AFTER_SIDE_EFFECT", "").strip() in ("1", "true", "yes")
def crash_before_outbox_publish() -> bool:
"""Fault injection for API/outbox tests (process-local)."""
return os.environ.get("CRASH_BEFORE_OUTBOX_PUBLISH", "").strip() in ("1", "true", "yes")
+218
View File
@@ -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
+411
View File
@@ -0,0 +1,411 @@
"""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
self._sof_ids: set[int] = set()
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")
ids = set()
for i in range(components):
cid = seg[6 + 3 * i]
if cid in ids:
raise _unsupported("Duplicate JPEG component id")
ids.add(cid)
self._sof_ids = ids
self._set_dimensions(width, height)
self._seen_sof = True
if marker == 0xDA:
# SOS must name only components declared in SOF (djpeg rejects mismatches).
seg = bytes(self._seg_small)
if len(seg) < 1:
raise _unsupported("Corrupted JPEG scan header")
ns = seg[0]
if ns < 1 or ns > 4 or len(seg) < 1 + 2 * ns + 3:
raise _unsupported("Corrupted JPEG scan header")
for i in range(ns):
cid = seg[1 + 2 * i]
if cid not in self._sof_ids:
raise _unsupported("JPEG scan component not in frame header")
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)
# Keep SOF and SOS bodies: SOS component ids must match SOF.
if self._marker in _JPEG_SOF_SUPPORTED or self._marker == 0xDA:
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")
+50
View File
@@ -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)
+28
View File
@@ -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())
+62
View File
@@ -0,0 +1,62 @@
"""Transactional outbox publisher: closes the COMMIT↔publish gap."""
from __future__ import annotations
import logging
import threading
import time
from typing import Optional
from messenger import broker, config
from messenger.store import Store, StoreUnavailable
log = logging.getLogger("messenger.outbox")
class OutboxPublisher:
def __init__(self, store: Store):
self._store = store
self._stop = threading.Event()
self._thread: Optional[threading.Thread] = None
def start(self) -> None:
if self._thread and self._thread.is_alive():
return
self._stop.clear()
self._thread = threading.Thread(target=self._run, name="outbox-publisher", daemon=True)
self._thread.start()
def stop(self, timeout: float = 2.0) -> None:
self._stop.set()
if self._thread and self._thread.is_alive():
self._thread.join(timeout=timeout)
def _run(self) -> None:
interval = config.outbox_poll_seconds()
while not self._stop.is_set():
try:
self.flush_once(limit=50)
except StoreUnavailable:
log.warning("outbox: database unavailable")
except Exception:
log.exception("outbox flush failed")
self._stop.wait(interval)
def flush_once(self, limit: int = 50) -> int:
"""Publish unpublished outbox rows with broker confirms; returns published count."""
rows = self._store.claim_outbox_batch(limit)
published = 0
for row in rows:
try:
broker.publish_job(row["payload"])
self._store.mark_outbox_published(row["id"])
published += 1
except Exception as exc:
log.warning(
"outbox publish failed id=%s job=%s err=%s",
row["id"],
row["job_id"],
type(exc).__name__,
)
self._store.bump_outbox_attempt(row["id"])
return published
+342
View File
@@ -0,0 +1,342 @@
"""DB/S3 reconciler: removes orphan objects after a safe grace, never live work.
Rules (never violated, also with --grace-seconds 0):
* an object whose key is referenced by attachments.object_key, attachments.staging_key
(for queued/processing), attachment_variants.object_key, or upload_intents is never deleted;
* metadata is never deleted (a missing original is only reported);
* intent / staging cleanup re-reads row state under FOR UPDATE right before DELETE
so replay cannot race into source_missing / ready-without-bytes (TOCTOU);
* staging for queued/processing is retained regardless of STAGING_RETENTION_SECONDS.
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 = 0x4C414235 # "LAB5": one reconciler at a time across replicas
BATCH = 500
def _referenced(conn, keys: List[str]) -> set:
"""All storage keys that must not be deleted (live or finished effects)."""
if not keys:
return set()
rows = conn.execute(
"""
SELECT object_key AS k FROM attachments
WHERE object_key = ANY(%s)
UNION
SELECT staging_key FROM attachments
WHERE staging_key = ANY(%s)
AND status IN ('queued', 'processing')
UNION
SELECT object_key FROM attachment_variants
WHERE object_key = ANY(%s)
UNION
SELECT object_key FROM upload_intents
WHERE object_key = ANY(%s)
""",
(keys, keys, keys, keys),
).fetchall()
return {r["k"] 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,
EXISTS(
SELECT 1 FROM attachments a
WHERE a.object_key = i.object_key
OR (a.staging_key = i.object_key AND a.status IN ('queued', 'processing'))
) AS committed
FROM upload_intents i
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
# Re-check under the intent lock: replay/upload may have claimed the key.
live = conn.execute(
"""
SELECT 1 AS ok FROM attachments
WHERE object_key = %s
OR (staging_key = %s AND status IN ('queued', 'processing'))
""",
(key, key),
).fetchone()
if not live:
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_prefix(
conn,
prefix: str,
grace: int,
dry_run: bool,
report: Dict[str, int],
listed: Optional[set],
) -> None:
db_now = conn.execute("SELECT now() AS now").fetchone()["now"]
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:
# TOCTOU: lock and re-check in one transaction before DELETE.
# Replay may have moved failed→queued / ready and re-linked the key.
with conn.transaction():
locked = conn.execute(
"""
SELECT id, status FROM attachments
WHERE staging_key = %s OR object_key = %s
FOR UPDATE
""",
(key, key),
).fetchall()
if any(r["status"] in ("queued", "processing", "ready") for r in locked):
report["referenced_objects"] += 1
continue
variant_hit = conn.execute(
"""
SELECT 1 AS ok FROM attachment_variants
WHERE object_key = %s
FOR UPDATE
""",
(key,),
).fetchone()
if variant_hit or _referenced(conn, [key]):
report["referenced_objects"] += 1
continue
s3.delete_object(key)
report["orphans_deleted"] += 1
page.clear()
for obj in s3.list_objects(prefix=prefix):
report["objects_scanned"] += 1
if listed is not None:
listed.add(obj["Key"])
page.append(obj)
if len(page) >= BATCH:
flush()
if page:
flush()
def _cleanup_stale_staging(conn, retention: int, dry_run: bool, report: Dict[str, int]) -> None:
"""Drop staging only for terminal failed attachments older than retention."""
if dry_run:
rows = conn.execute(
"""
SELECT staging_key FROM attachments
WHERE status = 'failed'
AND staging_key IS NOT NULL
AND updated_at < now() - make_interval(secs => %s)
""",
(retention,),
).fetchall()
report["stale_staging_candidates"] = len(rows)
return
while True:
with conn.transaction():
rows = conn.execute(
"""
SELECT id, staging_key FROM attachments
WHERE status = 'failed'
AND staging_key IS NOT NULL
AND updated_at < now() - make_interval(secs => %s)
ORDER BY updated_at
LIMIT %s
FOR UPDATE SKIP LOCKED
""",
(retention, BATCH),
).fetchall()
if not rows:
return
for row in rows:
# Re-read status under row lock: replay may have moved failed→queued.
cur = conn.execute(
"SELECT status, staging_key FROM attachments WHERE id = %s",
(row["id"],),
).fetchone()
if cur is None or cur["status"] != "failed" or not cur["staging_key"]:
continue
key = cur["staging_key"]
s3.delete_object(key)
conn.execute(
"UPDATE attachments SET staging_key = NULL, updated_at = now() WHERE id = %s",
(row["id"],),
)
report["stale_staging_deleted"] += 1
if len(rows) < BATCH:
return
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,
"stale_staging_candidates": 0,
"stale_staging_deleted": 0,
}
retention = config.staging_retention_seconds()
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)
listed = set() if check_missing else None
for prefix in (s3.ORIGINAL_PREFIX, s3.STAGING_PREFIX, s3.VARIANT_PREFIX):
_sweep_prefix(conn, prefix, grace_seconds, dry_run, report, listed)
_cleanup_stale_staging(conn, retention, dry_run, report)
if listed is not None:
rows = conn.execute(
"""
SELECT object_key FROM attachments
WHERE object_key IS NOT NULL AND created_at < now()
"""
).fetchall()
report["missing_originals"] = sum(
1 for r in rows if r["object_key"] not in listed
)
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:
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")
or result.get("stale_staging_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:
_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)",
)
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())
+71
View File
@@ -0,0 +1,71 @@
"""CLI entry: python -m messenger.replay (same semantics as scripts/replay_failed.py)."""
from __future__ import annotations
import argparse
import sys
def main() -> int:
from messenger import db
from messenger.outbox import OutboxPublisher
from messenger.store import Store
parser = argparse.ArgumentParser(description="Replay failed attachment jobs")
parser.add_argument("--dead-letter-id", type=int, default=None)
parser.add_argument("--attachment-id", default=None)
parser.add_argument("--list", action="store_true", help="list open dead letters")
parser.add_argument("--note", default="operator replay")
args = parser.parse_args()
db.init_pool()
store = Store()
try:
if args.list:
with db.get_pool().connection() as conn:
rows = conn.execute(
"""
SELECT id, job_id, attachment_id, error_code, attempts, failed_at
FROM dead_letter_jobs
WHERE replayed_at IS NULL
ORDER BY failed_at
LIMIT 50
"""
).fetchall()
for r in rows:
print(
f"id={r['id']} attachment={r['attachment_id']} "
f"error={r['error_code']} attempts={r['attempts']}"
)
print(f"open_dead_letters={len(rows)}")
return 0
dead_id = args.dead_letter_id
if dead_id is None and args.attachment_id:
with db.get_pool().connection() as conn:
row = conn.execute(
"""
SELECT id FROM dead_letter_jobs
WHERE attachment_id = %s AND replayed_at IS NULL
ORDER BY failed_at DESC
LIMIT 1
""",
(args.attachment_id,),
).fetchone()
if row is None:
print("no open dead letter for attachment", file=sys.stderr)
return 2
dead_id = int(row["id"])
if dead_id is None:
parser.error("need --dead-letter-id or --attachment-id or --list")
result = store.replay_dead_letter(dead_id, note=args.note)
if result is None:
print("dead letter not found", file=sys.stderr)
return 2
OutboxPublisher(store).flush_once()
print(f"replay_result={result} dead_letter_id={dead_id}")
return 0
finally:
db.close_pool()
if __name__ == "__main__":
raise SystemExit(main())
+193
View File
@@ -0,0 +1,193 @@
"""Private S3 bucket access (SeaweedFS S3 gateway) with bounded timeouts."""
from __future__ import annotations
import io
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/"
STAGING_PREFIX = "staging/"
VARIANT_PREFIX = "variants/"
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 put_bytes(key: str, data: bytes, content_type: str, sha256_hex: str) -> None:
put_object(key, io.BytesIO(data), len(data), content_type, sha256_hex)
def get_bytes(key: str) -> bytes:
length, chunks, body = open_object(key)
try:
data = b"".join(chunks)
finally:
body.close()
if length != len(data):
raise S3Unavailable("s3 get incomplete")
return data
def copy_object(src_key: str, dst_key: str, content_type: str) -> None:
try:
client().copy_object(
Bucket=config.s3_bucket(),
Key=dst_key,
CopySource={"Bucket": config.s3_bucket(), "Key": src_key},
ContentType=content_type,
MetadataDirective="REPLACE",
)
except (BotoCoreError, ClientError) as exc:
log.warning("s3 copy failed: %s", type(exc).__name__)
raise S3Unavailable("s3 copy 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
+67
View File
@@ -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())
+283
View File
@@ -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:]))
+212
View File
@@ -0,0 +1,212 @@
"""Opaque Bearer sessions in Redis with TTL (durable via Redis AOF).
Revocation is durable in PostgreSQL so logout still wins if Redis is briefly down:
stop Redis → logout 204 → start Redis → old token is 401 (not resurrected from AOF).
"""
from __future__ import annotations
import hashlib
import json
import logging
import secrets
from datetime import datetime, timedelta, timezone
from typing import Optional
import redis
from psycopg import Error as PsycopgError
from messenger import config
from messenger.db import get_pool
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 token_hash(token: str) -> str:
return hashlib.sha256(token.encode("utf-8")).hexdigest()
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 _is_revoked(token: str) -> bool:
try:
with get_pool().connection() as conn:
row = conn.execute(
"""
SELECT 1 AS ok FROM session_revocations
WHERE token_hash = %s AND expires_at > now()
""",
(token_hash(token),),
).fetchone()
return row is not None
except PsycopgError as exc:
raise SessionStoreError("session revocation store unavailable") from exc
def _record_revocation(token: str, expires_at: Optional[datetime] = None) -> None:
"""Persist revocation so a later Redis restore cannot resurrect the session."""
exp = expires_at or (utc_now() + timedelta(seconds=config.session_ttl_seconds()))
try:
with get_pool().connection() as conn:
with conn.transaction():
conn.execute(
"""
INSERT INTO session_revocations (token_hash, revoked_at, expires_at)
VALUES (%s, now(), %s)
ON CONFLICT (token_hash) DO UPDATE
SET revoked_at = now(), expires_at = GREATEST(session_revocations.expires_at, EXCLUDED.expires_at)
""",
(token_hash(token), exp),
)
except PsycopgError as exc:
raise SessionStoreError("session revocation store unavailable") from exc
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()
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
if _is_revoked(token):
# Drop a stale Redis copy if present; never trust a revoked token again.
try:
get_client().delete(KEY_PREFIX + token)
except redis.RedisError:
pass
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:
"""Revoke durably.
Returns:
True — session existed (or Redis was down) and is now revoked → HTTP 204
False — token already revoked / unknown while Redis is up → HTTP 401
"""
if not token:
return False
if _is_revoked(token):
return False
expires_at = None
key = KEY_PREFIX + token
redis_down = False
raw = None
try:
raw = get_client().get(key)
if raw:
try:
expires_at = parse_ts(json.loads(raw)["expires_at"])
except (ValueError, KeyError, TypeError, json.JSONDecodeError):
expires_at = None
except redis.RedisError:
redis_down = True
if raw is None and not redis_down:
# Redis reachable and no live session → unknown/expired token.
return False
_record_revocation(token, expires_at)
try:
get_client().delete(key)
except redis.RedisError:
pass
return True
File diff suppressed because it is too large Load Diff
+140
View File
@@ -0,0 +1,140 @@
"""Derive attachment variants: thumbnail, crop, optimized WebP (lab5 grade 4)."""
from __future__ import annotations
import hashlib
import io
import logging
from dataclasses import dataclass
from typing import Tuple
from PIL import Image, ImageOps
log = logging.getLogger("messenger.variants")
# Grade-4 optimized WebP: quality/method chosen for size vs fidelity; EXIF stripped.
WEBP_QUALITY = 80
WEBP_METHOD = 4
WEBP_MAX_EDGE = 1280
THUMB_MAX_EDGE = 256
CROP_EDGE = 128
class ProcessingError(Exception):
def __init__(self, code: str, message: str, *, permanent: bool = True):
super().__init__(message)
self.code = code
self.message = message
self.permanent = permanent
@dataclass(frozen=True)
class VariantBytes:
name: str
content_type: str
data: bytes
width: int
height: int
sha256: str
@property
def size_bytes(self) -> int:
return len(self.data)
def _open_oriented(data: bytes) -> Image.Image:
try:
img = Image.open(io.BytesIO(data))
img.load()
except Exception as exc:
raise ProcessingError("invalid_image", "Cannot decode image") from exc
img = ImageOps.exif_transpose(img)
if img.mode in ("RGBA", "LA") or (img.mode == "P" and "transparency" in img.info):
rgba = img.convert("RGBA")
background = Image.new("RGB", rgba.size, (255, 255, 255))
background.paste(rgba, mask=rgba.split()[-1])
return background
if img.mode != "RGB":
return img.convert("RGB")
return img
def _fit(width: int, height: int, max_edge: int) -> Tuple[int, int]:
"""Letterbox into max_edge×max_edge without upscaling; integer floor, min 1 px.
Uses integer division so 319×200 → 256×160 (not 256×161 from float rounding).
"""
if width <= 0 or height <= 0:
raise ProcessingError("invalid_image", "Invalid dimensions")
if width <= max_edge and height <= max_edge:
return width, height
# min(max_edge/w, max_edge/h) applied with floor: longer side becomes max_edge.
if width >= height:
return max_edge, max(1, (height * max_edge) // width)
return max(1, (width * max_edge) // height), max_edge
def _jpeg_bytes(img: Image.Image) -> bytes:
buf = io.BytesIO()
# No EXIF; progressive off for deterministic small thumbs.
img.save(buf, format="JPEG", quality=85, optimize=True, exif=b"")
return buf.getvalue()
def _webp_bytes(img: Image.Image) -> bytes:
buf = io.BytesIO()
img.save(
buf,
format="WEBP",
quality=WEBP_QUALITY,
method=WEBP_METHOD,
exact=False,
)
return buf.getvalue()
def _pack(name: str, content_type: str, data: bytes, width: int, height: int) -> VariantBytes:
return VariantBytes(
name=name,
content_type=content_type,
data=data,
width=width,
height=height,
sha256=hashlib.sha256(data).hexdigest(),
)
def make_thumbnail(original: bytes) -> VariantBytes:
img = _open_oriented(original)
tw, th = _fit(img.width, img.height, THUMB_MAX_EDGE)
if (tw, th) != (img.width, img.height):
img = img.resize((tw, th), Image.Resampling.LANCZOS)
data = _jpeg_bytes(img)
return _pack("thumbnail", "image/jpeg", data, tw, th)
def make_crop(original: bytes) -> VariantBytes:
"""Centered square 128×128 JPEG; small sources may be upscaled."""
img = _open_oriented(original)
side = min(img.width, img.height)
left = (img.width - side) // 2
top = (img.height - side) // 2
img = img.crop((left, top, left + side, top + side))
if img.size != (CROP_EDGE, CROP_EDGE):
img = img.resize((CROP_EDGE, CROP_EDGE), Image.Resampling.LANCZOS)
data = _jpeg_bytes(img)
return _pack("crop", "image/jpeg", data, CROP_EDGE, CROP_EDGE)
def make_optimized(original: bytes) -> VariantBytes:
"""WebP fitted into 1280×1280 without upscaling; EXIF removed; quality documented."""
img = _open_oriented(original)
ow, oh = _fit(img.width, img.height, WEBP_MAX_EDGE)
if (ow, oh) != (img.width, img.height):
img = img.resize((ow, oh), Image.Resampling.LANCZOS)
data = _webp_bytes(img)
return _pack("optimized", "image/webp", data, ow, oh)
def build_all(original: bytes) -> Tuple[VariantBytes, ...]:
return (make_thumbnail(original), make_crop(original), make_optimized(original))
+276
View File
@@ -0,0 +1,276 @@
"""Attachment processing worker: broker → variants → S3 → ready (lab5)."""
from __future__ import annotations
import logging
import os
import random
import signal
import socket
import sys
import threading
import time
from pathlib import Path
from typing import Any, Callable, Optional
_SRC = Path(__file__).resolve().parents[1]
if str(_SRC) not in sys.path:
sys.path.insert(0, str(_SRC))
from messenger import broker, config, db, s3
from messenger.outbox import OutboxPublisher
from messenger.store import Store, StoreUnavailable, Variant
from messenger.variants import ProcessingError, build_all
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
log = logging.getLogger("messenger.worker")
_stop = threading.Event()
_owner = (os.environ.get("HOSTNAME") or socket.gethostname())[:64]
def _backoff_seconds(attempt: int) -> float:
base = config.job_backoff_base_seconds()
cap = config.job_backoff_max_seconds()
exp = min(cap, base * (2 ** max(0, attempt - 1)))
# Full jitter: spread retries so thundering herds do not sync.
return random.uniform(0, exp)
def _variant_key(attachment_id: str, name: str, pipeline_version: int) -> str:
ext = {"thumbnail": "jpg", "crop": "jpg", "optimized": "webp"}[name]
return f"{s3.VARIANT_PREFIX}{attachment_id}/v{pipeline_version}/{name}.{ext}"
def process_job(store: Store, payload: dict[str, Any]) -> str:
"""
Process one job payload.
Returns: 'ack' | 'nack_requeue' (only for unexpected infra blips before side effects).
"""
job_id = str(payload.get("job_id", ""))
attachment_id = str(payload.get("attachment_id", ""))
if not job_id or not attachment_id:
log.error("malformed job payload")
return "ack"
leased = store.try_lease_job(job_id, _owner, config.job_timeout_seconds())
if leased is None:
# Backoff window or another worker holds the lease. Brief pause then
# requeue — do not ack-drop (that permanently loses the delivery).
time.sleep(0.2)
return "nack_requeue"
if leased.get("already_done") or leased.get("already_failed"):
return "ack"
att = leased["attachment"]
pipeline_version = int(leased["pipeline_version"])
attempt = int(leased["attempt"])
staging_key = att.staging_key
if not staging_key:
store.fail_or_retry_job(
job_id=job_id,
attachment_id=attachment_id,
error_code="processing_failed",
message="missing staging object",
permanent=True,
max_attempts=config.job_max_attempts(),
delay_seconds=0,
payload=payload,
)
return "ack"
# Idempotent short-circuit: if variants+original already present for this version.
if att.status == "ready" and att.object_key and len(att.variants) >= 1:
return "ack"
try:
original_bytes = s3.get_bytes(staging_key)
except s3.S3ObjectMissing:
store.fail_or_retry_job(
job_id=job_id,
attachment_id=attachment_id,
error_code="invalid_image",
message="staging object missing",
permanent=True,
max_attempts=config.job_max_attempts(),
delay_seconds=0,
payload=payload,
)
return "ack"
except s3.S3Unavailable:
outcome = store.fail_or_retry_job(
job_id=job_id,
attachment_id=attachment_id,
error_code="processing_failed",
message="s3 unavailable reading staging",
permanent=False,
max_attempts=config.job_max_attempts(),
delay_seconds=_backoff_seconds(attempt),
payload=payload,
)
return "ack" if outcome in ("retry", "failed") else "ack"
if len(original_bytes) != att.size_bytes:
store.fail_or_retry_job(
job_id=job_id,
attachment_id=attachment_id,
error_code="invalid_image",
message="staging size mismatch",
permanent=True,
max_attempts=config.job_max_attempts(),
delay_seconds=0,
payload=payload,
)
return "ack"
# Hard wall-clock deadline: a hung live decode must not sit in processing forever.
# Lease recovery alone does not interrupt a stuck process; this does.
try:
from concurrent.futures import ThreadPoolExecutor, TimeoutError as FuturesTimeout
with ThreadPoolExecutor(max_workers=1) as pool:
fut = pool.submit(build_all, original_bytes)
try:
variants = fut.result(timeout=config.worker_process_timeout_seconds())
except FuturesTimeout:
raise ProcessingError(
"processing_failed", "processing timeout", permanent=False
) from None
except ProcessingError as exc:
outcome = store.fail_or_retry_job(
job_id=job_id,
attachment_id=attachment_id,
error_code=exc.code,
message=exc.message,
permanent=exc.permanent,
max_attempts=config.job_max_attempts(),
delay_seconds=_backoff_seconds(attempt),
payload=payload,
)
log.warning("job %s processing error %s → %s", job_id, exc.code, outcome)
return "ack"
original_key = s3.ORIGINAL_PREFIX + attachment_id.replace("-", "") + uuid_suffix(att.sha256)
stored_variants: list[Variant] = []
try:
# Publish original to final prefix (bytes identical to staging).
s3.put_bytes(original_key, original_bytes, att.content_type, att.sha256)
for vb in variants:
key = _variant_key(attachment_id, vb.name, pipeline_version)
s3.put_bytes(key, vb.data, vb.content_type, vb.sha256)
stored_variants.append(
Variant(
name=vb.name,
content_type=vb.content_type,
size_bytes=vb.size_bytes,
width=vb.width,
height=vb.height,
sha256=vb.sha256,
object_key=key,
)
)
ok = store.complete_job_ready(
job_id=job_id,
attachment_id=attachment_id,
pipeline_version=pipeline_version,
original_key=original_key,
variants=stored_variants,
staging_key=staging_key,
)
if not ok:
log.info("job %s lost race to newer pipeline; acking", job_id)
return "ack"
# Safe to drop staging only after durable ready metadata.
try:
s3.delete_object(staging_key)
except s3.S3Unavailable:
log.warning("staging cleanup deferred for %s", staging_key[-8:])
if config.crash_after_side_effect():
log.error("fault injection: crash after side effect before ack")
os._exit(99)
return "ack"
except s3.S3Unavailable as exc:
outcome = store.fail_or_retry_job(
job_id=job_id,
attachment_id=attachment_id,
error_code="processing_failed",
message=f"s3 write failed: {type(exc).__name__}",
permanent=False,
max_attempts=config.job_max_attempts(),
delay_seconds=_backoff_seconds(attempt),
payload=payload,
)
log.warning("job %s s3 write failed → %s", job_id, outcome)
return "ack"
def uuid_suffix(sha256: str) -> str:
return sha256[:16]
def _handle(
store: Store,
payload: dict[str, Any],
ack: Callable[[], None],
nack: Callable[[bool], None],
) -> None:
try:
result = process_job(store, payload)
except StoreUnavailable:
log.warning("database unavailable during job; requeue")
nack(True)
return
except Exception:
log.exception("unexpected worker error")
nack(True)
return
if result == "ack":
ack()
elif result == "nack_requeue":
nack(True)
else:
nack(True)
def _lease_reaper(store: Store, outbox: OutboxPublisher) -> None:
while not _stop.wait(5.0):
try:
n = store.recover_expired_leases()
if n:
log.info("recovered %s expired leases", n)
outbox.flush_once()
except Exception:
log.exception("lease reaper failed")
def main() -> None:
signal.signal(signal.SIGTERM, lambda *_: _stop.set())
signal.signal(signal.SIGINT, lambda *_: _stop.set())
db.init_pool()
s3.init_client()
store = Store()
outbox = OutboxPublisher(store)
outbox.start()
reaper = threading.Thread(target=_lease_reaper, args=(store, outbox), name="lease-reaper", daemon=True)
reaper.start()
log.info(
"worker started owner=%s concurrency=%s max_attempts=%s",
_owner,
config.worker_concurrency(),
config.job_max_attempts(),
)
try:
broker.consume_forever(
lambda payload, ack, nack: _handle(store, payload, ack, nack),
prefetch=config.worker_concurrency(),
stop_flag=_stop.is_set,
)
finally:
_stop.set()
outbox.stop()
db.close_pool()
log.info("worker stopped")
if __name__ == "__main__":
main()