Implement durable image processing pipeline with outbox and recovery

This commit is contained in:
Polusikkkk
2026-11-17 18:48:50 +03:00
parent 276dbdad8a
commit be223efc8b
84 changed files with 8982 additions and 18 deletions
View File
+108
View File
@@ -0,0 +1,108 @@
from __future__ import annotations
import base64
import binascii
import hashlib
import re
import secrets
from argon2 import PasswordHasher, Type
from argon2.exceptions import VerificationError
from starlette.concurrency import run_in_threadpool
USERNAME_RE = re.compile(r"[a-z0-9_]{3,32}", re.ASCII)
password_hasher = PasswordHasher(
time_cost=3,
memory_cost=65536,
parallelism=4,
hash_len=32,
salt_len=16,
type=Type.ID,
)
DUMMY_PASSWORD_HASH = password_hasher.hash(
secrets.token_urlsafe(32)
)
async def hash_password(password: str) -> str:
return await run_in_threadpool(
password_hasher.hash,
password,
)
async def verify_password(
password_hash: str,
password: str,
) -> bool:
try:
return await run_in_threadpool(
password_hasher.verify,
password_hash,
password,
)
except VerificationError:
return False
def parse_basic_credentials(
authorization: str | None,
) -> tuple[str, str] | None:
if authorization is None or len(authorization) > 2048:
return None
parts = authorization.split()
if len(parts) != 2 or parts[0].lower() != "basic":
return None
try:
decoded = base64.b64decode(
parts[1],
validate=True,
).decode("utf-8")
except (binascii.Error, UnicodeError, ValueError):
return None
username, separator, password = decoded.partition(":")
if not separator:
return None
if USERNAME_RE.fullmatch(username) is None:
return None
if not 12 <= len(password) <= 128:
return None
return username, password
def parse_bearer_token(
authorization: str | None,
) -> str | None:
if authorization is None or len(authorization) > 2048:
return None
parts = authorization.split()
if len(parts) != 2 or parts[0].lower() != "bearer":
return None
token = parts[1]
if re.fullmatch(r"[A-Za-z0-9_-]{43}", token) is None:
return None
return token
def generate_token() -> str:
return secrets.token_urlsafe(32)
def hash_token(token: str) -> str:
return hashlib.sha256(token.encode("ascii")).hexdigest()
+36
View File
@@ -0,0 +1,36 @@
from __future__ import annotations
import os
from pathlib import Path
import pika
QUEUE_NAME = "attachment.process.v1"
def connect_broker():
url = Path(os.environ["BROKER_URL_FILE"]).read_text().strip()
if not url:
raise ValueError("Empty broker URL file")
parameters = pika.URLParameters(url)
parameters.heartbeat = 15
parameters.blocked_connection_timeout = 5
parameters.socket_timeout = 5
parameters.stack_timeout = 10
parameters.connection_attempts = 1
connection = pika.BlockingConnection(parameters)
try:
channel = connection.channel()
channel.queue_declare(
queue=QUEUE_NAME,
durable=True,
exclusive=False,
auto_delete=False,
)
return connection, channel
except Exception:
connection.close()
raise
+129
View File
@@ -0,0 +1,129 @@
from __future__ import annotations
import json
import logging
import os
from datetime import datetime, timezone
from uuid import UUID
from redis.asyncio import Redis
from redis.exceptions import RedisError
from app.store import store
logger = logging.getLogger("messenger.cache")
CACHE_TTL_SECONDS = int(
os.getenv("USER_CACHE_TTL_SECONDS", "60")
)
if not 1 <= CACHE_TTL_SECONDS <= 3600:
raise ValueError(
"USER_CACHE_TTL_SECONDS must be between 1 and 3600"
)
redis_client = Redis(
host=os.getenv("REDIS_HOST", "redis"),
port=int(os.getenv("REDIS_PORT", "6379")),
decode_responses=True,
socket_connect_timeout=0.2,
socket_timeout=0.2,
retry_on_timeout=False,
max_connections=10,
)
def serialize_user(user: dict) -> str:
created_at = user["created_at"]
return json.dumps(
{
"id": str(user["id"]),
"username": user["username"],
"display_name": user["display_name"],
"created_at": created_at.astimezone(
timezone.utc
).isoformat().replace("+00:00", "Z"),
},
ensure_ascii=False,
separators=(",", ":"),
)
def deserialize_user(
raw: str,
expected_id: UUID,
) -> dict:
data = json.loads(raw)
if not isinstance(data, dict):
raise ValueError("Invalid cached user")
expected_fields = {
"id",
"username",
"display_name",
"created_at",
}
if set(data) != expected_fields:
raise ValueError("Invalid cached user fields")
if not all(isinstance(value, str) for value in data.values()):
raise ValueError("Invalid cached user types")
user_id = UUID(data["id"])
if user_id != expected_id:
raise ValueError("Cached user ID mismatch")
created_at = datetime.fromisoformat(
data["created_at"].replace("Z", "+00:00")
)
if created_at.tzinfo is None:
raise ValueError("Cached timestamp has no timezone")
return {
"id": user_id,
"username": data["username"],
"display_name": data["display_name"],
"created_at": created_at,
}
async def get_cached_user(user_id: UUID) -> dict | None:
key = f"user:v1:{user_id}"
try:
raw = await redis_client.get(key)
if raw is not None:
return deserialize_user(raw, user_id)
except RedisError:
logger.warning("User cache read unavailable")
except (ValueError, TypeError, OverflowError):
logger.warning("Invalid user cache entry ignored")
user = await store.get_user(user_id)
if user is None:
return None
try:
await redis_client.set(
key,
serialize_user(user),
ex=CACHE_TTL_SECONDS,
)
except RedisError:
logger.warning("User cache write unavailable")
return user
async def close_cache() -> None:
await redis_client.aclose()
+208
View File
@@ -0,0 +1,208 @@
from __future__ import annotations
import argparse
from collections import Counter
from datetime import datetime, timedelta, timezone
import json
import os
import sys
import time
from uuid import UUID
import psycopg
from psycopg.rows import dict_row
from botocore.exceptions import ClientError
from app.object_locks import object_lock_id
from app.storage import bucket_name, get_client
def managed_key(key: str) -> bool:
prefix = "originals/"
if not key.startswith(prefix):
return False
suffix = key[len(prefix):]
try:
return str(UUID(suffix)) == suffix
except ValueError:
return False
def database_connection():
return psycopg.connect(
host=os.getenv("PGHOST", "postgres"),
port=int(os.getenv("PGPORT", "5432")),
dbname=os.getenv("PGDATABASE", "messenger"),
user=os.getenv("PGUSER", "messenger"),
password=os.environ["PGPASSWORD"],
connect_timeout=3,
options=(
"-c statement_timeout=3000 "
"-c lock_timeout=2000 "
"-c idle_in_transaction_session_timeout=10000"
),
autocommit=True,
row_factory=dict_row,
)
def sweep(*, apply: bool, grace_seconds: int) -> dict:
cutoff = datetime.now(timezone.utc) - timedelta(
seconds=grace_seconds
)
counts = Counter({
"scanned": 0,
"kept": 0,
"fresh": 0,
"busy": 0,
"ignored": 0,
"gone": 0,
"candidates": 0,
"deleted": 0,
})
with database_connection() as conn:
client = get_client()
bucket = bucket_name()
pages = client.get_paginator("list_objects_v2")
for page in pages.paginate(
Bucket=bucket,
Prefix="originals/",
PaginationConfig={"PageSize": 200},
):
for item in page.get("Contents", []):
counts["scanned"] += 1
key = item["Key"]
if not managed_key(key):
counts["ignored"] += 1
continue
if item["LastModified"] >= cutoff:
counts["fresh"] += 1
continue
with conn.transaction():
conn.execute(
"SET LOCAL "
"idle_in_transaction_session_timeout = '60s'"
)
locked = conn.execute(
"SELECT pg_try_advisory_xact_lock(%s) AS locked",
(object_lock_id(bucket, key),),
).fetchone()["locked"]
if not locked:
counts["busy"] += 1
continue
metadata = conn.execute(
"""
SELECT 1
FROM attachments
WHERE object_key = %s
""",
(key,),
).fetchone()
if metadata is not None:
counts["kept"] += 1
continue
try:
current = client.head_object(
Bucket=bucket,
Key=key,
)
except ClientError as exc:
status = exc.response.get(
"ResponseMetadata", {}
).get("HTTPStatusCode")
if status == 404:
counts["gone"] += 1
continue
raise
if current["LastModified"] >= cutoff:
counts["fresh"] += 1
continue
counts["candidates"] += 1
print(
json.dumps({
"action": "delete" if apply else "would_delete",
"key": key,
}),
flush=True,
)
if apply:
client.delete_object(
Bucket=bucket,
Key=key,
)
counts["deleted"] += 1
return {
"mode": "apply" if apply else "dry-run",
"grace_seconds": grace_seconds,
**dict(counts),
}
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--apply", action="store_true")
parser.add_argument("--grace-seconds", type=int, default=86400)
parser.add_argument("--allow-short-grace", action="store_true")
parser.add_argument("--interval-seconds", type=int, default=0)
args = parser.parse_args()
if args.grace_seconds < 60:
parser.error("grace must be at least 60 seconds")
if args.grace_seconds < 3600 and not args.allow_short_grace:
parser.error(
"short test grace requires --allow-short-grace"
)
if args.interval_seconds != 0 and args.interval_seconds < 60:
parser.error("interval must be zero or at least 60 seconds")
if args.grace_seconds < 3600:
print(
"WARNING: short grace is for controlled local tests",
file=sys.stderr,
flush=True,
)
while True:
try:
result = sweep(
apply=args.apply,
grace_seconds=args.grace_seconds,
)
except Exception as exc:
print(
json.dumps({
"status": "failed",
"error_type": type(exc).__name__,
}),
file=sys.stderr,
flush=True,
)
return 1
print(json.dumps(result, sort_keys=True), flush=True)
if args.interval_seconds == 0:
return 0
time.sleep(args.interval_seconds)
if __name__ == "__main__":
raise SystemExit(main())
+198
View File
@@ -0,0 +1,198 @@
from __future__ import annotations
import argparse
from collections import Counter
from datetime import datetime, timedelta, timezone
import json
import os
import re
import time
from uuid import UUID
from botocore.exceptions import ClientError
from app.job_db import connect_db
from app.object_locks import object_lock_id
from app.storage import bucket_name, get_client
KEY_PATTERN = re.compile(
r"staging/([0-9a-f-]{36})/v([1-9][0-9]*)"
)
def managed_key(key):
match = KEY_PATTERN.fullmatch(key)
if match is None:
return False
try:
return str(UUID(match.group(1))) == match.group(1)
except ValueError:
return False
def sweep(*, apply, grace_seconds, attachment_id=None):
cutoff = datetime.now(timezone.utc) - timedelta(seconds=grace_seconds)
counts = Counter({
"scanned": 0,
"ignored": 0,
"fresh": 0,
"busy": 0,
"active": 0,
"gone": 0,
"candidates": 0,
"deleted": 0,
})
bucket = bucket_name()
client = get_client()
prefix = (
f"staging/{attachment_id}/"
if attachment_id is not None
else "staging/"
)
with connect_db() as db:
for page in client.get_paginator("list_objects_v2").paginate(
Bucket=bucket,
Prefix=prefix,
PaginationConfig={"PageSize": 200},
):
for item in page.get("Contents", []):
counts["scanned"] += 1
key = item["Key"]
if not managed_key(key):
counts["ignored"] += 1
continue
if item["LastModified"] >= cutoff:
counts["fresh"] += 1
continue
with db.transaction():
db.execute(
"SET LOCAL idle_in_transaction_session_timeout = '60s'"
)
locked = db.execute(
"SELECT pg_try_advisory_xact_lock(%s) AS locked",
(object_lock_id(bucket, key),),
).fetchone()["locked"]
if not locked:
counts["busy"] += 1
continue
row = db.execute(
"""
SELECT id, status, updated_at
FROM attachments
WHERE staging_key = %s
FOR UPDATE
""",
(key,),
).fetchone()
if row is not None:
if row["status"] in ("queued", "processing"):
counts["active"] += 1
continue
if row["status"] == "failed" and row["updated_at"] >= cutoff:
counts["fresh"] += 1
continue
try:
current = client.head_object(Bucket=bucket, Key=key)
except ClientError as exc:
status = exc.response.get(
"ResponseMetadata", {}
).get("HTTPStatusCode")
if status == 404:
counts["gone"] += 1
continue
raise
if current["LastModified"] >= cutoff:
counts["fresh"] += 1
continue
counts["candidates"] += 1
if apply:
client.delete_object(Bucket=bucket, Key=key)
if row is not None:
db.execute(
"""
UPDATE attachments
SET staging_key = NULL
WHERE id = %s
AND staging_key = %s
AND status IN ('ready', 'failed')
""",
(row["id"], key),
)
counts["deleted"] += 1
return {
"mode": "apply" if apply else "dry-run",
"grace_seconds": grace_seconds,
"attachment_id": (
str(attachment_id) if attachment_id is not None else None
),
**dict(counts),
}
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--apply", action="store_true")
parser.add_argument(
"--grace-seconds",
type=int,
default=int(os.getenv("STAGING_RETENTION_SECONDS", "86400")),
)
parser.add_argument("--attachment-id", type=UUID)
parser.add_argument("--allow-short-grace", action="store_true")
parser.add_argument("--interval-seconds", type=int, default=0)
args = parser.parse_args()
if args.grace_seconds < 0:
parser.error("grace must not be negative")
if args.grace_seconds < 3600 and (
not args.allow_short_grace or args.attachment_id is None
):
parser.error(
"short grace requires --allow-short-grace "
"and a specific --attachment-id"
)
if args.interval_seconds != 0 and args.interval_seconds < 60:
parser.error("interval must be zero or at least 60 seconds")
while True:
try:
result = sweep(
apply=args.apply,
grace_seconds=args.grace_seconds,
attachment_id=args.attachment_id,
)
except Exception as exc:
print(json.dumps({
"result": "error",
"error_type": type(exc).__name__,
}), flush=True)
raise SystemExit(1)
print(json.dumps(result), flush=True)
if args.interval_seconds == 0:
return
time.sleep(args.interval_seconds)
if __name__ == "__main__":
main()
+12
View File
@@ -0,0 +1,12 @@
from __future__ import annotations
import os
SESSION_TTL_SECONDS = int(
os.getenv("SESSION_TTL_SECONDS", "3600")
)
if SESSION_TTL_SECONDS < 1:
raise ValueError("SESSION_TTL_SECONDS must be positive")
+76
View File
@@ -0,0 +1,76 @@
from __future__ import annotations
import asyncio
import os
from psycopg import AsyncConnection, OperationalError, waiting
from psycopg.rows import dict_row
from psycopg_pool import AsyncConnectionPool
DB_IO_TIMEOUT_SECONDS = float(
os.getenv("DB_IO_TIMEOUT_SECONDS", "3")
)
if DB_IO_TIMEOUT_SECONDS <= 0:
raise ValueError("DB_IO_TIMEOUT_SECONDS must be positive")
class DeadlineConnection(AsyncConnection):
async def wait(self, gen, interval=0.1):
try:
async with asyncio.timeout(DB_IO_TIMEOUT_SECONDS):
return await waiting.wait_async(
gen,
self.pgconn.socket,
interval=interval,
)
except TimeoutError:
await self.close()
raise OperationalError(
"PostgreSQL response deadline exceeded"
) from None
except asyncio.CancelledError:
await self.close()
raise
pool = AsyncConnectionPool(
conninfo="",
connection_class=DeadlineConnection,
kwargs={
"host": os.getenv("PGHOST", "postgres"),
"port": int(os.getenv("PGPORT", "5432")),
"dbname": os.getenv("PGDATABASE", "messenger"),
"user": os.getenv("PGUSER", "messenger"),
"password": os.environ.get("PGPASSWORD", ""),
"connect_timeout": 3,
"options": (
"-c statement_timeout=3000 "
"-c lock_timeout=2000 "
"-c idle_in_transaction_session_timeout=10000"
),
"row_factory": dict_row,
},
min_size=1,
max_size=5,
timeout=3,
max_waiting=20,
open=False,
check=AsyncConnectionPool.check_connection,
)
async def open_db() -> None:
await pool.open(wait=True, timeout=10)
async def close_db() -> None:
await pool.close()
async def check_db() -> None:
async with pool.connection() as conn:
await conn.execute("SELECT 1")
+48
View File
@@ -0,0 +1,48 @@
from __future__ import annotations
from uuid import UUID
from fastapi import Request
from app.auth import hash_token, parse_bearer_token
from app.cache import get_cached_user
from app.errors import not_found, unauthorized
from app.store import store
from app.validation import parse_uuid
async def current_user(request: Request) -> tuple[dict, str]:
token = parse_bearer_token(
request.headers.get("authorization")
)
if token is None:
raise unauthorized()
token_digest = hash_token(token)
user_id = await store.get_session_user_id(token_digest)
if user_id is None:
raise unauthorized()
user = await get_cached_user(user_id)
if user is None:
raise unauthorized()
return user, token_digest
async def accessible_chat(
raw_chat_id: str,
user_id: UUID,
) -> tuple[UUID, dict]:
chat_id = parse_uuid(raw_chat_id)
chat = await store.get_accessible_chat(chat_id, user_id)
if chat is None:
raise not_found()
return chat_id, chat
+71
View File
@@ -0,0 +1,71 @@
from __future__ import annotations
from uuid import uuid4
from fastapi import Request
from fastapi.responses import JSONResponse
class ApiError(Exception):
def __init__(
self,
status: int,
code: str,
message: str,
challenge: str | None = None,
):
super().__init__(message)
self.status = status
self.code = code
self.message = message
self.challenge = challenge
def invalid(message: str = "Некорректный запрос") -> ApiError:
return ApiError(400, "invalid_request", message)
def unauthorized(scheme: str = "Bearer") -> ApiError:
if scheme == "Basic":
challenge = 'Basic realm="messenger", charset="UTF-8"'
else:
challenge = 'Bearer realm="messenger"'
return ApiError(
401,
"unauthorized",
"Недействительная аутентификация",
challenge,
)
def not_found() -> ApiError:
return ApiError(404, "not_found", "Объект не найден")
def error_response(
request: Request,
error: ApiError,
) -> JSONResponse:
request_id = getattr(
request.state,
"request_id",
str(uuid4()),
)
headers = {"X-Request-Id": request_id}
if error.challenge is not None:
headers["WWW-Authenticate"] = error.challenge
return JSONResponse(
status_code=error.status,
content={
"error": {
"code": error.code,
"message": error.message,
"request_id": request_id,
}
},
headers=headers,
)
+34
View File
@@ -0,0 +1,34 @@
from __future__ import annotations
import logging
import os
from app.job_db import connect_db
logger = logging.getLogger("messenger.faults")
def trip_fault(job_id, stage: str) -> None:
with connect_db() as db:
row = db.execute(
"""
UPDATE pipeline_fault_injections
SET consumed_at = clock_timestamp()
WHERE job_id = %s
AND stage = %s
AND consumed_at IS NULL
RETURNING job_id
""",
(job_id, stage),
).fetchone()
if row is None:
return
logger.warning(
"fault_injection job_id=%s stage=%s exit_code=75",
job_id,
stage,
)
os._exit(75)
+180
View File
@@ -0,0 +1,180 @@
from __future__ import annotations
import hashlib
import json
from uuid import UUID, uuid4
from app.db import pool
from app.errors import ApiError, invalid, not_found
async def create_message_once(
chat_id: UUID,
sender_id: UUID,
text: str,
key: str,
attachment_ids: list[UUID] | None = None,
) -> dict:
attachment_ids = list(
attachment_ids if attachment_ids is not None else []
)
if (
len(attachment_ids) > 10
or len(set(attachment_ids)) != len(attachment_ids)
):
raise invalid("Некорректный список вложений")
if not isinstance(text, str) or len(text) > 4000:
raise invalid("Некорректный текст сообщения")
if not text.strip() and not attachment_ids:
raise invalid("Сообщение должно содержать текст или вложение")
scope = json.dumps(
[
str(sender_id),
"POST",
f"/api/v1/chats/{chat_id}/messages",
key,
],
separators=(",", ":"),
)
lock_id = int.from_bytes(
hashlib.sha256(scope.encode("utf-8")).digest()[:8],
byteorder="big",
signed=True,
)
async with pool.connection() as conn:
await conn.execute(
"SELECT pg_advisory_xact_lock(%s)",
(lock_id,),
)
cursor = await conn.execute(
"""
SELECT i.request_text,
i.request_attachment_ids,
m.id, m.chat_id, m.sender_id,
m.text, m.created_at,
ARRAY(
SELECT ma.attachment_id
FROM message_attachments AS ma
WHERE ma.message_id = m.id
ORDER BY ma.position
) AS attachment_ids
FROM message_idempotency AS i
JOIN messages AS m ON m.id = i.message_id
WHERE i.user_id = %s
AND i.chat_id = %s
AND i.http_method = 'POST'
AND i.idempotency_key = %s
""",
(sender_id, chat_id, key),
)
previous = await cursor.fetchone()
if previous is not None:
if (
previous["request_text"] != text
or previous["request_attachment_ids"] != attachment_ids
):
raise ApiError(
409,
"conflict",
"Ключ уже использован с другим сообщением",
)
message = {
field: previous[field]
for field in (
"id",
"chat_id",
"sender_id",
"text",
"created_at",
"attachment_ids",
)
}
else:
if attachment_ids:
cursor = await conn.execute(
"""
SELECT id, status
FROM attachments
WHERE id = ANY(%s::uuid[])
AND chat_id = %s
ORDER BY id
FOR SHARE
""",
(attachment_ids, chat_id),
)
available = await cursor.fetchall()
if len(available) != len(attachment_ids):
raise not_found()
if any(row["status"] == "failed" for row in available):
raise ApiError(
409,
"conflict",
"Нельзя прикрепить вложение с ошибкой обработки",
)
cursor = await conn.execute(
"""
INSERT INTO messages (
id, chat_id, sender_id, text
)
VALUES (%s, %s, %s, %s)
RETURNING id, chat_id, sender_id,
text, created_at
""",
(uuid4(), chat_id, sender_id, text),
)
message = await cursor.fetchone()
if attachment_ids:
async with conn.cursor() as cursor:
await cursor.executemany(
"""
INSERT INTO message_attachments (
message_id, attachment_id, position
)
VALUES (%s, %s, %s)
""",
[
(message["id"], attachment_id, position)
for position, attachment_id
in enumerate(attachment_ids)
],
)
await conn.execute(
"""
INSERT INTO message_idempotency (
user_id,
chat_id,
http_method,
idempotency_key,
request_text,
request_attachment_ids,
message_id
)
VALUES (%s, %s, 'POST', %s, %s, %s::uuid[], %s)
""",
(
sender_id,
chat_id,
key,
text,
attachment_ids,
message["id"],
),
)
message["attachment_ids"] = attachment_ids
return message
+133
View File
@@ -0,0 +1,133 @@
from __future__ import annotations
import hashlib
import io
import warnings
from PIL import Image, ImageOps, UnidentifiedImageError
MAX_BYTES = 10_485_760
MAX_PIXELS = 40_000_000
JPEG_QUALITY = 85
WEBP_QUALITY = 82
class InvalidImage(ValueError):
pass
def fitted_size(width: int, height: int, limit: int) -> tuple[int, int]:
longest = max(width, height)
if longest <= limit:
return width, height
return (
max(1, width * limit // longest),
max(1, height * limit // longest),
)
def encode_variant(name: str, image: Image.Image, fmt: str) -> dict:
image.info.clear()
output = io.BytesIO()
if fmt == "JPEG":
image.save(
output,
format="JPEG",
quality=JPEG_QUALITY,
optimize=True,
exif=b"",
icc_profile=None,
)
content_type = "image/jpeg"
else:
image.save(
output,
format="WEBP",
quality=WEBP_QUALITY,
method=4,
exif=b"",
icc_profile=b"",
xmp=b"",
)
content_type = "image/webp"
data = output.getvalue()
return {
"name": name,
"content_type": content_type,
"size_bytes": len(data),
"width": image.width,
"height": image.height,
"sha256": hashlib.sha256(data).hexdigest(),
"data": data,
}
def render_variants(data: bytes) -> list[dict]:
if not 1 <= len(data) <= MAX_BYTES:
raise InvalidImage("invalid_size")
try:
with warnings.catch_warnings():
warnings.simplefilter("error", Image.DecompressionBombWarning)
with Image.open(io.BytesIO(data)) as source:
if source.format not in ("PNG", "JPEG"):
raise InvalidImage("invalid_format")
width, height = source.size
if width < 1 or height < 1 or width * height > MAX_PIXELS:
raise InvalidImage("invalid_dimensions")
source.verify()
with Image.open(io.BytesIO(data)) as source:
oriented = ImageOps.exif_transpose(source)
try:
rgba = oriented.convert("RGBA")
try:
rgb = Image.new("RGB", rgba.size, "white")
alpha = rgba.getchannel("A")
try:
rgb.paste(rgba, mask=alpha)
finally:
alpha.close()
finally:
rgba.close()
finally:
oriented.close()
try:
variants = []
size = fitted_size(rgb.width, rgb.height, 256)
with rgb.resize(size, Image.Resampling.LANCZOS) as thumb:
variants.append(encode_variant("thumbnail", thumb, "JPEG"))
with ImageOps.fit(
rgb,
(128, 128),
method=Image.Resampling.LANCZOS,
centering=(0.5, 0.5),
) as crop:
variants.append(encode_variant("crop", crop, "JPEG"))
size = fitted_size(rgb.width, rgb.height, 1280)
with rgb.resize(size, Image.Resampling.LANCZOS) as optimized:
variants.append(encode_variant("optimized", optimized, "WEBP"))
return variants
finally:
rgb.close()
except (
UnidentifiedImageError,
Image.DecompressionBombError,
Image.DecompressionBombWarning,
OSError,
SyntaxError,
ValueError,
) as exc:
if isinstance(exc, InvalidImage):
raise
raise InvalidImage("invalid_image") from None
+95
View File
@@ -0,0 +1,95 @@
from __future__ import annotations
import io
import unicodedata
from PIL import Image, UnidentifiedImageError
from app.errors import ApiError, invalid
MAX_BYTES = 10 * 1024 * 1024
MAX_PIXELS = 40_000_000
FORMAT_TO_MIME = {
"PNG": "image/png",
"JPEG": "image/jpeg",
}
def validate_filename(value: str | None) -> str:
if (
value is None
or not 1 <= len(value) <= 255
or not value.strip()
):
raise invalid("Некорректное имя файла")
for char in value:
if char in "/\\" or unicodedata.category(char) == "Cc":
raise invalid("Некорректное имя файла")
return value
def inspect_image(data: bytes, declared_type: str) -> str:
if len(data) > MAX_BYTES:
raise ApiError(
413,
"payload_too_large",
"Файл превышает 10 MiB",
)
if declared_type not in FORMAT_TO_MIME.values():
raise ApiError(
415,
"unsupported_media_type",
"Допустимы только image/png и image/jpeg",
)
try:
with Image.open(io.BytesIO(data)) as image:
detected = FORMAT_TO_MIME.get(image.format or "")
width, height = image.size
pixels = width * height
except Image.DecompressionBombError:
raise ApiError(
413,
"payload_too_large",
"Слишком много пикселей",
) from None
except (UnidentifiedImageError, OSError, SyntaxError, ValueError):
raise ApiError(
415,
"unsupported_media_type",
"Файл не является корректным PNG/JPEG",
) from None
if detected is None or detected != declared_type:
raise ApiError(
415,
"unsupported_media_type",
"Содержимое не соответствует Content-Type",
)
if width < 1 or height < 1 or pixels > MAX_PIXELS:
raise ApiError(
413,
"payload_too_large",
"Слишком много пикселей",
)
try:
with Image.open(io.BytesIO(data)) as image:
image.verify()
with Image.open(io.BytesIO(data)) as image:
image.load()
except (Image.DecompressionBombError, OSError, SyntaxError, ValueError):
raise ApiError(
415,
"unsupported_media_type",
"Файл повреждён",
) from None
return detected
+7
View File
@@ -0,0 +1,7 @@
from __future__ import annotations
import socket
from uuid import uuid4
INSTANCE_ID = f"{socket.gethostname()}:{uuid4().hex[:12]}"
+24
View File
@@ -0,0 +1,24 @@
from __future__ import annotations
import os
import psycopg
from psycopg.rows import dict_row
def connect_db():
return psycopg.connect(
host=os.getenv("PGHOST", "postgres"),
port=int(os.getenv("PGPORT", "5432")),
dbname=os.getenv("PGDATABASE", "messenger"),
user=os.getenv("PGUSER", "messenger"),
password=os.environ["PGPASSWORD"],
connect_timeout=3,
autocommit=True,
row_factory=dict_row,
options=(
"-c statement_timeout=3000 "
"-c lock_timeout=2000 "
"-c idle_in_transaction_session_timeout=60000"
),
)
+194
View File
@@ -0,0 +1,194 @@
from __future__ import annotations
import hashlib
import json
import os
import resource
import sys
from uuid import UUID
def execute(job_id: UUID, lease_token: UUID) -> str:
from app.image_pipeline import InvalidImage, render_variants
from app.faults import trip_fault
from app.job_db import connect_db
from app.storage import _get, _put, bucket_name, get_client
with connect_db() as db:
row = db.execute(
"""
SELECT j.attachment_id, j.pipeline_version,
a.staging_key, a.object_key,
a.content_type, a.size_bytes, a.sha256
FROM attachment_jobs AS j
JOIN attachments AS a ON a.id = j.attachment_id
WHERE j.id = %s
AND j.status = 'processing'
AND j.lease_token = %s
AND j.lease_until > clock_timestamp()
AND a.pipeline_version = j.pipeline_version
AND a.status = 'processing'
""",
(job_id, lease_token),
).fetchone()
if row is None:
return "stale"
data = _get(row["staging_key"])
if (
len(data) != row["size_bytes"]
or hashlib.sha256(data).hexdigest() != row["sha256"]
):
raise InvalidImage("original_integrity_error")
variants = render_variants(data)
_put(row["object_key"], data, row["content_type"])
for variant in variants:
variant["object_key"] = (
f"variants/{row['attachment_id']}/"
f"v{row['pipeline_version']}/{variant['name']}"
)
_put(
variant["object_key"],
variant["data"],
variant["content_type"],
)
trip_fault(job_id, "after_objects")
with connect_db() as db:
with db.transaction():
job = db.execute(
"""
SELECT id
FROM attachment_jobs
WHERE id = %s
AND status = 'processing'
AND lease_token = %s
AND lease_until > clock_timestamp()
FOR UPDATE
""",
(job_id, lease_token),
).fetchone()
if job is None:
return "stale"
attachment = db.execute(
"""
SELECT id
FROM attachments
WHERE id = %s
AND pipeline_version = %s
AND status = 'processing'
FOR UPDATE
""",
(row["attachment_id"], row["pipeline_version"]),
).fetchone()
if attachment is None:
return "stale"
for variant in variants:
db.execute(
"""
INSERT INTO attachment_variants (
attachment_id, pipeline_version,
name, object_key, content_type,
size_bytes, width, height, sha256
)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
ON CONFLICT (attachment_id, pipeline_version, name)
DO UPDATE SET
object_key = EXCLUDED.object_key,
content_type = EXCLUDED.content_type,
size_bytes = EXCLUDED.size_bytes,
width = EXCLUDED.width,
height = EXCLUDED.height,
sha256 = EXCLUDED.sha256
""",
(
row["attachment_id"], row["pipeline_version"],
variant["name"], variant["object_key"],
variant["content_type"], variant["size_bytes"],
variant["width"], variant["height"],
variant["sha256"],
),
)
db.execute(
"""
UPDATE attachments
SET status = 'ready',
error_code = NULL,
updated_at = clock_timestamp()
WHERE id = %s
""",
(row["attachment_id"],),
)
db.execute(
"""
UPDATE attachment_jobs
SET status = 'ready',
lease_token = NULL,
lease_until = NULL,
error_code = NULL,
updated_at = clock_timestamp()
WHERE id = %s
""",
(job_id,),
)
# Результат уже зафиксирован. Ошибка очистки не отменяет ready.
try:
get_client().delete_object(
Bucket=bucket_name(),
Key=row["staging_key"],
)
with connect_db() as db:
db.execute(
"""
UPDATE attachments
SET staging_key = NULL
WHERE id = %s
AND staging_key = %s
AND status = 'ready'
""",
(row["attachment_id"], row["staging_key"]),
)
except Exception:
pass
return "ready"
def main():
memory_bytes = int(os.getenv("JOB_MEMORY_MB", "512")) * 1024 * 1024
cpu_seconds = int(os.getenv("JOB_TIMEOUT_SECONDS", "60"))
resource.setrlimit(resource.RLIMIT_AS, (memory_bytes, memory_bytes))
resource.setrlimit(
resource.RLIMIT_CPU,
(cpu_seconds, cpu_seconds + 1),
)
from app.image_pipeline import InvalidImage
try:
outcome = execute(UUID(sys.argv[1]), UUID(sys.argv[2]))
result = {"outcome": outcome}
except InvalidImage:
result = {"outcome": "failed", "error_code": "invalid_image"}
except MemoryError:
result = {"outcome": "failed", "error_code": "resource_limit"}
except Exception:
result = {"outcome": "retry", "error_code": "processing_failed"}
print(json.dumps(result), flush=True)
if __name__ == "__main__":
main()
+90
View File
@@ -0,0 +1,90 @@
from __future__ import annotations
import hashlib
import os
from uuid import UUID, uuid4
from app.db import pool
from app.object_locks import object_lock_id
from app.storage import bucket_name, put_object
PIPELINE_VERSION = 1
JOB_MAX_ATTEMPTS = int(os.getenv("JOB_MAX_ATTEMPTS", "5"))
if not 1 <= JOB_MAX_ATTEMPTS <= 100:
raise ValueError("JOB_MAX_ATTEMPTS must be between 1 and 100")
async def accept_upload(
*,
chat_id: UUID,
owner_id: UUID,
filename: str,
content_type: str,
data: bytes,
) -> dict:
attachment_id = uuid4()
job_id = uuid4()
staging_key = f"staging/{attachment_id}/v{PIPELINE_VERSION}"
original_key = f"originals/{attachment_id}"
digest = hashlib.sha256(data).hexdigest()
async with pool.connection() as conn:
await conn.execute(
"SET LOCAL idle_in_transaction_session_timeout = '60s'"
)
await conn.execute(
"SELECT pg_advisory_xact_lock(%s)",
(object_lock_id(bucket_name(), staging_key),),
)
await put_object(staging_key, data, content_type)
cursor = await conn.execute(
"""
INSERT INTO attachments (
id, chat_id, owner_id, filename,
content_type, size_bytes, sha256,
object_key, staging_key, pipeline_version, status
)
VALUES (
%s, %s, %s, %s,
%s, %s, %s,
%s, %s, %s, 'queued'
)
RETURNING id, chat_id, owner_id, filename,
content_type, size_bytes, sha256,
status, error_code, created_at, updated_at
""",
(
attachment_id, chat_id, owner_id, filename,
content_type, len(data), digest,
original_key, staging_key, PIPELINE_VERSION,
),
)
row = await cursor.fetchone()
await conn.execute(
"""
INSERT INTO attachment_jobs (
id, attachment_id, pipeline_version, max_attempts
)
VALUES (%s, %s, %s, %s)
""",
(
job_id, attachment_id,
PIPELINE_VERSION, JOB_MAX_ATTEMPTS,
),
)
await conn.execute(
"""
INSERT INTO attachment_outbox (id, job_id, attempt)
VALUES (%s, %s, 1)
""",
(uuid4(), job_id),
)
row["variants"] = []
return row
+116
View File
@@ -0,0 +1,116 @@
from __future__ import annotations
import logging
from contextlib import asynccontextmanager
from uuid import uuid4
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from psycopg import InterfaceError, OperationalError
from psycopg.errors import LockNotAvailable, QueryCanceled
from psycopg_pool import PoolTimeout, TooManyRequests
from starlette.exceptions import HTTPException
from app.cache import close_cache
from app.instance import INSTANCE_ID
from app.db import close_db, open_db
from app.errors import ApiError, error_response, invalid, not_found
from app.routers import attachments, chats, health, messages, sessions, users
logger = logging.getLogger("messenger.api")
@asynccontextmanager
async def lifespan(app: FastAPI):
try:
await open_db()
yield
finally:
await close_cache()
await close_db()
app = FastAPI(
title="Replicated PostgreSQL messenger — Lab 3",
docs_url=None,
redoc_url=None,
openapi_url=None,
lifespan=lifespan,
)
@app.middleware("http")
async def request_middleware(request: Request, call_next):
request.state.request_id = str(uuid4())
try:
response = await call_next(request)
except ApiError as exc:
response = error_response(request, exc)
except (
OperationalError,
InterfaceError,
PoolTimeout,
TooManyRequests,
QueryCanceled,
LockNotAvailable,
) as exc:
logger.warning(
"Database unavailable request_id=%s error_type=%s",
request.state.request_id,
type(exc).__name__,
)
response = error_response(
request,
ApiError(
503,
"unavailable",
"Сервис временно недоступен",
),
)
except Exception as exc:
logger.error(
"Unhandled error request_id=%s error_type=%s",
request.state.request_id,
type(exc).__name__,
)
response = error_response(
request,
ApiError(
500,
"internal_error",
"Внутренняя ошибка сервера",
),
)
response.headers["X-Request-Id"] = request.state.request_id
response.headers["X-Instance-Id"] = INSTANCE_ID
return response
@app.exception_handler(RequestValidationError)
async def validation_error_handler(request: Request, exc):
return error_response(request, invalid())
@app.exception_handler(HTTPException)
async def http_error_handler(request: Request, exc: HTTPException):
if exc.status_code == 404:
error = not_found()
else:
error = invalid("Недопустимый HTTP-запрос")
return error_response(request, error)
app.include_router(health.router)
app.include_router(users.router)
app.include_router(sessions.router)
app.include_router(chats.router)
app.include_router(messages.router)
app.include_router(attachments.router)
+84
View File
@@ -0,0 +1,84 @@
from __future__ import annotations
import hashlib
import os
from pathlib import Path
import psycopg
MIGRATIONS_DIR = Path(__file__).resolve().parent.parent / "migrations"
MIGRATION_LOCK_ID = 202602001
def apply_migrations() -> None:
files = sorted(MIGRATIONS_DIR.glob("[0-9]*_*.sql"))
if not files:
raise RuntimeError("Migration files not found")
with psycopg.connect(
host=os.getenv("PGHOST", "postgres"),
port=int(os.getenv("PGPORT", "5432")),
dbname=os.getenv("PGDATABASE", "messenger"),
user=os.getenv("PGUSER", "messenger"),
password=os.environ["PGPASSWORD"],
connect_timeout=5,
options="-c statement_timeout=30000 -c lock_timeout=10000",
) as conn:
conn.execute(
"SELECT pg_advisory_xact_lock(%s)",
(MIGRATION_LOCK_ID,),
)
conn.execute(
"""
CREATE TABLE IF NOT EXISTS schema_migrations (
version TEXT PRIMARY KEY,
checksum TEXT NOT NULL,
applied_at TIMESTAMPTZ NOT NULL
DEFAULT clock_timestamp()
)
"""
)
for path in files:
version = path.name
content = path.read_bytes()
checksum = hashlib.sha256(content).hexdigest()
row = conn.execute(
"""
SELECT checksum
FROM schema_migrations
WHERE version = %s
""",
(version,),
).fetchone()
if row is not None:
if row[0] != checksum:
raise RuntimeError(
f"Applied migration was modified: {version}"
)
print(f"Already applied: {version}", flush=True)
continue
conn.execute(content.decode("utf-8"), prepare=False)
conn.execute(
"""
INSERT INTO schema_migrations (version, checksum)
VALUES (%s, %s)
""",
(version, checksum),
)
print(f"Executed: {version} (pending commit)", flush=True)
print("Migrations committed successfully", flush=True)
if __name__ == "__main__":
apply_migrations()
+12
View File
@@ -0,0 +1,12 @@
from __future__ import annotations
import hashlib
def object_lock_id(bucket: str, object_key: str) -> int:
value = f"s3-object\0{bucket}\0{object_key}".encode("utf-8")
return int.from_bytes(
hashlib.sha256(value).digest()[:8],
byteorder="big",
signed=True,
)
+128
View File
@@ -0,0 +1,128 @@
from __future__ import annotations
import base64
import binascii
import json
import re
from datetime import datetime
from uuid import UUID
from fastapi import Request
from fastapi.responses import JSONResponse
from app.errors import invalid
from app.responses import json_response, utc_text
def encode_cursor(scope: str, item: dict) -> str:
raw = json.dumps(
{
"scope": scope,
"created_at": utc_text(item["created_at"]),
"id": str(item["id"]),
},
separators=(",", ":"),
).encode("utf-8")
return (
base64.urlsafe_b64encode(raw)
.decode("ascii")
.rstrip("=")
)
def decode_cursor(
cursor: str,
scope: str,
) -> tuple[datetime, UUID]:
if not cursor or len(cursor) > 2048:
raise invalid("Некорректный cursor")
try:
padded = cursor + "=" * (-len(cursor) % 4)
raw = base64.b64decode(
padded,
altchars=b"-_",
validate=True,
)
data = json.loads(raw.decode("utf-8"))
if (
not isinstance(data, dict)
or set(data) != {"scope", "created_at", "id"}
or data["scope"] != scope
):
raise ValueError
timestamp = data["created_at"]
if (
not isinstance(timestamp, str)
or not timestamp.endswith("Z")
or not isinstance(data["id"], str)
):
raise ValueError
created_at = datetime.fromisoformat(
timestamp[:-1] + "+00:00"
)
item_id = UUID(data["id"])
return created_at, item_id
except (
ValueError,
TypeError,
UnicodeError,
binascii.Error,
OverflowError,
):
raise invalid("Некорректный cursor") from None
def pagination(
request: Request,
scope: str,
) -> tuple[int, tuple[datetime, UUID] | None]:
raw_limit = request.query_params.get("limit", "50")
if (
len(raw_limit) > 10
or re.fullmatch(r"[0-9]+", raw_limit) is None
):
raise invalid("Некорректный limit")
limit = int(raw_limit)
if not 1 <= limit <= 100:
raise invalid("Некорректный limit")
raw_cursor = request.query_params.get("cursor")
after = None
if raw_cursor is not None:
after = decode_cursor(raw_cursor, scope)
return limit, after
def page_response(
rows: list[dict],
limit: int,
scope: str,
) -> JSONResponse:
items = rows[:limit]
next_cursor = None
if len(rows) > limit:
next_cursor = encode_cursor(scope, items[-1])
return json_response(
{
"items": items,
"next_cursor": next_cursor,
}
)
+126
View File
@@ -0,0 +1,126 @@
from __future__ import annotations
import json
import logging
import time
import pika
from app.broker import QUEUE_NAME, connect_broker
from app.job_db import connect_db
from app.responses import utc_text
logger = logging.getLogger("messenger.publisher")
def publish_one(db, channel) -> bool:
with db.transaction():
row = db.execute(
"""
SELECT o.id AS outbox_id,
o.job_id,
o.attempt,
j.attachment_id,
j.pipeline_version,
j.created_at
FROM attachment_outbox AS o
JOIN attachment_jobs AS j ON j.id = o.job_id
JOIN attachments AS a ON a.id = j.attachment_id
WHERE o.published_at IS NULL
AND o.available_at <= clock_timestamp()
AND j.available_at <= clock_timestamp()
AND j.status = 'queued'
AND j.attempt = o.attempt
AND a.status = 'queued'
AND a.pipeline_version = j.pipeline_version
ORDER BY o.available_at, o.id
LIMIT 1
FOR UPDATE OF o SKIP LOCKED
"""
).fetchone()
if row is None:
return False
payload = {
"schema_version": 1,
"job_id": str(row["job_id"]),
"type": "attachment.process.v1",
"attachment_id": str(row["attachment_id"]),
"pipeline_version": row["pipeline_version"],
"attempt": row["attempt"],
"created_at": utc_text(row["created_at"]),
}
channel.basic_publish(
exchange="",
routing_key=QUEUE_NAME,
body=json.dumps(
payload,
separators=(",", ":"),
).encode("utf-8"),
properties=pika.BasicProperties(
content_type="application/json",
delivery_mode=2,
message_id=str(row["outbox_id"]),
type="attachment.process.v1",
),
mandatory=True,
)
db.execute(
"""
UPDATE attachment_outbox
SET published_at = clock_timestamp()
WHERE id = %s
""",
(row["outbox_id"],),
)
logger.info(
"published job_id=%s attempt=%s",
row["job_id"],
row["attempt"],
)
return True
def main():
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s",
)
while True:
broker = None
try:
broker, channel = connect_broker()
channel.confirm_delivery()
with connect_db() as db:
logger.info("publisher connected")
while True:
if not publish_one(db, channel):
broker.process_data_events(time_limit=0.5)
except KeyboardInterrupt:
return
except Exception as exc:
logger.warning(
"publisher reconnect error_type=%s",
type(exc).__name__,
)
time.sleep(2)
finally:
if broker is not None and broker.is_open:
try:
broker.close()
except Exception:
pass
if __name__ == "__main__":
main()
+188
View File
@@ -0,0 +1,188 @@
from __future__ import annotations
import argparse
import hashlib
import json
import os
from uuid import UUID, uuid4
from app.job_db import connect_db
from app.responses import to_json
from app.storage import _get
def list_failed():
with connect_db() as db:
return db.execute(
"""
SELECT id AS job_id, attachment_id,
pipeline_version, attempt, max_attempts,
error_code, updated_at
FROM attachment_jobs
WHERE status = 'failed'
ORDER BY updated_at, id
LIMIT 100
"""
).fetchall()
def replay(job_id, *, actor, reason, apply):
budget = int(os.getenv("JOB_MAX_ATTEMPTS", "5"))
if not 1 <= budget <= 100:
raise ValueError("Invalid retry budget")
with connect_db() as db:
with db.transaction():
row = db.execute(
"""
SELECT j.*,
a.status AS attachment_status,
a.pipeline_version AS current_version,
a.staging_key, a.size_bytes, a.sha256
FROM attachment_jobs j
JOIN attachments a ON a.id = j.attachment_id
WHERE j.id = %s
FOR UPDATE OF j, a
""",
(job_id,),
).fetchone()
if row is None:
raise ValueError("Unknown job")
if (
row["status"] != "failed"
or row["attachment_status"] != "failed"
or row["pipeline_version"] != row["current_version"]
):
return {
"result": "noop",
"job_id": str(job_id),
"status": row["status"],
"reason": "job_is_not_current_failed_work",
}
if not row["staging_key"]:
raise ValueError("Staging is unavailable")
plan = {
"result": "replayed" if apply else "dry_run",
"job_id": str(job_id),
"previous_attempt": row["attempt"],
"new_attempt": row["attempt"] + 1,
"new_max_attempts": row["attempt"] + budget,
"previous_error_code": row["error_code"],
}
if not apply:
return plan
# Не ставим задачу в очередь, если исходник отсутствует
# или не совпадает с устойчиво принятыми метаданными.
db.execute(
"SET LOCAL idle_in_transaction_session_timeout = '60s'"
)
original = _get(row["staging_key"])
if (
len(original) != row["size_bytes"]
or hashlib.sha256(original).hexdigest() != row["sha256"]
):
raise ValueError("Staging integrity check failed")
db.execute(
"""
INSERT INTO attachment_job_replays (
id, job_id, actor, reason,
previous_attempt, new_attempt, previous_error_code
)
VALUES (%s, %s, %s, %s, %s, %s, %s)
""",
(
uuid4(), job_id, actor, reason,
row["attempt"], plan["new_attempt"], row["error_code"],
),
)
db.execute(
"""
UPDATE attachment_jobs
SET status = 'queued',
attempt = %s,
max_attempts = %s,
error_code = NULL,
lease_token = NULL,
lease_until = NULL,
available_at = clock_timestamp(),
updated_at = clock_timestamp()
WHERE id = %s
""",
(
plan["new_attempt"],
plan["new_max_attempts"],
job_id,
),
)
db.execute(
"""
UPDATE attachments
SET status = 'queued',
error_code = NULL,
updated_at = clock_timestamp()
WHERE id = %s
""",
(row["attachment_id"],),
)
db.execute(
"""
INSERT INTO attachment_outbox (id, job_id, attempt)
VALUES (%s, %s, %s)
""",
(uuid4(), job_id, plan["new_attempt"]),
)
return plan
def main():
parser = argparse.ArgumentParser()
selection = parser.add_mutually_exclusive_group(required=True)
selection.add_argument("--list", action="store_true")
selection.add_argument("--job-id", type=UUID)
parser.add_argument("--actor")
parser.add_argument("--reason")
parser.add_argument("--apply", action="store_true")
args = parser.parse_args()
if args.list and args.apply:
parser.error("--apply requires --job-id")
if args.job_id:
if not args.actor or not 1 <= len(args.actor.strip()) <= 100:
parser.error("--actor must contain 1–100 characters")
if not args.reason or not 1 <= len(args.reason.strip()) <= 500:
parser.error("--reason must contain 1–500 characters")
try:
if args.list:
result = list_failed()
else:
result = replay(
args.job_id,
actor=args.actor.strip(),
reason=args.reason.strip(),
apply=args.apply,
)
except Exception as exc:
print(json.dumps({
"result": "error",
"error_type": type(exc).__name__,
}))
raise SystemExit(1)
print(json.dumps(to_json(result), ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
+40
View File
@@ -0,0 +1,40 @@
from __future__ import annotations
from datetime import datetime, timezone
from uuid import UUID
from fastapi.responses import JSONResponse
def utc_text(value: datetime) -> str:
return (
value.astimezone(timezone.utc)
.isoformat(timespec="microseconds")
.replace("+00:00", "Z")
)
def to_json(value):
if isinstance(value, UUID):
return str(value)
if isinstance(value, datetime):
return utc_text(value)
if isinstance(value, dict):
return {
key: to_json(item)
for key, item in value.items()
}
if isinstance(value, (list, tuple)):
return [to_json(item) for item in value]
return value
def json_response(value, status: int = 200) -> JSONResponse:
return JSONResponse(
status_code=status,
content=to_json(value),
)
View File
+275
View File
@@ -0,0 +1,275 @@
from __future__ import annotations
import asyncio
import hashlib
from contextlib import asynccontextmanager
from uuid import UUID
from fastapi import APIRouter, Request
from fastapi.responses import Response
from starlette.concurrency import run_in_threadpool
from starlette.requests import ClientDisconnect
from app.db import pool
from app.jobs import accept_upload
from app.dependencies import accessible_chat, current_user
from app.errors import ApiError, invalid, not_found
from app.images import MAX_BYTES, inspect_image, validate_filename
from app.responses import json_response
from app.storage import get_object
from app.validation import parse_uuid
router = APIRouter()
binary_slot = asyncio.Semaphore(1)
PUBLIC_FIELDS = (
"id",
"chat_id",
"owner_id",
"filename",
"content_type",
"size_bytes",
"sha256",
"status",
"created_at",
"updated_at",
)
@asynccontextmanager
async def binary_operation():
try:
await asyncio.wait_for(binary_slot.acquire(), timeout=3)
except TimeoutError:
raise ApiError(
503,
"unavailable",
"Обработка файлов временно занята",
) from None
try:
yield
finally:
binary_slot.release()
def public_attachment(row: dict) -> dict:
result = {field: row[field] for field in PUBLIC_FIELDS}
result["variants"] = row.get("variants", [])
result["error_code"] = row.get("error_code")
return result
async def read_image_body(request: Request) -> bytes:
lengths = request.headers.getlist("content-length")
if len(lengths) > 1:
raise invalid("Некорректный Content-Length")
expected = None
if lengths:
value = lengths[0]
if not value.isascii() or not value.isdecimal():
raise invalid("Некорректный Content-Length")
if len(value) > 20:
raise ApiError(
413, "payload_too_large", "Файл превышает 10 MiB"
)
expected = int(value)
if expected > MAX_BYTES:
raise ApiError(
413, "payload_too_large", "Файл превышает 10 MiB"
)
data = bytearray()
async for chunk in request.stream():
if len(data) + len(chunk) > MAX_BYTES:
raise ApiError(
413, "payload_too_large", "Файл превышает 10 MiB"
)
data.extend(chunk)
if expected is not None and len(data) != expected:
raise invalid("Размер тела не соответствует Content-Length")
return bytes(data)
async def accessible_attachment(
attachment_id: UUID,
user_id: UUID,
) -> dict:
async with pool.connection() as conn:
cursor = await conn.execute(
"""
SELECT a.id, a.chat_id, a.owner_id,
a.filename, a.content_type, a.size_bytes,
a.sha256, a.object_key, a.status,
a.error_code, a.pipeline_version,
a.created_at, a.updated_at
FROM attachments AS a
WHERE a.id = %s
AND EXISTS (
SELECT 1
FROM chat_members AS cm
WHERE cm.chat_id = a.chat_id
AND cm.user_id = %s
)
""",
(attachment_id, user_id),
)
row = await cursor.fetchone()
if row is not None:
cursor = await conn.execute(
"""
SELECT name, content_type, size_bytes,
width, height, sha256, object_key
FROM attachment_variants
WHERE attachment_id = %s
AND pipeline_version = %s
ORDER BY name
""",
(row["id"], row["pipeline_version"]),
)
variants = await cursor.fetchall()
row["_variant_objects"] = {
variant["name"]: variant
for variant in variants
}
row["variants"] = [
{
key: value
for key, value in variant.items()
if key != "object_key"
}
for variant in variants
] if row["status"] == "ready" else []
if row is None:
raise not_found()
return row
@router.post("/api/v1/chats/{chat_id}/attachments")
async def upload_attachment(chat_id: str, request: Request):
user, _ = await current_user(request)
chat_uuid, _ = await accessible_chat(chat_id, user["id"])
filenames = request.query_params.getlist("filename")
if len(filenames) != 1:
raise invalid("Требуется одно имя файла")
filename = validate_filename(filenames[0])
content_types = request.headers.getlist("content-type")
if len(content_types) != 1:
raise ApiError(
415,
"unsupported_media_type",
"Требуется Content-Type изображения",
)
declared_type = content_types[0].split(";", 1)[0].strip().lower()
if declared_type not in ("image/png", "image/jpeg"):
raise ApiError(
415,
"unsupported_media_type",
"Допустимы только image/png и image/jpeg",
)
async with binary_operation():
try:
data = await asyncio.wait_for(
read_image_body(request),
timeout=60,
)
except ClientDisconnect:
raise invalid("Загрузка файла прервана") from None
except TimeoutError:
raise invalid("Превышено время загрузки файла") from None
content_type = await run_in_threadpool(
inspect_image,
data,
declared_type,
)
row = await accept_upload(
chat_id=chat_uuid,
owner_id=user["id"],
filename=filename,
content_type=content_type,
data=data,
)
return json_response(public_attachment(row), 202)
@router.get("/api/v1/attachments/{attachment_id}")
async def get_attachment(attachment_id: str, request: Request):
user, _ = await current_user(request)
row = await accessible_attachment(
parse_uuid(attachment_id),
user["id"],
)
return json_response(public_attachment(row))
@router.get("/api/v1/attachments/{attachment_id}/content")
async def download_attachment(attachment_id: str, request: Request):
user, _ = await current_user(request)
row = await accessible_attachment(
parse_uuid(attachment_id),
user["id"],
)
variants = request.query_params.getlist("variant")
if len(variants) > 1:
raise invalid("Допускается один вариант изображения")
variant_name = variants[0] if variants else "original"
if row["status"] != "ready":
raise ApiError(
409,
"conflict",
"Вложение не готово к скачиванию",
)
if variant_name == "original":
selected = row
else:
selected = row["_variant_objects"].get(variant_name)
if selected is None:
raise not_found()
async with binary_operation():
data = await get_object(selected["object_key"])
if (
len(data) != selected["size_bytes"]
or hashlib.sha256(data).hexdigest() != selected["sha256"]
):
raise ApiError(
503,
"unavailable",
"Изображение временно недоступно",
)
return Response(
content=data,
media_type=selected["content_type"],
headers={
"X-Content-Type-Options": "nosniff",
"Cache-Control": "private, no-store",
},
)
+74
View File
@@ -0,0 +1,74 @@
from __future__ import annotations
from fastapi import APIRouter, Request
from app.dependencies import accessible_chat, current_user
from app.errors import invalid
from app.pagination import page_response, pagination
from app.responses import json_response
from app.store import InvalidMembersError, store
from app.validation import parse_uuid, read_payload, valid_text
router = APIRouter()
@router.post("/api/v1/chats")
async def create_chat(request: Request):
user, _ = await current_user(request)
payload = await read_payload(
request,
{"title", "member_ids"},
)
if not valid_text(payload["title"], 100):
raise invalid("Некорректный title")
raw_members = payload["member_ids"]
if (
not isinstance(raw_members, list)
or not 1 <= len(raw_members) <= 100
):
raise invalid("Некорректный member_ids")
member_ids = [parse_uuid(item) for item in raw_members]
if len(set(member_ids)) != len(member_ids):
raise invalid("В member_ids есть дубликаты")
if user["id"] not in member_ids:
raise invalid("Создатель должен входить в member_ids")
try:
chat = await store.create_chat(
payload["title"],
member_ids,
)
except InvalidMembersError:
raise invalid(
"В member_ids есть неизвестный пользователь"
) from None
return json_response(chat, 201)
@router.get("/api/v1/chats")
async def list_chats(request: Request):
user, _ = await current_user(request)
scope = f"chats:{user['id']}"
limit, after = pagination(request, scope)
rows = await store.list_chats(user["id"], limit, after)
return page_response(rows, limit, scope)
@router.get("/api/v1/chats/{chat_id}")
async def get_chat(chat_id: str, request: Request):
user, _ = await current_user(request)
_, chat = await accessible_chat(chat_id, user["id"])
return json_response(chat)
+20
View File
@@ -0,0 +1,20 @@
from __future__ import annotations
from fastapi import APIRouter
from app.db import check_db
from app.storage import check_storage
router = APIRouter()
@router.get("/health/live")
async def health_live():
return {"status": "ok"}
@router.get("/health/ready")
async def health_ready():
await check_db()
await check_storage()
return {"status": "ok"}
+90
View File
@@ -0,0 +1,90 @@
from __future__ import annotations
import re
from fastapi import APIRouter, Request
from app.dependencies import accessible_chat, current_user
from app.errors import invalid
from app.idempotency import create_message_once
from app.pagination import page_response, pagination
from app.responses import json_response
from app.store import store
from app.validation import parse_uuid, read_payload
router = APIRouter()
KEY_RE = re.compile(r"[A-Za-z0-9._:-]{1,128}", re.ASCII)
@router.post("/api/v1/chats/{chat_id}/messages")
async def create_message(chat_id: str, request: Request):
user, _ = await current_user(request)
chat_uuid, _ = await accessible_chat(
chat_id,
user["id"],
)
keys = request.headers.getlist("idempotency-key")
if len(keys) != 1 or KEY_RE.fullmatch(keys[0]) is None:
raise invalid("Требуется корректный Idempotency-Key")
payload = await read_payload(
request,
{"text"},
optional_fields={"attachment_ids"},
)
text = payload["text"]
if not isinstance(text, str) or len(text) > 4000:
raise invalid("Некорректный текст сообщения")
raw_attachment_ids = payload.get("attachment_ids", [])
if (
not isinstance(raw_attachment_ids, list)
or len(raw_attachment_ids) > 10
):
raise invalid("Допускается список максимум из 10 вложений")
attachment_ids = [
parse_uuid(value)
for value in raw_attachment_ids
]
if len(set(attachment_ids)) != len(attachment_ids):
raise invalid("Вложения не должны повторяться")
if not text.strip() and not attachment_ids:
raise invalid("Сообщение должно содержать текст или вложение")
message = await create_message_once(
chat_uuid,
user["id"],
text,
keys[0],
attachment_ids=attachment_ids,
)
return json_response(message, 201)
@router.get("/api/v1/chats/{chat_id}/messages")
async def list_messages(chat_id: str, request: Request):
user, _ = await current_user(request)
chat_uuid, _ = await accessible_chat(
chat_id,
user["id"],
)
scope = f"messages:{chat_uuid}"
limit, after = pagination(request, scope)
rows = await store.list_messages(
chat_uuid,
limit,
after,
)
return page_response(rows, limit, scope)
+82
View File
@@ -0,0 +1,82 @@
from __future__ import annotations
from fastapi import APIRouter, Request
from fastapi.responses import Response
from app.auth import (
DUMMY_PASSWORD_HASH,
generate_token,
hash_token,
parse_basic_credentials,
verify_password,
)
from app.config import SESSION_TTL_SECONDS
from app.dependencies import current_user
from app.errors import invalid, unauthorized
from app.responses import json_response
from app.store import store
router = APIRouter()
@router.post("/api/v1/auth/sessions")
async def create_session(request: Request):
credentials = parse_basic_credentials(
request.headers.get("authorization")
)
if credentials is None:
raise unauthorized("Basic")
username, password = credentials
user = await store.get_user_for_login(username)
stored_hash = (
DUMMY_PASSWORD_HASH
if user is None
else user["password_hash"]
)
password_ok = await verify_password(stored_hash, password)
if user is None or not password_ok:
raise unauthorized("Basic")
if await request.body():
raise invalid("Тело запроса при входе не допускается")
token = generate_token()
session = await store.create_session(
user["id"],
hash_token(token),
SESSION_TTL_SECONDS,
)
public_user = {
field: user[field]
for field in ("id", "username", "display_name", "created_at")
}
return json_response(
{
"token": token,
"token_type": "Bearer",
"expires_at": session["expires_at"],
"user": public_user,
},
201,
)
@router.delete("/api/v1/auth/sessions/current")
async def revoke_session(request: Request):
_, token_digest = await current_user(request)
revoked = await store.revoke_session(token_digest)
if not revoked:
raise unauthorized()
return Response(status_code=204)
+59
View File
@@ -0,0 +1,59 @@
from __future__ import annotations
from fastapi import APIRouter, Request
from app.auth import USERNAME_RE, hash_password
from app.dependencies import current_user
from app.errors import ApiError, invalid
from app.responses import json_response
from app.store import store
from app.validation import read_payload, valid_text
router = APIRouter()
@router.post("/api/v1/users")
async def create_user(request: Request):
payload = await read_payload(
request,
{"username", "display_name", "password"},
)
username = payload["username"]
display_name = payload["display_name"]
password = payload["password"]
if (
not isinstance(username, str)
or USERNAME_RE.fullmatch(username) is None
):
raise invalid("Некорректный username")
if not valid_text(display_name, 100):
raise invalid("Некорректное display_name")
if not valid_text(password, 128) or len(password) < 12:
raise invalid("Пароль должен содержать от 12 до 128 символов")
password_digest = await hash_password(password)
user = await store.create_user(
username,
display_name,
password_digest,
)
if user is None:
raise ApiError(
409,
"conflict",
"Username уже занят",
)
return json_response(user, 201)
@router.get("/api/v1/users/me")
async def get_current_user(request: Request):
user, _ = await current_user(request)
return json_response(user)
+34
View File
@@ -0,0 +1,34 @@
from __future__ import annotations
import asyncio
import time
from app.errors import ApiError
from app.storage import check_storage
async def main() -> None:
deadline = time.monotonic() + 90
while True:
try:
await check_storage()
except ApiError:
if time.monotonic() >= deadline:
raise SystemExit(
"S3 readiness failed: bucket unavailable "
"or API credentials rejected"
) from None
print("Waiting for S3 bucket...", flush=True)
await asyncio.sleep(2)
else:
print(
"S3 bucket is accessible with API credentials",
flush=True,
)
return
if __name__ == "__main__":
asyncio.run(main())
+123
View File
@@ -0,0 +1,123 @@
from __future__ import annotations
import asyncio
import os
from pathlib import Path
import boto3
from botocore.config import Config
from botocore.exceptions import (
BotoCoreError,
ClientError,
)
from app.errors import ApiError
_client = None
def _unavailable() -> ApiError:
return ApiError(
503,
"unavailable",
"Сервис временно недоступен",
)
def _credential(file_variable: str) -> str:
file_path = os.environ[file_variable]
value = Path(file_path).read_text().rstrip("\r\n")
if not value:
raise ValueError("Empty S3 credential file")
return value
def bucket_name() -> str:
return os.environ["S3_BUCKET"]
def get_client():
global _client
if _client is None:
_client = boto3.client(
"s3",
endpoint_url=os.environ["S3_ENDPOINT"],
aws_access_key_id=_credential("S3_ACCESS_KEY_ID_FILE"),
aws_secret_access_key=_credential("S3_SECRET_ACCESS_KEY_FILE"),
region_name=os.getenv("S3_REGION", "us-east-1"),
config=Config(
signature_version="s3v4",
s3={"addressing_style": "path"},
connect_timeout=3,
read_timeout=10,
retries={
"mode": "standard",
"total_max_attempts": 2,
},
),
)
return _client
def _put(key: str, data: bytes, content_type: str) -> None:
get_client().put_object(
Bucket=bucket_name(),
Key=key,
Body=data,
ContentType=content_type,
)
def _get(key: str) -> bytes:
maximum = 10 * 1024 * 1024
response = get_client().get_object(
Bucket=bucket_name(),
Key=key,
)
body = response["Body"]
try:
expected_size = response["ContentLength"]
if not 1 <= expected_size <= maximum:
raise _unavailable()
data = body.read(maximum + 1)
if len(data) != expected_size or len(data) > maximum:
raise _unavailable()
return data
finally:
body.close()
async def put_object(
key: str,
data: bytes,
content_type: str,
) -> None:
try:
await asyncio.to_thread(_put, key, data, content_type)
except (BotoCoreError, ClientError, OSError, KeyError, ValueError):
raise _unavailable() from None
async def get_object(key: str) -> bytes:
try:
return await asyncio.to_thread(_get, key)
except (BotoCoreError, ClientError, OSError, KeyError, ValueError):
raise _unavailable() from None
def _check() -> None:
get_client().head_bucket(Bucket=bucket_name())
async def check_storage() -> None:
try:
await asyncio.to_thread(_check)
except (BotoCoreError, ClientError, OSError, KeyError, ValueError):
raise _unavailable() from None
+280
View File
@@ -0,0 +1,280 @@
from __future__ import annotations
from datetime import datetime
from uuid import UUID, uuid4
from psycopg.errors import ForeignKeyViolation, UniqueViolation
from app.db import pool
class InvalidMembersError(Exception):
pass
class PostgresStore:
async def create_user(
self,
username: str,
display_name: str,
password_hash: str,
) -> dict | None:
try:
async with pool.connection() as conn:
cursor = await conn.execute(
"""
INSERT INTO users (
id, username, display_name, password_hash
)
VALUES (%s, %s, %s, %s)
RETURNING id, username, display_name, created_at
""",
(uuid4(), username, display_name, password_hash),
)
user = await cursor.fetchone()
return user
except UniqueViolation as exc:
if exc.diag.constraint_name == "users_username_unique":
return None
raise
async def get_user(self, user_id: UUID) -> dict | None:
async with pool.connection() as conn:
cursor = await conn.execute(
"""
SELECT id, username, display_name, created_at
FROM users
WHERE id = %s
""",
(user_id,),
)
return await cursor.fetchone()
async def get_user_for_login(self, username: str) -> dict | None:
async with pool.connection() as conn:
cursor = await conn.execute(
"""
SELECT id, username, display_name,
password_hash, created_at
FROM users
WHERE username = %s
""",
(username,),
)
return await cursor.fetchone()
async def create_chat(
self,
title: str,
member_ids: list[UUID],
) -> dict:
chat_id = uuid4()
try:
async with pool.connection() as conn:
cursor = await conn.execute(
"""
INSERT INTO chats (id, title)
VALUES (%s, %s)
RETURNING id, title, created_at
""",
(chat_id, title),
)
chat = await cursor.fetchone()
async with conn.cursor() as cursor:
await cursor.executemany(
"""
INSERT INTO chat_members (chat_id, user_id)
VALUES (%s, %s)
""",
[(chat_id, user_id) for user_id in member_ids],
)
chat["member_ids"] = member_ids
return chat
except ForeignKeyViolation as exc:
raise InvalidMembersError from exc
async def get_accessible_chat(
self,
chat_id: UUID,
user_id: UUID,
) -> dict | None:
async with pool.connection() as conn:
cursor = await conn.execute(
"""
SELECT c.id, c.title, c.created_at,
ARRAY(
SELECT cm.user_id
FROM chat_members AS cm
WHERE cm.chat_id = c.id
ORDER BY cm.user_id
) AS member_ids
FROM chats AS c
WHERE c.id = %s
AND EXISTS (
SELECT 1
FROM chat_members AS access
WHERE access.chat_id = c.id
AND access.user_id = %s
)
""",
(chat_id, user_id),
)
return await cursor.fetchone()
async def list_chats(
self,
user_id: UUID,
limit: int,
after: tuple[datetime, UUID] | None = None,
) -> list[dict]:
params: list[object] = [user_id]
after_sql = ""
if after is not None:
after_sql = "AND (c.created_at, c.id) > (%s, %s)"
params.extend(after)
params.append(limit + 1)
async with pool.connection() as conn:
cursor = await conn.execute(
f"""
SELECT c.id, c.title, c.created_at,
ARRAY(
SELECT cm.user_id
FROM chat_members AS cm
WHERE cm.chat_id = c.id
ORDER BY cm.user_id
) AS member_ids
FROM chats AS c
JOIN chat_members AS access
ON access.chat_id = c.id
WHERE access.user_id = %s
{after_sql}
ORDER BY c.created_at, c.id
LIMIT %s
""",
params,
)
return await cursor.fetchall()
async def create_message(
self,
chat_id: UUID,
sender_id: UUID,
text: str,
) -> dict:
async with pool.connection() as conn:
cursor = await conn.execute(
"""
INSERT INTO messages (id, chat_id, sender_id, text)
VALUES (%s, %s, %s, %s)
RETURNING id, chat_id, sender_id, text, created_at
""",
(uuid4(), chat_id, sender_id, text),
)
message = await cursor.fetchone()
return message
async def list_messages(
self,
chat_id: UUID,
limit: int,
after: tuple[datetime, UUID] | None = None,
) -> list[dict]:
params: list[object] = [chat_id]
after_sql = ""
if after is not None:
after_sql = "AND (created_at, id) > (%s, %s)"
params.extend(after)
params.append(limit + 1)
async with pool.connection() as conn:
cursor = await conn.execute(
f"""
SELECT m.id, m.chat_id, m.sender_id,
m.text, m.created_at,
ARRAY(
SELECT ma.attachment_id
FROM message_attachments AS ma
WHERE ma.message_id = m.id
ORDER BY ma.position
) AS attachment_ids
FROM messages AS m
WHERE m.chat_id = %s
{after_sql}
ORDER BY created_at, id
LIMIT %s
""",
params,
)
return await cursor.fetchall()
async def create_session(
self,
user_id: UUID,
token_hash: str,
ttl_seconds: int,
) -> dict:
async with pool.connection() as conn:
cursor = await conn.execute(
"""
INSERT INTO sessions (
token_hash, user_id, created_at, expires_at
)
VALUES (
%s, %s, statement_timestamp(),
statement_timestamp()
+ (%s * INTERVAL '1 second')
)
RETURNING expires_at
""",
(token_hash, user_id, ttl_seconds),
)
session = await cursor.fetchone()
return session
async def get_session_user_id(
self,
token_hash: str,
) -> UUID | None:
async with pool.connection() as conn:
cursor = await conn.execute(
"""
SELECT user_id
FROM sessions
WHERE token_hash = %s
AND expires_at > statement_timestamp()
""",
(token_hash,),
)
row = await cursor.fetchone()
return None if row is None else row["user_id"]
async def revoke_session(self, token_hash: str) -> bool:
async with pool.connection() as conn:
cursor = await conn.execute(
"""
DELETE FROM sessions
WHERE token_hash = %s
AND expires_at > statement_timestamp()
RETURNING token_hash
""",
(token_hash,),
)
row = await cursor.fetchone()
return row is not None
store = PostgresStore()
+61
View File
@@ -0,0 +1,61 @@
from __future__ import annotations
from uuid import UUID
from fastapi import Request
from app.errors import ApiError, invalid
def parse_uuid(value: object) -> UUID:
if not isinstance(value, str):
raise invalid("Некорректный UUID")
try:
return UUID(value)
except ValueError:
raise invalid("Некорректный UUID") from None
def valid_text(value: object, maximum: int) -> bool:
return (
isinstance(value, str)
and 1 <= len(value) <= maximum
and bool(value.strip())
)
async def read_payload(
request: Request,
expected_fields: set[str],
optional_fields: set[str] | None = None,
) -> dict:
content_type = (
request.headers.get("content-type", "")
.split(";", 1)[0]
.strip()
.lower()
)
if content_type != "application/json":
raise ApiError(
415,
"unsupported_media_type",
"Требуется Content-Type: application/json",
)
try:
payload = await request.json()
except (ValueError, UnicodeError):
raise invalid("Некорректный JSON") from None
allowed_fields = expected_fields | (optional_fields or set())
if (
not isinstance(payload, dict)
or not expected_fields.issubset(payload)
or not set(payload).issubset(allowed_fields)
):
raise invalid("Некорректные поля запроса")
return payload
+341
View File
@@ -0,0 +1,341 @@
from __future__ import annotations
import json
import logging
import os
import random
import subprocess
import sys
import time
from uuid import UUID, uuid4
from app.broker import QUEUE_NAME, connect_broker
from app.job_db import connect_db
from app.faults import trip_fault
logger = logging.getLogger("messenger.worker")
WORKER_CONCURRENCY = int(os.getenv("WORKER_CONCURRENCY", "1"))
if WORKER_CONCURRENCY != 1:
raise ValueError("This worker supports WORKER_CONCURRENCY=1 only")
JOB_TIMEOUT = int(os.getenv("JOB_TIMEOUT_SECONDS", "60"))
LEASE_SECONDS = int(os.getenv("JOB_LEASE_SECONDS", "120"))
if JOB_TIMEOUT < 1 or LEASE_SECONDS < JOB_TIMEOUT + 15:
raise ValueError("Lease must exceed job timeout by at least 15 seconds")
def claim_job(payload: dict):
job_id = UUID(payload["job_id"])
attachment_id = UUID(payload["attachment_id"])
attempt = payload["attempt"]
version = payload["pipeline_version"]
if (
payload.get("schema_version") != 1
or payload.get("type") != "attachment.process.v1"
or type(attempt) is not int
or attempt < 1
or type(version) is not int
or version < 1
):
raise ValueError("Invalid job message")
token = uuid4()
with connect_db() as db:
with db.transaction():
row = db.execute(
"""
SELECT j.id, j.status, j.attempt,
j.attachment_id, j.pipeline_version,
a.status AS attachment_status,
a.pipeline_version AS current_version
FROM attachment_jobs AS j
JOIN attachments AS a ON a.id = j.attachment_id
WHERE j.id = %s
FOR UPDATE OF j, a
""",
(job_id,),
).fetchone()
if (
row is None
or row["attachment_id"] != attachment_id
or row["pipeline_version"] != version
or row["current_version"] != version
or row["attempt"] != attempt
or row["status"] != "queued"
or row["attachment_status"] != "queued"
):
return None
db.execute(
"""
UPDATE attachment_jobs
SET status = 'processing',
lease_token = %s,
lease_until = clock_timestamp()
+ make_interval(secs => %s),
updated_at = clock_timestamp()
WHERE id = %s
""",
(token, LEASE_SECONDS, job_id),
)
db.execute(
"""
UPDATE attachments
SET status = 'processing',
updated_at = clock_timestamp()
WHERE id = %s
""",
(attachment_id,),
)
return job_id, token
def finish_unsuccessful(job_id, token, *, permanent, error_code):
with connect_db() as db:
with db.transaction():
row = db.execute(
"""
SELECT *
FROM attachment_jobs
WHERE id = %s
FOR UPDATE
""",
(job_id,),
).fetchone()
if (
row is None
or row["status"] != "processing"
or row["lease_token"] != token
):
return
exhausted = row["attempt"] >= row["max_attempts"]
terminal = permanent or exhausted
status = "failed" if terminal else "queued"
code = (
error_code if permanent else "retry_exhausted"
) if terminal else None
delay = random.uniform(
0.5,
min(30.0, 2.0 ** min(row["attempt"], 5)),
)
next_attempt = row["attempt"] if terminal else row["attempt"] + 1
db.execute(
"""
UPDATE attachment_jobs
SET status = %s,
attempt = %s,
error_code = %s,
lease_token = NULL,
lease_until = NULL,
available_at = clock_timestamp()
+ make_interval(secs => %s),
updated_at = clock_timestamp()
WHERE id = %s
""",
(status, next_attempt, code, delay, job_id),
)
db.execute(
"""
UPDATE attachments
SET status = %s,
error_code = %s,
updated_at = clock_timestamp()
WHERE id = %s
AND pipeline_version = %s
AND status <> 'ready'
""",
(
status, code,
row["attachment_id"], row["pipeline_version"],
),
)
if not terminal:
db.execute(
"""
INSERT INTO attachment_outbox (
id, job_id, attempt, available_at
)
VALUES (
%s, %s, %s,
clock_timestamp() + make_interval(secs => %s)
)
""",
(uuid4(), job_id, next_attempt, delay),
)
logger.info(
"job transition job_id=%s status=%s reason=%s",
job_id, status, error_code,
)
def recover_expired():
with connect_db() as db:
rows = db.execute(
"""
SELECT id, lease_token
FROM attachment_jobs
WHERE status = 'processing'
AND lease_until < clock_timestamp()
ORDER BY lease_until
LIMIT 10
"""
).fetchall()
for row in rows:
finish_unsuccessful(
row["id"],
row["lease_token"],
permanent=False,
error_code="lease_expired",
)
def run_child(broker, job_id, token):
process = subprocess.Popen(
[
sys.executable,
"-m",
"app.job_runner",
str(job_id),
str(token),
],
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
text=True,
)
deadline = time.monotonic() + JOB_TIMEOUT
try:
while process.poll() is None:
if time.monotonic() >= deadline:
process.kill()
process.communicate()
return {"outcome": "retry", "error_code": "processing_timeout"}
broker.process_data_events(time_limit=0.2)
output, _ = process.communicate()
if process.returncode == 75:
logger.warning(
"child_fault job_id=%s stage=after_objects exit_code=75",
job_id,
)
os._exit(75)
if process.returncode != 0:
return {"outcome": "retry", "error_code": "processing_failed"}
result = json.loads(output)
if result.get("outcome") not in ("ready", "stale", "failed", "retry"):
raise ValueError("Invalid child outcome")
return result
finally:
if process.poll() is None:
process.kill()
process.communicate()
def main():
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s",
)
while True:
broker = None
try:
broker, channel = connect_broker()
channel.basic_qos(prefetch_count=1)
logger.info("worker connected")
next_recovery = 0.0
while True:
if time.monotonic() >= next_recovery:
recover_expired()
next_recovery = time.monotonic() + 5
method, properties, body = channel.basic_get(
queue=QUEUE_NAME,
auto_ack=False,
)
if method is None:
broker.process_data_events(time_limit=0.5)
continue
try:
if len(body) > 16_384:
raise ValueError("Oversized job message")
payload = json.loads(body)
if not isinstance(payload, dict):
raise ValueError("Job must be an object")
claimed = claim_job(payload)
logger.info(
"delivery job_id=%s redelivered=%s",
payload["job_id"],
method.redelivered,
)
except (ValueError, KeyError, TypeError):
logger.warning("invalid broker message rejected")
channel.basic_reject(
delivery_tag=method.delivery_tag,
requeue=False,
)
continue
if claimed is not None:
job_id, token = claimed
result = run_child(broker, job_id, token)
if result["outcome"] in ("failed", "retry"):
finish_unsuccessful(
job_id,
token,
permanent=result["outcome"] == "failed",
error_code=result["error_code"],
)
if claimed is not None and result["outcome"] == "ready":
trip_fault(job_id, "before_ack")
channel.basic_ack(delivery_tag=method.delivery_tag)
logger.info("ack job_id=%s", payload["job_id"])
except KeyboardInterrupt:
return
except Exception as exc:
logger.warning(
"worker reconnect error_type=%s",
type(exc).__name__,
)
time.sleep(2)
finally:
if broker is not None and broker.is_open:
try:
broker.close()
except Exception:
pass
if __name__ == "__main__":
main()