Implement durable image queue with outbox worker and recovery checks

This commit is contained in:
2026-11-21 11:56:57 +03:00
parent 276dbdad8a
commit 7909110924
52 changed files with 2658 additions and 48 deletions
+1
View File
@@ -0,0 +1 @@
"""Laboratory 1: a single-process, in-memory messenger."""
+17
View File
@@ -0,0 +1,17 @@
import logging
import os
import uvicorn
def main():
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logging.getLogger("psycopg.pool").setLevel(logging.CRITICAL)
logging.info("Starting lab3 environment=%s with shared PostgreSQL and Redis", os.getenv("APP_ENV", "lab"))
uvicorn.run("app.api:app", host=os.getenv("APP_HOST", "0.0.0.0"),
port=int(os.getenv("APP_PORT", "8080")), workers=1,
access_log=False, timeout_graceful_shutdown=5)
if __name__ == "__main__":
main()
+194
View File
@@ -0,0 +1,194 @@
import asyncio
from contextlib import asynccontextmanager
import json
import logging
import os
from pathlib import Path
import re
from time import perf_counter
from uuid import uuid4
from fastapi import Depends, FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from fastapi.responses import Response
import psycopg
from psycopg_pool import PoolTimeout, TooManyRequests
from redis.exceptions import RedisError
from pydantic import ValidationError
from starlette.exceptions import HTTPException
from .config import Settings
from .errors import APIError, invalid, unavailable
from .models import CreateChat, CreateMessage, CreateUser
from .security import basic_credentials, identifier
from .store import Store
from .attachments import Attachments, metadata
from botocore.exceptions import BotoCoreError, ClientError
from starlette.requests import ClientDisconnect
logger = logging.getLogger("messenger")
def error_response(request, status, code, message, headers=None):
return JSONResponse(status_code=status, headers=headers, content={"error": {
"code": code, "message": message, "request_id": request.state.request_id}})
async def body(request, model):
content_type = request.headers.get("content-type", "").split(";", 1)[0].strip().lower()
if content_type != "application/json":
raise APIError(415, "unsupported_media_type", "Use application/json")
try:
raw = (await request.body()).decode("utf-8")
def reject_constant(value):
raise ValueError("Nonstandard JSON constant")
data = json.loads(raw, parse_constant=reject_constant)
return model.model_validate(data)
except (ValueError, UnicodeError, ValidationError):
raise invalid("Body must be valid UTF-8 JSON with the required fields and types") from None
def pagination(request):
raw = request.query_params.get("limit", "50")
if re.fullmatch(r"[0-9]+", raw) is None or len(raw) > 3 or not 1 <= int(raw) <= 100:
raise invalid("Limit must be an integer from 1 to 100")
return int(raw), request.query_params.get("cursor")
def create_app(settings=None):
@asynccontextmanager
async def lifespan(app):
store = Store(settings or Settings.load())
app.state.store = store
app.state.attachments = Attachments(store)
try:
await store.open()
yield
finally:
await store.close()
instance_id = os.getenv("HOSTNAME", "api") + "-" + uuid4().hex[:12]
app = FastAPI(title="Lab 5 messenger", docs_url=None, redoc_url=None,
openapi_url=None, redirect_slashes=False, lifespan=lifespan)
@app.middleware("http")
async def request_context(request, call_next):
request.state.request_id = str(uuid4())
start = perf_counter()
try:
async with asyncio.timeout(35):
response = await call_next(request)
except (psycopg.Error, PoolTimeout, TooManyRequests, RedisError, BotoCoreError, ClientError, TimeoutError, ClientDisconnect):
error = unavailable()
logger.warning("Storage unavailable request_id=%s", request.state.request_id)
response = error_response(request, error.status, error.code, error.message)
except Exception:
logger.error("Unhandled error request_id=%s", request.state.request_id)
response = error_response(request, 500, "internal_error", "Internal server error")
response.headers["X-Request-Id"] = request.state.request_id
response.headers["X-Instance-Id"] = instance_id
response.headers["X-App-Version"] = os.getenv("APP_VERSION", "lab3-v1")
logger.info("request_id=%s method=%s path=%s status=%s duration_ms=%.2f",
request.state.request_id, request.method, request.url.path,
response.status_code, (perf_counter() - start) * 1000)
return response
@app.exception_handler(APIError)
async def api_error(request, error):
return error_response(request, error.status, error.code, error.message, error.headers)
@app.exception_handler(RequestValidationError)
async def validation_error(request, error):
return error_response(request, 400, "invalid_request", "Invalid request parameters")
@app.exception_handler(HTTPException)
async def routing_error(request, error):
code = "not_found" if error.status_code == 404 else "invalid_request"
return error_response(request, error.status_code, code, "Unknown path or unsupported method")
async def current_user(request: Request):
user, token = await app.state.store.authenticate(request.headers.get("authorization"))
request.state.session_token = token
return user
@app.get("/health/live")
async def health():
return {"status": "ok"}
@app.get("/health/ready")
async def readiness():
await app.state.store.ready()
await asyncio.to_thread(app.state.attachments.s3.head_bucket, Bucket="attachments")
return {"status": "ok"}
@app.post("/api/v1/auth/sessions", status_code=201)
async def login(request: Request):
credentials = basic_credentials(request.headers.get("authorization"))
if await request.body():
raise invalid("Session creation does not accept a body")
return await app.state.store.login(*credentials)
@app.delete("/api/v1/auth/sessions/current", status_code=204)
async def logout(request: Request, user=Depends(current_user)):
await app.state.store.logout(request.state.session_token)
return Response(status_code=204)
@app.post("/api/v1/users", status_code=201)
async def create_user(request: Request):
return await app.state.store.create_user(await body(request, CreateUser))
@app.get("/api/v1/users/me")
async def me(user=Depends(current_user)):
return user
@app.post("/api/v1/chats", status_code=201)
async def create_chat(request: Request, user=Depends(current_user)):
return await app.state.store.create_chat(user["id"], await body(request, CreateChat))
@app.get("/api/v1/chats")
async def list_chats(request: Request, user=Depends(current_user)):
return await app.state.store.list_chats(user["id"], *pagination(request))
@app.get("/api/v1/chats/{chat_id}")
async def get_chat(chat_id: str, user=Depends(current_user)):
return await app.state.store.get_chat(user["id"], identifier(chat_id))
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
async def create_message(chat_id: str, request: Request, user=Depends(current_user)):
chat_id = identifier(chat_id)
await app.state.store.get_chat(user["id"], chat_id)
key = request.headers.get("idempotency-key", "")
if re.fullmatch(r"[A-Za-z0-9._:-]{1,128}", key, flags=re.ASCII) is None:
raise invalid("A valid Idempotency-Key is required")
return await app.state.store.create_message(user["id"], chat_id,
await body(request, CreateMessage), key)
@app.get("/api/v1/chats/{chat_id}/messages")
async def list_messages(chat_id: str, request: Request, user=Depends(current_user)):
chat_id = identifier(chat_id)
await app.state.store.get_chat(user["id"], chat_id)
return await app.state.store.list_messages(user["id"], chat_id, *pagination(request))
@app.post("/api/v1/chats/{chat_id}/attachments", status_code=202)
async def upload(chat_id: str, request: Request, user=Depends(current_user)):
return await app.state.attachments.upload(user["id"], identifier(chat_id), request)
@app.get("/api/v1/attachments/{attachment_id}")
async def attachment(attachment_id: str, user=Depends(current_user)):
return metadata(await app.state.attachments.get(user["id"], identifier(attachment_id)))
@app.get("/api/v1/attachments/{attachment_id}/content")
async def content(attachment_id: str, request: Request, user=Depends(current_user)):
row = await app.state.attachments.get(user["id"], identifier(attachment_id))
return await app.state.attachments.download(row, request.query_params.get("variant", "original"))
@app.get("/openapi.json", include_in_schema=False)
async def contract():
path = Path(__file__).resolve().parents[1] / "contracts" / "openapi.json"
return json.loads(path.read_text(encoding="utf-8"))
return app
app = create_app()
+195
View File
@@ -0,0 +1,195 @@
"""Private S3 originals and durable upload intents."""
import asyncio
from contextlib import asynccontextmanager
import hashlib
import os
from pathlib import Path
import tempfile
import warnings
from uuid import uuid4, UUID
import boto3
from botocore.config import Config
from PIL import Image, UnidentifiedImageError
from starlette.responses import StreamingResponse
from .errors import APIError, invalid
from .store import public
MAX_BYTES = 10 * 1024 * 1024
MAX_PIXELS = 40_000_000
Image.MAX_IMAGE_PIXELS = MAX_PIXELS
BUCKET = 'attachments'
def secret(name):
return Path('/run/secrets/' + name).read_text().strip()
def client():
return boto3.client('s3', endpoint_url='http://minio:9000', region_name='us-east-1',
aws_access_key_id='messenger-api', aws_secret_access_key=secret('s3_secret_key'),
config=Config(connect_timeout=2, read_timeout=3, retries={'max_attempts': 0},
s3={'addressing_style': 'path'}, max_pool_connections=4))
def validate_image(file, content_type):
try:
with warnings.catch_warnings():
warnings.simplefilter('error', Image.DecompressionBombWarning)
file.seek(0)
with Image.open(file) as image:
if image.width * image.height > MAX_PIXELS:
raise APIError(413, 'payload_too_large', 'Too many pixels')
if image.format not in ('PNG', 'JPEG') or Image.MIME[image.format] != content_type:
raise APIError(415, 'unsupported_media_type', 'Image MIME does not match')
image.verify()
file.seek(0)
with Image.open(file) as image:
image.load()
except (Image.DecompressionBombError, Image.DecompressionBombWarning):
raise APIError(413, 'payload_too_large', 'Too many pixels') from None
except (UnidentifiedImageError, OSError, SyntaxError, ValueError):
raise APIError(415, 'unsupported_media_type', 'Invalid image') from None
finally:
file.seek(0)
def metadata(row):
row = dict(row)
row['owner_id'] = row['uploader_id']
row.setdefault('updated_at', row['created_at'])
return public({k: row[k] for k in ('id','chat_id','owner_id','filename','content_type',
'size_bytes','sha256','status','created_at','updated_at')}) | {'variants': row['variants'], 'error_code': row['error_code']}
async def blocking(function, *args, **kwargs):
# Cancellation must not close the spool or release the SQL lock while a thread uses it.
task = asyncio.create_task(asyncio.to_thread(function, *args, **kwargs))
try:
return await asyncio.shield(task)
except asyncio.CancelledError:
await task
raise
class Attachments:
def __init__(self, store):
self.store = store
self.s3 = client()
# One decode per replica bounds decoded RGBA memory to about 160 MB.
self.slots = asyncio.Semaphore(1)
@asynccontextmanager
async def slot(self):
try:
await asyncio.wait_for(self.slots.acquire(), timeout=10)
except TimeoutError:
raise APIError(503, 'unavailable', 'Upload capacity is busy') from None
try:
yield
finally:
self.slots.release()
async def get(self, actor, attachment_id):
async with self.store.pool.connection() as conn:
cur = await conn.execute('''SELECT a.* FROM attachments a JOIN chat_members m
ON m.chat_id=a.chat_id WHERE a.id=%s AND m.user_id=%s''',
(attachment_id, UUID(actor)))
row = await cur.fetchone()
if row is None:
raise APIError(404, 'not_found', 'Attachment not found')
return row
async def upload(self, actor, chat_id, request):
await self.store.get_chat(actor, chat_id)
name = request.query_params.get('filename', '')
if not 1 <= len(name) <= 255 or any(c in '/\\' or ord(c) < 32 or ord(c) == 127 for c in name):
raise invalid('Invalid filename')
mime = request.headers.get('content-type', '').strip().lower()
if mime not in ('image/png','image/jpeg'):
raise APIError(415, 'unsupported_media_type', 'Use PNG or JPEG')
length = request.headers.get('content-length')
if length is not None:
if not length.isascii() or not length.isdecimal():
raise invalid('Invalid Content-Length')
if int(length) > MAX_BYTES:
raise APIError(413, 'payload_too_large', 'File exceeds 10 MiB')
async with self.slot():
# Temporary spool is only staging, never the source of confirmed originals.
with tempfile.TemporaryFile() as file:
size = 0
digest = hashlib.sha256()
async with asyncio.timeout(20):
async for chunk in request.stream():
size += len(chunk)
if size > MAX_BYTES:
raise APIError(413, 'payload_too_large', 'File exceeds 10 MiB')
file.write(chunk)
digest.update(chunk)
await blocking(validate_image, file, mime)
attachment_id = uuid4()
key = 'original/' + attachment_id.hex
# Commit the intent BEFORE PUT: even a killed process leaves a tracked key.
async with self.store.pool.connection() as conn:
await conn.execute('''INSERT INTO attachments
(id,chat_id,uploader_id,object_key,filename,content_type,size_bytes,sha256,status)
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,'pending')''',
(attachment_id,chat_id,UUID(actor),key,name,mime,size,digest.hexdigest()))
# The pending row tracks the staging key before S3 PUT.
async with self.store.pool.connection() as conn:
await conn.execute('SELECT id FROM attachments WHERE id=%s FOR UPDATE', (attachment_id,))
await blocking(self.s3.put_object, Bucket=BUCKET, Key='staging/'+attachment_id.hex,
Body=file, ContentLength=size, ContentType=mime)
cur = await conn.execute("UPDATE attachments SET status='queued', updated_at=clock_timestamp() WHERE id=%s RETURNING *",
(attachment_id,))
result = metadata(await cur.fetchone())
await conn.execute('INSERT INTO jobs(id,attachment_id) VALUES (%s,%s)', (uuid4(),attachment_id))
# COMMIT of queued + job is the durable handoff; publisher is independent.
return result
async def download(self, row, variant='original'):
if row['status'] != 'ready':
raise APIError(409, 'conflict', 'Attachment is not ready')
row = dict(row)
if variant != 'original':
info = next((v for v in row['variants'] if v['name']==variant), None)
if info is None:
raise APIError(404, 'not_found', 'Variant not found')
row.update(info)
row['object_key'] = 'variants/'+row['id'].hex+'/v1/'+variant
obj = await asyncio.to_thread(self.s3.get_object, Bucket=BUCKET, Key=row['object_key'])
stream = obj['Body']
async def chunks():
try:
while chunk := await asyncio.to_thread(stream.read, 64 * 1024):
yield chunk
finally:
stream.close()
return StreamingResponse(chunks(), media_type=row['content_type'], headers={
'Content-Length': str(row['size_bytes']), 'X-Content-Type-Options': 'nosniff'})
async def cleanup(self):
removed = 0
async with self.store.pool.connection() as conn:
cur = await conn.execute("""SELECT id,object_key FROM attachments WHERE status='pending'
AND created_at < clock_timestamp()-interval '1 hour' ORDER BY created_at
LIMIT 100 FOR UPDATE SKIP LOCKED""")
for row in await cur.fetchall():
await asyncio.to_thread(self.s3.delete_object, Bucket=BUCKET, Key='staging/'+row['id'].hex)
await conn.execute("DELETE FROM attachments WHERE id=%s AND status='pending'", (row['id'],))
removed += 1
return removed
async def cleaner():
from .config import Settings
from .store import Store
store = Store(Settings.load())
await store.open()
attachments = Attachments(store)
try:
while True:
try:
print({'removed_pending': await attachments.cleanup()}, flush=True)
except Exception:
print('Cleanup deferred; storage unavailable', flush=True)
await asyncio.sleep(60)
finally:
await store.close()
if __name__ == '__main__':
asyncio.run(cleaner())
+28
View File
@@ -0,0 +1,28 @@
"""Runtime settings; credential values are never logged."""
from dataclasses import dataclass
import os
from pathlib import Path
def secret(name):
return Path(os.environ[name + "_FILE"]).read_text(encoding="utf-8").strip()
@dataclass(frozen=True)
class Settings:
database_url: str
cache_url: str
cursor_key: bytes
session_ttl: int
@classmethod
def load(cls):
ttl = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
if not 1 <= ttl <= 604800:
raise ValueError("SESSION_TTL_SECONDS must be in 1..604800")
if os.getenv("SESSION_STORE", "redis") != "redis":
raise ValueError("This deployment uses SESSION_STORE=redis")
key = secret("CURSOR_KEY").encode()
if len(key) < 32:
raise ValueError("Cursor key must contain at least 32 bytes")
return cls(secret("DATABASE_URL"), secret("CACHE_URL"), key, ttl)
+22
View File
@@ -0,0 +1,22 @@
class APIError(Exception):
def __init__(self, status: int, code: str, message: str, headers=None):
self.status = status
self.code = code
self.message = message
self.headers = headers or {}
super().__init__(message)
def invalid(message="Invalid request"):
return APIError(400, "invalid_request", message)
def unauthorized(basic=False):
challenge = ('Basic realm="messenger", charset="UTF-8"' if basic
else 'Bearer realm="messenger"')
return APIError(401, "unauthorized", "Valid credentials required",
{"WWW-Authenticate": challenge})
def unavailable():
return APIError(503, "unavailable", "Storage temporarily unavailable")
+37
View File
@@ -0,0 +1,37 @@
"""Apply numbered migrations atomically; safe to repeat and serialize."""
import hashlib
from pathlib import Path
import psycopg
from .config import secret
ROOT = Path(__file__).resolve().parents[1]
def migrate():
with psycopg.connect(secret("DATABASE_URL"), connect_timeout=2,
options="-c statement_timeout=10000 -c lock_timeout=5000") as conn:
conn.execute("SELECT pg_advisory_xact_lock(202602)")
conn.execute("""CREATE TABLE IF NOT EXISTS schema_migrations (
version text PRIMARY KEY, sha256 text NOT NULL,
applied_at timestamptz NOT NULL DEFAULT clock_timestamp())""")
for path in sorted((ROOT / "migrations").glob("[0-9]*.sql")):
# Git checkout may change LF to CRLF on Windows; SQL is unchanged.
content = path.read_text(encoding="utf-8").encode("utf-8")
checksum = hashlib.sha256(content).hexdigest()
row = conn.execute("SELECT sha256 FROM schema_migrations WHERE version=%s", (path.name,)).fetchone()
if row:
if row[0] != checksum:
raise RuntimeError("Applied migration checksum differs: " + path.name)
print("Unchanged:", path.name)
continue
conn.execute(content.decode("utf-8"))
conn.execute("INSERT INTO schema_migrations(version, sha256) VALUES (%s, %s)",
(path.name, checksum))
print("Applied:", path.name)
print("PASS: migrations committed")
if __name__ == "__main__":
migrate()
+73
View File
@@ -0,0 +1,73 @@
"""Strict request models; strings retain their original Unicode content."""
import re
from uuid import UUID
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
class Input(BaseModel):
model_config = ConfigDict(strict=True, extra="forbid")
@field_validator("*", check_fields=False)
@classmethod
def valid_text(cls, value):
if isinstance(value, str):
if not value.strip():
raise ValueError("A string must not be blank")
value.encode("utf-8")
if "\x00" in value:
raise ValueError("NUL is not supported")
return value
class CreateUser(Input):
username: str
display_name: str = Field(min_length=1, max_length=100)
password: str = Field(min_length=12, max_length=128)
@field_validator("username")
@classmethod
def username_format(cls, value):
if re.fullmatch(r"[a-z0-9_]{3,32}", value) is None:
raise ValueError("Invalid username")
return value
class CreateChat(Input):
title: str = Field(min_length=1, max_length=100)
member_ids: list[str] = Field(min_length=1, max_length=100)
@field_validator("member_ids")
@classmethod
def members(cls, values):
normalized = [str(UUID(value)) for value in values]
if len(set(normalized)) != len(normalized):
raise ValueError("Duplicate members")
return normalized
class CreateMessage(Input):
text: str = Field(max_length=4000)
attachment_ids: list[str] = Field(default_factory=list, max_length=10)
@field_validator("text")
@classmethod
def valid_text(cls, value):
value.encode("utf-8")
if "\x00" in value:
raise ValueError("Invalid text")
return value
@field_validator("attachment_ids")
@classmethod
def attachments(cls, values):
normalized = [str(UUID(value)) for value in values]
if len(set(normalized)) != len(normalized):
raise ValueError("Duplicate attachments")
return normalized
@model_validator(mode="after")
def not_empty(self):
if not self.text.strip() and not self.attachment_ids:
raise ValueError("Message is empty")
return self
+181
View File
@@ -0,0 +1,181 @@
"""PostgreSQL outbox, Redis Streams at-least-once transport and fenced effects."""
import asyncio
import hashlib
import json
import os
from pathlib import Path
import random
import sys
import tempfile
from uuid import uuid4, UUID
from psycopg.types.json import Jsonb
from redis.asyncio import Redis
from redis.exceptions import ResponseError
from .attachments import Attachments, BUCKET
from .config import Settings
from .store import Store
STREAM='images.v1'
GROUP='workers'
MAX_ATTEMPTS=int(os.getenv('MAX_ATTEMPTS','5'))
def broker():
return Redis.from_url(Path('/run/secrets/cache_url').read_text().strip().replace('@redis:', '@broker:'), decode_responses=True)
async def publish(store, queue, attachments):
async with store.pool.connection() as conn:
# Row locks fence stale workers; recovery waits until their connection is gone.
expired=await conn.execute("""SELECT id,attachment_id,attempts FROM jobs WHERE state='processing'
AND lease_until<clock_timestamp() FOR UPDATE SKIP LOCKED""")
for row in await expired.fetchall():
if row['attempts']>=MAX_ATTEMPTS:
await conn.execute("UPDATE jobs SET state='failed',lease_until=NULL WHERE id=%s",(row['id'],))
await conn.execute("UPDATE attachments SET status='failed',error_code='retry_exhausted',updated_at=clock_timestamp() WHERE id=%s",(row['attachment_id'],))
continue
await conn.execute("UPDATE jobs SET state='queued', available_at=clock_timestamp(),last_published=NULL WHERE id=%s",(row['id'],))
await conn.execute("UPDATE attachments SET status='queued',updated_at=clock_timestamp() WHERE id=%s",(row['attachment_id'],))
cur=await conn.execute("""SELECT * FROM jobs WHERE state='queued' AND available_at<=clock_timestamp()
AND (last_published IS NULL OR last_published<clock_timestamp()-interval '5 seconds')
ORDER BY available_at LIMIT 50 FOR UPDATE SKIP LOCKED""")
for row in await cur.fetchall():
payload=dict(schema_version=1,job_id=str(row['id']),type='attachment.process.v1',
attachment_id=str(row['attachment_id']),pipeline_version=1,attempt=row['attempts']+1,
created_at=row['created_at'].isoformat())
await queue.xadd(STREAM,{'payload':json.dumps(payload)})
# Redis appendfsync=always confirms its AOF before replying. A lost reply
# or DB rollback causes a duplicate. DB intent stays until terminal state.
await conn.execute('UPDATE jobs SET last_published=clock_timestamp() WHERE id=%s',(row['id'],))
# Delete staging only for safely committed ready; repeated deletion is safe.
async with store.pool.connection() as conn:
cur=await conn.execute("SELECT id FROM attachments WHERE status='ready' AND staging_cleaned=false LIMIT 100")
for row in await cur.fetchall():
await asyncio.to_thread(attachments.s3.delete_object,Bucket=BUCKET,Key='staging/'+row['id'].hex)
await conn.execute('UPDATE attachments SET staging_cleaned=true WHERE id=%s',(row['id'],))
# Failed inputs retained for replay for 7 days, then removed; row remains auditable.
cur=await conn.execute("""SELECT a.id FROM attachments a JOIN jobs j ON j.attachment_id=a.id
WHERE a.status='failed' AND a.updated_at<clock_timestamp()-interval '7 days'
AND NOT a.staging_cleaned LIMIT 100 FOR UPDATE OF j SKIP LOCKED""")
for row in await cur.fetchall():
await asyncio.to_thread(attachments.s3.delete_object,Bucket=BUCKET,Key='staging/'+row['id'].hex)
await conn.execute('UPDATE attachments SET staging_cleaned=true WHERE id=%s',(row['id'],))
async def process(store, attachments, payload):
job_id=UUID(payload['job_id'])
async with store.pool.connection() as conn:
cur=await conn.execute('SELECT * FROM jobs WHERE id=%s FOR UPDATE',(job_id,))
job=await cur.fetchone()
if not job or job['state'] in ('ready','failed'):
return
if str(job['attachment_id'])!=payload['attachment_id'] or payload['pipeline_version']!=1:
return
# DB is authoritative for attempts, availability and lease, never the duplicate payload.
cur=await conn.execute("""UPDATE jobs SET state='processing',attempts=attempts+1,
lease_until=clock_timestamp()+interval '90 seconds' WHERE id=%s AND state='queued'
AND available_at<=clock_timestamp() RETURNING *""",(job_id,))
job=await cur.fetchone()
if not job:
return
await conn.execute("UPDATE attachments SET status='processing',updated_at=clock_timestamp() WHERE id=%s",(job['attachment_id'],))
# Claim is committed and visible. Effect transaction locks the job for fencing.
async with store.pool.connection() as conn:
await conn.execute('SELECT id FROM jobs WHERE id=%s FOR UPDATE',(job_id,))
cur=await conn.execute('SELECT * FROM attachments WHERE id=%s',(job['attachment_id'],))
row=await cur.fetchone()
code=None
try:
if job['attempts']>MAX_ATTEMPTS:
code='retry_exhausted'
else:
with tempfile.TemporaryDirectory() as directory:
source=Path(directory)/'source'
await asyncio.to_thread(attachments.s3.download_file,BUCKET,'staging/'+row['id'].hex,str(source))
if source.stat().st_size!=row['size_bytes'] or hashlib.sha256(source.read_bytes()).hexdigest()!=row['sha256']:
code='invalid_image'
else:
child=await asyncio.create_subprocess_exec(sys.executable,'-m','app.transform',str(source),row['content_type'],directory,
stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.DEVNULL)
try:
stdout,_=await asyncio.wait_for(child.communicate(),30)
except BaseException:
child.kill()
await child.wait()
raise
if child.returncode:
code='invalid_image'
else:
variants=json.loads(stdout)
await asyncio.to_thread(attachments.s3.copy_object,Bucket=BUCKET,Key=row['object_key'],
CopySource={'Bucket':BUCKET,'Key':'staging/'+row['id'].hex})
# Test-only one-shot crash marker on the disposable container filesystem.
if Path('/tmp/crash_after_object').exists():
Path('/tmp/crash_after_object').unlink()
os._exit(86)
for variant in variants:
body=(Path(directory)/variant['name']).read_bytes()
variant.update(size_bytes=len(body),sha256=hashlib.sha256(body).hexdigest())
await asyncio.to_thread(attachments.s3.put_object,Bucket=BUCKET,
Key='variants/'+row['id'].hex+'/v1/'+variant['name'],Body=body,ContentType=variant['content_type'])
await conn.execute("UPDATE attachments SET status='ready',variants=%s,error_code=NULL,updated_at=clock_timestamp() WHERE id=%s",(Jsonb(variants),row['id']))
await conn.execute("UPDATE jobs SET state='ready',lease_until=NULL WHERE id=%s",(job_id,))
return
except TimeoutError:
code='processing_timeout'
except Exception:
code='storage_unavailable'
terminal=code=='invalid_image' or job['attempts']>=MAX_ATTEMPTS
if terminal and code!='invalid_image':
code='retry_exhausted'
delay=min(60,2**min(job['attempts'],6))+random.uniform(0,1)
state='failed' if terminal else 'queued'
await conn.execute("UPDATE jobs SET state=%s,available_at=clock_timestamp()+(%s*interval '1 second'),lease_until=NULL,last_published=NULL WHERE id=%s",(state,delay,job_id))
await conn.execute('UPDATE attachments SET status=%s,error_code=%s,updated_at=clock_timestamp() WHERE id=%s',(state,code if terminal else None,row['id']))
async def replay(store, job_id, reason):
if not reason.strip():
raise ValueError('Replay reason required')
async with store.pool.connection() as conn:
cur=await conn.execute('SELECT * FROM jobs WHERE id=%s FOR UPDATE',(UUID(job_id),))
job=await cur.fetchone()
if not job or job['state']!='failed':
raise ValueError('Only failed jobs can be replayed')
cur=await conn.execute('SELECT staging_cleaned FROM attachments WHERE id=%s',(job['attachment_id'],))
if (await cur.fetchone())['staging_cleaned']:
raise ValueError('Replay retention expired')
await conn.execute('INSERT INTO replay_audit(job_id,reason) VALUES (%s,%s)',(job['id'],reason))
await conn.execute("UPDATE jobs SET state='queued',attempts=0,available_at=clock_timestamp(),last_published=NULL WHERE id=%s",(job['id'],))
await conn.execute("UPDATE attachments SET status='queued',error_code=NULL,updated_at=clock_timestamp() WHERE id=%s",(job['attachment_id'],))
async def main(role):
store=Store(Settings.load()); await store.open()
queue=broker(); attachments=Attachments(store)
try:
if role=='replay':
await replay(store,*sys.argv[2:]); return
if role=='worker':
try: await queue.xgroup_create(STREAM,GROUP,id='0',mkstream=True)
except ResponseError as error:
if 'BUSYGROUP' not in str(error): raise
consumer=uuid4().hex
while True:
try:
Path('/tmp/pipeline_alive').touch()
if role=='publisher':
await publish(store,queue,attachments); await asyncio.sleep(.5)
else:
claimed=await queue.xautoclaim(STREAM,GROUP,consumer,5000,'0-0',count=1)
entries=claimed[1]
if not entries:
batches=await queue.xreadgroup(GROUP,consumer,{STREAM:'>'},count=1,block=1000)
entries=batches[0][1] if batches else []
for message_id, fields in entries:
await process(store,attachments,json.loads(fields['payload']))
await queue.xack(STREAM,GROUP,message_id)
await queue.xdel(STREAM,message_id)
except Exception:
print(role+': operation deferred',flush=True)
await asyncio.sleep(1)
finally:
await queue.aclose(); await store.close()
if __name__=='__main__':
asyncio.run(main(sys.argv[1]))
+93
View File
@@ -0,0 +1,93 @@
"""scrypt passwords, strict Basic credentials and persistent signed cursors."""
import base64
from datetime import datetime, timezone
import hashlib
import hmac
import json
import re
import secrets
from uuid import UUID
from .errors import invalid, unauthorized
def password_hash(password, salt=None):
salt = salt or secrets.token_bytes(16)
digest = hashlib.scrypt(password.encode("utf-8"), salt=salt, n=16384,
r=8, p=1, dklen=32, maxmem=64 * 1024 * 1024)
return "scrypt$16384$8$1$" + salt.hex() + "$" + digest.hex()
def password_matches(password, encoded):
try:
algorithm, n, r, p, salt, digest = encoded.split("$")
if (algorithm, n, r, p) != ("scrypt", "16384", "8", "1"):
return False
actual = password_hash(password, bytes.fromhex(salt)).rsplit("$", 1)[1]
return hmac.compare_digest(actual, digest)
except (ValueError, UnicodeError):
return False
def basic_credentials(header):
try:
scheme, encoded = header.split(" ", 1)
if scheme.lower() != "basic" or len(encoded) > 2048:
raise ValueError
value = base64.b64decode(encoded, validate=True).decode("utf-8")
username, password = value.split(":", 1)
if re.fullmatch(r"[a-z0-9_]{3,32}", username) is None:
raise ValueError
if not 12 <= len(password) <= 128:
raise ValueError
return username, password
except (AttributeError, ValueError, UnicodeError):
raise unauthorized(basic=True) from None
def bearer(header):
try:
scheme, token = header.split(" ", 1)
if scheme.lower() != "bearer" or re.fullmatch(r"[A-Za-z0-9_-]{43}", token) is None:
raise ValueError
return token
except (AttributeError, ValueError):
raise unauthorized() from None
def identifier(value):
try:
return UUID(value)
except (ValueError, AttributeError, TypeError):
raise invalid("Invalid UUID") from None
def stamp(value):
return value.astimezone(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z")
class Cursors:
def __init__(self, key):
self.key = key
def encode(self, scope, item):
payload = json.dumps([scope, item["created_at"], item["id"]], separators=(",", ":")).encode()
signature = hmac.digest(self.key, payload, hashlib.sha256)
return base64.urlsafe_b64encode(signature + payload).decode().rstrip("=")
def decode(self, scope, token):
try:
if not token or len(token) > 1024:
raise ValueError
raw = base64.b64decode(token + "=" * (-len(token) % 4), altchars=b"-_", validate=True)
signature, payload = raw[:32], raw[32:]
if not hmac.compare_digest(signature, hmac.digest(self.key, payload, hashlib.sha256)):
raise ValueError
parts = json.loads(payload)
if not isinstance(parts, list) or len(parts) != 3 or parts[0] != scope:
raise ValueError
if not all(isinstance(x, str) for x in parts) or not parts[1].endswith("Z"):
raise ValueError
return datetime.fromisoformat(parts[1].replace("Z", "+00:00")), UUID(parts[2])
except (ValueError, TypeError, UnicodeError):
raise invalid("Invalid cursor for this resource") from None
+238
View File
@@ -0,0 +1,238 @@
"""Persistent business data and durable Redis sessions; no local state cache."""
import asyncio
from datetime import datetime, timezone
import hashlib
import json
import secrets
from uuid import UUID, uuid4
from psycopg.errors import ForeignKeyViolation, UniqueViolation
from psycopg.rows import dict_row
from psycopg_pool import AsyncConnectionPool
import redis.asyncio as redis
from redis.asyncio.retry import Retry
from redis.backoff import NoBackoff
from .errors import APIError, invalid, unauthorized
from .security import Cursors, bearer, password_hash, password_matches, stamp
USER_COLUMNS = "id, username, display_name, created_at"
MESSAGE_COLUMNS = "id, chat_id, sender_id, text, created_at, attachment_ids"
def public(row):
if "attachment_ids" in row:
row["attachment_ids"] = [str(x) for x in row["attachment_ids"]]
return {key: (str(value) if isinstance(value, UUID) else
stamp(value) if isinstance(value, datetime) else value)
for key, value in row.items()}
class Store:
def __init__(self, settings):
self.settings = settings
self.cursors = Cursors(settings.cursor_key)
self.kdf_slots = asyncio.Semaphore(4)
self.dummy_hash = password_hash("dummy-password-for-missing-user", b"0" * 16)
self.pool = AsyncConnectionPool(
settings.database_url, min_size=1, max_size=10, max_waiting=20,
timeout=1, open=False, reconnect_timeout=5,
check=AsyncConnectionPool.check_connection,
kwargs={"row_factory": dict_row, "connect_timeout": 2,
"keepalives": 1, "keepalives_idle": 2, "keepalives_interval": 1,
"keepalives_count": 2, "tcp_user_timeout": 2000,
"options": "-c timezone=UTC -c statement_timeout=2000 -c lock_timeout=1000"})
self.sessions = redis.Redis.from_url(
settings.cache_url, decode_responses=True, max_connections=10,
socket_connect_timeout=1, socket_timeout=1,
retry=Retry(NoBackoff(), 0), retry_on_timeout=False)
async def open(self):
await self.pool.open()
await self.pool.wait(timeout=10)
await self.sessions.ping()
async def close(self):
await self.sessions.aclose()
await self.pool.close()
async def ready(self):
async with self.pool.connection() as conn:
await conn.execute("SELECT 1")
await self.sessions.ping()
async def create_user(self, data):
async with self.kdf_slots:
encoded = await asyncio.to_thread(password_hash, data.password)
try:
async with self.pool.connection() as conn:
cur = await conn.execute(
"INSERT INTO users(id, username, display_name, password_hash) "
"VALUES (%s, %s, %s, %s) RETURNING " + USER_COLUMNS,
(uuid4(), data.username, data.display_name, encoded))
result = public(await cur.fetchone())
return result
except UniqueViolation:
raise APIError(409, "conflict", "Username is already taken") from None
async def login(self, username, password):
async with self.pool.connection() as conn:
cur = await conn.execute("SELECT " + USER_COLUMNS + ", password_hash FROM users WHERE username=%s",
(username,))
row = await cur.fetchone()
async with self.kdf_slots:
valid = await asyncio.to_thread(password_matches, password,
row["password_hash"] if row else self.dummy_hash)
if not valid or row is None:
raise unauthorized(basic=True)
row.pop("password_hash")
token = secrets.token_urlsafe(32)
expires_ms = int(datetime.now(timezone.utc).timestamp() * 1000) + self.settings.session_ttl * 1000
await self.sessions.set(self.session_key(token), json.dumps(
{"user_id": str(row["id"]), "expires_ms": expires_ms}), pxat=expires_ms)
return {"token": token, "token_type": "Bearer",
"expires_at": stamp(datetime.fromtimestamp(expires_ms / 1000, timezone.utc)),
"user": public(row)}
@staticmethod
def session_key(token):
return "session:" + hashlib.sha256(token.encode("ascii")).hexdigest()
async def authenticate(self, header):
token = bearer(header)
value = await self.sessions.get(self.session_key(token))
if value is None:
raise unauthorized()
session = json.loads(value)
if session["expires_ms"] <= int(datetime.now(timezone.utc).timestamp() * 1000):
raise unauthorized()
async with self.pool.connection() as conn:
cur = await conn.execute("SELECT " + USER_COLUMNS + " FROM users WHERE id=%s",
(UUID(session["user_id"]),))
row = await cur.fetchone()
if row is None:
raise unauthorized()
return public(row), token
async def logout(self, token):
await self.sessions.delete(self.session_key(token))
async def create_chat(self, actor, data):
if actor not in data.member_ids:
raise invalid("Members must include the current user")
try:
async with self.pool.connection() as conn:
cur = await conn.execute("INSERT INTO chats(id, title) VALUES (%s, %s) "
"RETURNING id, title, created_at", (uuid4(), data.title))
row = await cur.fetchone()
async with conn.cursor() as cur:
await cur.executemany("INSERT INTO chat_members(chat_id, user_id) VALUES (%s, %s)",
[(row["id"], UUID(member)) for member in data.member_ids])
result = public(row)
result["member_ids"] = sorted(data.member_ids)
return result
except ForeignKeyViolation:
raise invalid("All members must exist") from None
async def accessible_chat(self, conn, actor, chat_id):
cur = await conn.execute("""SELECT c.id, c.title, c.created_at FROM chats c
JOIN chat_members m ON m.chat_id=c.id
WHERE c.id=%s AND m.user_id=%s""", (chat_id, UUID(actor)))
row = await cur.fetchone()
if row is None:
raise APIError(404, "not_found", "Chat not found")
return row
async def get_chat(self, actor, chat_id):
async with self.pool.connection() as conn:
row = await self.accessible_chat(conn, actor, chat_id)
cur = await conn.execute("SELECT user_id FROM chat_members WHERE chat_id=%s ORDER BY user_id", (chat_id,))
result = public(row)
result["member_ids"] = [str(x["user_id"]) for x in await cur.fetchall()]
return result
async def create_message(self, actor, chat_id, data, key):
fingerprint = hashlib.sha256(json.dumps({"text": data.text, "attachment_ids": data.attachment_ids},
ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")).hexdigest()
async with self.pool.connection() as conn:
await self.accessible_chat(conn, actor, chat_id)
# Evaluate clock_timestamp AFTER obtaining the per-chat lock.
await conn.execute("SELECT id FROM chats WHERE id=%s FOR UPDATE", (chat_id,))
# All replicas share this lock. Replay and side effect commit together.
await conn.execute("DELETE FROM message_requests WHERE user_id=%s AND chat_id=%s "
"AND request_key=%s AND expires_at <= clock_timestamp()", (UUID(actor), chat_id, key))
replay = await conn.execute("SELECT request_hash, message_id FROM message_requests "
"WHERE user_id=%s AND chat_id=%s AND request_key=%s", (UUID(actor), chat_id, key))
previous = await replay.fetchone()
if previous:
if previous["request_hash"] != fingerprint:
raise APIError(409, "conflict", "Idempotency key was used with a different message")
saved = await conn.execute("SELECT " + MESSAGE_COLUMNS + " FROM messages WHERE id=%s",
(previous["message_id"],))
return public(await saved.fetchone())
for attachment_id in data.attachment_ids:
found = await conn.execute("SELECT status FROM attachments WHERE id=%s AND chat_id=%s",
(UUID(attachment_id), chat_id))
attachment = await found.fetchone()
if attachment is None:
raise APIError(404, "not_found", "Attachment not found")
if attachment["status"] not in ("ready", "queued", "processing"):
raise APIError(409, "conflict", "Attachment is not ready")
cur = await conn.execute("""UPDATE chats SET last_message_at=
greatest(clock_timestamp(), last_message_at + interval '1 microsecond')
WHERE id=%s RETURNING last_message_at""", (chat_id,))
created_at = (await cur.fetchone())["last_message_at"]
cur = await conn.execute("INSERT INTO messages(id, chat_id, sender_id, text, created_at, attachment_ids) "
"VALUES (%s, %s, %s, %s, %s, %s) RETURNING " + MESSAGE_COLUMNS,
(uuid4(), chat_id, UUID(actor), data.text, created_at, [UUID(x) for x in data.attachment_ids]))
result = public(await cur.fetchone())
await conn.execute("INSERT INTO message_requests "
"(user_id, chat_id, request_key, request_hash, message_id) VALUES (%s,%s,%s,%s,%s)",
(UUID(actor), chat_id, key, fingerprint, UUID(result["id"])))
return result
def page(self, rows, scope, limit):
items = rows[:limit]
return {"items": items, "next_cursor": self.cursors.encode(scope, items[-1])
if len(rows) > limit else None}
async def list_messages(self, actor, chat_id, limit, cursor):
scope = "messages:" + str(chat_id)
boundary = self.cursors.decode(scope, cursor) if cursor is not None else None
async with self.pool.connection() as conn:
await self.accessible_chat(conn, actor, chat_id)
query = "SELECT " + MESSAGE_COLUMNS + " FROM messages WHERE chat_id=%s"
params = [chat_id]
if boundary:
query += " AND (created_at, id) > (%s, %s)"
params.extend(boundary)
query += " ORDER BY created_at, id LIMIT %s"
params.append(limit + 1)
cur = await conn.execute(query, params)
rows = [public(row) for row in await cur.fetchall()]
return self.page(rows, scope, limit)
async def list_chats(self, actor, limit, cursor):
scope = "chats:" + actor
boundary = self.cursors.decode(scope, cursor) if cursor is not None else None
query = """SELECT c.id, c.title, c.created_at FROM chats c
JOIN chat_members m ON m.chat_id=c.id WHERE m.user_id=%s"""
params = [UUID(actor)]
if boundary:
query += " AND (c.created_at, c.id) > (%s, %s)"
params.extend(boundary)
query += " ORDER BY c.created_at, c.id LIMIT %s"
params.append(limit + 1)
async with self.pool.connection() as conn:
cur = await conn.execute(query, params)
rows = [public(row) for row in await cur.fetchall()]
if rows:
ids = [UUID(row["id"]) for row in rows]
cur = await conn.execute("SELECT chat_id, user_id FROM chat_members WHERE chat_id=ANY(%s) ORDER BY user_id",
(ids,))
members = {row["id"]: [] for row in rows}
for member in await cur.fetchall():
members[str(member["chat_id"])].append(str(member["user_id"]))
for row in rows:
row["member_ids"] = members[row["id"]]
return self.page(rows, scope, limit)
+35
View File
@@ -0,0 +1,35 @@
"""Isolated decoder: parent enforces a wall-clock timeout, container bounds RAM."""
import json
from pathlib import Path
import sys
from PIL import Image, ImageOps
from .attachments import validate_image
def transform(source, mime, destination):
with open(source, 'rb') as file:
validate_image(file, mime)
with Image.open(file) as raw:
oriented = ImageOps.exif_transpose(raw).convert('RGBA')
image = Image.new('RGB', oriented.size, 'white')
image.paste(oriented, mask=oriented.getchannel('A'))
variants = []
for name, bound, fmt in [('thumbnail',256,'JPEG'),('crop',128,'JPEG'),('optimized',1280,'WEBP')]:
if name == 'crop':
out = ImageOps.fit(image, (128,128), method=Image.Resampling.LANCZOS, centering=(.5,.5))
else:
w,h = image.size
ratio = min(1, bound/w, bound/h)
out = image.resize((max(1,int(w*ratio)),max(1,int(h*ratio))), Image.Resampling.LANCZOS)
# New RGB image removes EXIF, ICC and text metadata.
clean = Image.new('RGB', out.size)
clean.paste(out)
clean.save(Path(destination)/name, format=fmt, quality=85 if fmt=='JPEG' else 80)
variants.append({'name':name,'width':out.width,'height':out.height,
'content_type':'image/jpeg' if fmt=='JPEG' else 'image/webp'})
return variants
if __name__ == '__main__':
try:
print(json.dumps(transform(*sys.argv[1:])))
except Exception:
sys.exit(2)