feat: complete lab 7 for grade 4
Skeleton contracts / contracts (pull_request) Blocked by required conditions
Skeleton contracts / contracts (pull_request) Blocked by required conditions
This commit is contained in:
@@ -0,0 +1,150 @@
|
||||
import asyncio
|
||||
import hashlib
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unicodedata
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
from fastapi import HTTPException, Request
|
||||
from fastapi.responses import StreamingResponse
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
from starlette.requests import ClientDisconnect
|
||||
|
||||
from .database import get_connection
|
||||
from .jobs import enqueue
|
||||
from .telemetry import span
|
||||
from .storage import s3, BUCKET
|
||||
|
||||
MAX_BYTES = 10 * 1024**2
|
||||
upload_slots = asyncio.Semaphore(1)
|
||||
|
||||
|
||||
def serialize(row):
|
||||
result = {key: str(row[key]) for key in ('id', 'chat_id', 'owner_id')}
|
||||
result.update({key: row[key] for key in ('filename', 'content_type', 'size_bytes', 'sha256', 'status')})
|
||||
result.update({key: row[key].isoformat().replace('+00:00', 'Z') for key in ('created_at', 'updated_at')})
|
||||
manifest = row.get('manifest') or {}
|
||||
variants = [
|
||||
dict(name=name, **{field: obj[field] for field in
|
||||
('content_type', 'size_bytes', 'sha256', 'width', 'height')})
|
||||
for name, obj in sorted(manifest.items()) if name != 'original'
|
||||
]
|
||||
return dict(result, variants=variants, error_code=row['error_code'])
|
||||
|
||||
|
||||
def persist(path, chat, owner, filename, mime, size, checksum):
|
||||
attachment_id = uuid4()
|
||||
key = 'staging/' + str(attachment_id)
|
||||
# The same lock is taken by cleanup before its final DB check/deletion.
|
||||
# A process crash releases the transaction; an uncommitted object is later cleaned.
|
||||
with get_connection() as conn:
|
||||
with span("attachment.accept"), conn.transaction():
|
||||
conn.execute('SELECT pg_advisory_xact_lock(hashtextextended(%s, 0))', (key,))
|
||||
with open(path, 'rb') as source:
|
||||
s3.put_object(Bucket=BUCKET, Key=key, Body=source, ContentLength=size, ContentType=mime)
|
||||
row = conn.execute('''INSERT INTO attachments
|
||||
(id, chat_id, owner_id, filename, object_key, size_bytes, content_type, sha256, staging_key, status)
|
||||
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,'queued') RETURNING *''',
|
||||
(attachment_id, UUID(chat), UUID(owner), filename, key, size, mime, checksum, key)).fetchone()
|
||||
enqueue(conn, attachment_id, 1, accepted=True)
|
||||
# Exiting transaction above commits before returning 202.
|
||||
return serialize(row)
|
||||
|
||||
|
||||
def accessible(attachment_id, user_id):
|
||||
try:
|
||||
aid = UUID(attachment_id)
|
||||
except ValueError:
|
||||
raise HTTPException(400, 'Неверный UUID') from None
|
||||
with get_connection() as conn:
|
||||
row = conn.execute('''SELECT a.*, j.manifest FROM attachments a
|
||||
LEFT JOIN image_jobs j ON j.attachment_id=a.id AND j.pipeline_version=a.active_version
|
||||
JOIN chat_members cm ON cm.chat_id=a.chat_id
|
||||
WHERE a.id=%s AND cm.user_id=%s''', (aid, UUID(user_id))).fetchone()
|
||||
if row is None:
|
||||
raise HTTPException(404, 'Вложение не найдено')
|
||||
return row
|
||||
|
||||
|
||||
def register(app, current_user, get_chat):
|
||||
@app.post('/api/v1/chats/{chat_id}/attachments', status_code=202)
|
||||
async def upload(chat_id: str, request: Request):
|
||||
user = await run_in_threadpool(current_user, request)
|
||||
chat = await run_in_threadpool(get_chat, chat_id, request)
|
||||
filename = request.query_params.get('filename', '')
|
||||
if (not 1 <= len(filename) <= 255 or not filename.strip()
|
||||
or any(c in '/\\' or unicodedata.category(c).startswith('C') for c in filename)):
|
||||
raise HTTPException(400, 'Недопустимое имя файла')
|
||||
mime = request.headers.get('content-type', '').split(';')[0].strip().lower()
|
||||
if mime not in ('image/png', 'image/jpeg'):
|
||||
raise HTTPException(415, 'Ожидается PNG или JPEG')
|
||||
length = request.headers.get('content-length')
|
||||
if length is not None:
|
||||
if not length.isascii() or not length.isdecimal() or len(length) > 12:
|
||||
raise HTTPException(400, 'Неверный размер')
|
||||
if int(length) > MAX_BYTES:
|
||||
raise HTTPException(413, 'Файл больше 10 MiB')
|
||||
try:
|
||||
await asyncio.wait_for(upload_slots.acquire(), timeout=30)
|
||||
except asyncio.TimeoutError:
|
||||
raise HTTPException(503, 'Загрузчик занят') from None
|
||||
try:
|
||||
with tempfile.NamedTemporaryFile(prefix='lab6-') as target:
|
||||
size = 0
|
||||
digest = hashlib.sha256()
|
||||
try:
|
||||
async with asyncio.timeout(30):
|
||||
async for chunk in request.stream():
|
||||
size += len(chunk)
|
||||
if size > MAX_BYTES:
|
||||
raise HTTPException(413, 'Файл больше 10 MiB')
|
||||
target.write(chunk)
|
||||
digest.update(chunk)
|
||||
except ClientDisconnect:
|
||||
raise HTTPException(400, 'Загрузка прервана') from None
|
||||
except TimeoutError:
|
||||
raise HTTPException(400, 'Истекло время загрузки') from None
|
||||
target.flush()
|
||||
def validate():
|
||||
try:
|
||||
return subprocess.run([sys.executable, '-m', 'src.image_check', target.name, mime],
|
||||
timeout=10, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode
|
||||
except subprocess.TimeoutExpired:
|
||||
return 15
|
||||
code = await run_in_threadpool(validate)
|
||||
if code != 0:
|
||||
raise HTTPException(413 if code == 13 else 415, 'Недопустимое изображение')
|
||||
return await run_in_threadpool(persist, target.name, chat['id'], user['id'], filename, mime, size, digest.hexdigest())
|
||||
finally:
|
||||
upload_slots.release()
|
||||
|
||||
@app.get('/api/v1/attachments/{attachment_id}')
|
||||
def metadata(attachment_id: str, request: Request):
|
||||
return serialize(accessible(attachment_id, current_user(request)['id']))
|
||||
|
||||
@app.get('/api/v1/attachments/{attachment_id}/content')
|
||||
def content(attachment_id: str, request: Request):
|
||||
row = accessible(attachment_id, current_user(request)['id'])
|
||||
if row['status'] != 'ready':
|
||||
raise HTTPException(409, 'Вложение не готово')
|
||||
variant = row['manifest'].get(request.query_params.get('variant', 'original'))
|
||||
if variant is None:
|
||||
raise HTTPException(404, 'Вариант не найден')
|
||||
obj = s3.get_object(Bucket=BUCKET, Key=variant['key'])
|
||||
def chunks():
|
||||
try:
|
||||
for chunk in obj['Body'].iter_chunks(64 * 1024):
|
||||
yield chunk
|
||||
finally:
|
||||
obj['Body'].close()
|
||||
return StreamingResponse(chunks(), media_type=variant['content_type'], headers={
|
||||
'Content-Length': str(variant['size_bytes']), 'X-Content-Type-Options': 'nosniff',
|
||||
'Content-Disposition': 'attachment', 'Cache-Control': 'private, no-store'})
|
||||
|
||||
@app.exception_handler(BotoCoreError)
|
||||
@app.exception_handler(ClientError)
|
||||
async def storage_error(request, exc):
|
||||
from .main import error_response
|
||||
return error_response(request, 503, 'unavailable', 'Хранилище временно недоступно')
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
import base64
|
||||
import binascii
|
||||
import hashlib
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from argon2 import PasswordHasher, Type
|
||||
from argon2.exceptions import InvalidHashError, VerifyMismatchError
|
||||
|
||||
|
||||
memory = int(os.getenv("ARGON2_MEMORY_KIB", "65536"))
|
||||
iterations = int(os.getenv("ARGON2_ITERATIONS", "3"))
|
||||
parallelism = int(os.getenv("ARGON2_PARALLELISM", "4"))
|
||||
if memory < 19456 or iterations < 2 or parallelism < 1:
|
||||
raise ValueError("Argon2id configuration below the lab minimum")
|
||||
|
||||
password_hasher = PasswordHasher(
|
||||
time_cost=iterations, memory_cost=memory, parallelism=parallelism, type=Type.ID,
|
||||
)
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return password_hasher.hash(password)
|
||||
|
||||
|
||||
def verify_password(password_hash: str, password: str) -> bool:
|
||||
try:
|
||||
return password_hasher.verify(password_hash, password)
|
||||
except (VerifyMismatchError, InvalidHashError):
|
||||
return False
|
||||
|
||||
|
||||
def parse_basic(authorization: str | None) -> tuple[str, str] | None:
|
||||
if not authorization:
|
||||
return None
|
||||
|
||||
scheme, separator, credentials = authorization.partition(" ")
|
||||
|
||||
if not separator or scheme.lower() != "basic":
|
||||
return None
|
||||
|
||||
try:
|
||||
raw = base64.b64decode(credentials, validate=True)
|
||||
decoded = raw.decode("utf-8")
|
||||
username, password = decoded.split(":", 1)
|
||||
except (ValueError, UnicodeError, binascii.Error):
|
||||
return None
|
||||
|
||||
if not re.fullmatch(r"[a-z0-9_]{3,32}", username):
|
||||
return None
|
||||
|
||||
if not 12 <= len(password) <= 128:
|
||||
return None
|
||||
|
||||
return username, password
|
||||
|
||||
|
||||
def parse_bearer(authorization: str | None) -> str | None:
|
||||
if not authorization:
|
||||
return None
|
||||
|
||||
scheme, separator, token = authorization.partition(" ")
|
||||
|
||||
if not separator or scheme.lower() != "bearer":
|
||||
return None
|
||||
|
||||
if not re.fullmatch(r"[A-Za-z0-9._~+/-]+={0,2}", token) or len(token) > 512:
|
||||
return None
|
||||
|
||||
return token
|
||||
|
||||
|
||||
def create_token() -> str:
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
|
||||
def hash_token(token: str) -> str:
|
||||
return hashlib.sha256(token.encode("ascii")).hexdigest()
|
||||
|
||||
|
||||
def session_expiration() -> datetime:
|
||||
ttl = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
|
||||
|
||||
if ttl < 1:
|
||||
raise ValueError("SESSION_TTL_SECONDS must be positive")
|
||||
|
||||
return datetime.now(timezone.utc) + timedelta(seconds=ttl)
|
||||
|
||||
|
||||
def format_datetime(value: datetime) -> str:
|
||||
return value.astimezone(timezone.utc).isoformat(
|
||||
timespec="microseconds"
|
||||
).replace("+00:00", "Z")
|
||||
@@ -0,0 +1,34 @@
|
||||
"""Mutual TLS transport with explicit broker identities and publisher confirms."""
|
||||
import json
|
||||
import os
|
||||
import ssl
|
||||
from contextlib import contextmanager
|
||||
|
||||
import pika
|
||||
|
||||
QUEUE = "attachment.process.v1"
|
||||
EXCHANGE = "attachments"
|
||||
|
||||
|
||||
@contextmanager
|
||||
def channel():
|
||||
context = ssl.create_default_context(cafile=os.environ["TLS_CA_FILE"])
|
||||
context.load_cert_chain("/run/identity/amqp.crt", "/run/identity/amqp.key")
|
||||
params = pika.ConnectionParameters(
|
||||
host="broker", port=5671, virtual_host="messenger",
|
||||
credentials=pika.credentials.ExternalCredentials(),
|
||||
ssl_options=pika.SSLOptions(context, "broker"), connection_attempts=1,
|
||||
socket_timeout=4, stack_timeout=8, blocked_connection_timeout=10, heartbeat=120,
|
||||
)
|
||||
connection = pika.BlockingConnection(params)
|
||||
try:
|
||||
yield connection, connection.channel()
|
||||
finally:
|
||||
if connection.is_open:
|
||||
connection.close()
|
||||
|
||||
|
||||
def send(ch, message, headers=None):
|
||||
ch.basic_publish(EXCHANGE, QUEUE, json.dumps(message).encode(), mandatory=True,
|
||||
properties=pika.BasicProperties(content_type="application/json", delivery_mode=2,
|
||||
message_id=message["job_id"], headers=headers))
|
||||
@@ -0,0 +1,254 @@
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from .database import get_connection
|
||||
|
||||
|
||||
def serialize_chat(row):
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"title": row["title"],
|
||||
"member_ids": [str(member_id) for member_id in row["member_ids"]],
|
||||
"created_at": row["created_at"].isoformat(
|
||||
timespec="microseconds"
|
||||
).replace("+00:00", "Z"),
|
||||
}
|
||||
|
||||
|
||||
def serialize_message(row):
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"chat_id": str(row["chat_id"]),
|
||||
"sender_id": str(row["sender_id"]),
|
||||
"text": row["text"],
|
||||
"attachment_ids": [str(a) for a in row["attachment_ids"]],
|
||||
"created_at": row["created_at"].isoformat(
|
||||
timespec="microseconds"
|
||||
).replace("+00:00", "Z"),
|
||||
}
|
||||
|
||||
|
||||
def create_chat(creator_id, title, member_ids):
|
||||
chat_id = uuid4()
|
||||
members = [UUID(member_id) for member_id in member_ids]
|
||||
|
||||
with get_connection() as conn:
|
||||
with conn.transaction():
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id
|
||||
FROM users
|
||||
WHERE id = ANY(%s::uuid[])
|
||||
""",
|
||||
(members,),
|
||||
)
|
||||
existing = {row["id"] for row in cur.fetchall()}
|
||||
|
||||
if len(existing) != len(members):
|
||||
return None
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO chats (id, title, created_by)
|
||||
VALUES (%s, %s, %s)
|
||||
RETURNING id, title, created_at
|
||||
""",
|
||||
(chat_id, title, UUID(creator_id)),
|
||||
)
|
||||
chat = cur.fetchone()
|
||||
|
||||
cur.executemany(
|
||||
"""
|
||||
INSERT INTO chat_members (chat_id, user_id)
|
||||
VALUES (%s, %s)
|
||||
""",
|
||||
[(chat_id, member_id) for member_id in members],
|
||||
)
|
||||
|
||||
return {
|
||||
"id": str(chat["id"]),
|
||||
"title": chat["title"],
|
||||
"member_ids": member_ids,
|
||||
"created_at": chat["created_at"].isoformat(
|
||||
timespec="microseconds"
|
||||
).replace("+00:00", "Z"),
|
||||
}
|
||||
|
||||
|
||||
def get_chat(chat_id, user_id):
|
||||
with get_connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
c.id,
|
||||
c.title,
|
||||
c.created_at,
|
||||
ARRAY(
|
||||
SELECT cm2.user_id
|
||||
FROM chat_members cm2
|
||||
WHERE cm2.chat_id = c.id
|
||||
ORDER BY cm2.user_id
|
||||
) AS member_ids
|
||||
FROM chats c
|
||||
JOIN chat_members cm
|
||||
ON cm.chat_id = c.id
|
||||
WHERE c.id = %s
|
||||
AND cm.user_id = %s
|
||||
""",
|
||||
(UUID(chat_id), UUID(user_id)),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return serialize_chat(row) if row else None
|
||||
|
||||
|
||||
def list_chats(user_id, limit, last_chat_id=None):
|
||||
with get_connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
last_key = None
|
||||
|
||||
if last_chat_id is not None:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT c.created_at, c.id
|
||||
FROM chats c
|
||||
JOIN chat_members cm
|
||||
ON cm.chat_id = c.id
|
||||
WHERE c.id = %s
|
||||
AND cm.user_id = %s
|
||||
""",
|
||||
(UUID(last_chat_id), UUID(user_id)),
|
||||
)
|
||||
last_key = cur.fetchone()
|
||||
|
||||
if last_key is None:
|
||||
return None
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
c.id,
|
||||
c.title,
|
||||
c.created_at,
|
||||
ARRAY(
|
||||
SELECT cm2.user_id
|
||||
FROM chat_members cm2
|
||||
WHERE cm2.chat_id = c.id
|
||||
ORDER BY cm2.user_id
|
||||
) AS member_ids
|
||||
FROM chats c
|
||||
JOIN chat_members cm
|
||||
ON cm.chat_id = c.id
|
||||
WHERE cm.user_id = %s
|
||||
AND (
|
||||
%s::timestamptz IS NULL
|
||||
OR (c.created_at, c.id) >
|
||||
(%s::timestamptz, %s::uuid)
|
||||
)
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT %s
|
||||
""",
|
||||
(
|
||||
UUID(user_id),
|
||||
last_key["created_at"] if last_key else None,
|
||||
last_key["created_at"] if last_key else None,
|
||||
last_key["id"] if last_key else None,
|
||||
limit + 1,
|
||||
),
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
|
||||
return [serialize_chat(row) for row in rows]
|
||||
|
||||
|
||||
def create_message(chat_id, sender_id, text, key, attachment_ids):
|
||||
# INSERT ON CONFLICT waits for a concurrent transaction on the same key.
|
||||
# READ COMMITTED's next statement sees its committed result. Both the
|
||||
# message and deduplication record commit together, or both roll back.
|
||||
with get_connection() as conn:
|
||||
with conn.transaction():
|
||||
attachments = [UUID(a) for a in attachment_ids]
|
||||
scope = (UUID(chat_id), UUID(sender_id), key)
|
||||
conn.execute("""
|
||||
DELETE FROM message_requests WHERE chat_id=%s AND sender_id=%s AND key=%s
|
||||
AND created_at <= clock_timestamp() - interval '24 hours'
|
||||
""", scope)
|
||||
row = conn.execute(
|
||||
"""INSERT INTO message_requests(chat_id, sender_id, key, text)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
ON CONFLICT (chat_id, sender_id, key) DO NOTHING
|
||||
RETURNING key""", (*scope, text)
|
||||
).fetchone()
|
||||
if row is None:
|
||||
previous = conn.execute(
|
||||
"""SELECT m.* FROM message_requests r
|
||||
JOIN messages m ON m.id = r.message_id
|
||||
WHERE r.chat_id=%s AND r.sender_id=%s AND r.key=%s""",
|
||||
scope,
|
||||
).fetchone()
|
||||
if previous["text"] != text or previous["attachment_ids"] != attachments:
|
||||
return "conflict"
|
||||
return serialize_message(previous)
|
||||
rows = conn.execute(
|
||||
'SELECT id,status FROM attachments WHERE chat_id=%s AND id=ANY(%s::uuid[]) '
|
||||
'ORDER BY id FOR SHARE', (UUID(chat_id), attachments)
|
||||
).fetchall()
|
||||
if len(rows) != len(attachments) or any(row['status'] == 'failed' for row in rows):
|
||||
# No unfinished idempotency record may survive validation failure.
|
||||
conn.execute('DELETE FROM message_requests WHERE chat_id=%s AND sender_id=%s AND key=%s', scope)
|
||||
return None if len(rows) != len(attachments) else "attachment_failed"
|
||||
message = conn.execute(
|
||||
"""INSERT INTO messages(id, chat_id, sender_id, text, attachment_ids)
|
||||
VALUES (%s, %s, %s, %s, %s) RETURNING *""",
|
||||
(uuid4(), UUID(chat_id), UUID(sender_id), text, attachments),
|
||||
).fetchone()
|
||||
conn.execute(
|
||||
"""UPDATE message_requests SET message_id=%s
|
||||
WHERE chat_id=%s AND sender_id=%s AND key=%s""",
|
||||
(message["id"], *scope),
|
||||
)
|
||||
return serialize_message(message)
|
||||
|
||||
|
||||
def list_messages(chat_id, limit, last_message_id=None):
|
||||
with get_connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
last_key = None
|
||||
|
||||
if last_message_id is not None:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT created_at, id
|
||||
FROM messages
|
||||
WHERE chat_id = %s
|
||||
AND id = %s
|
||||
""",
|
||||
(UUID(chat_id), UUID(last_message_id)),
|
||||
)
|
||||
last_key = cur.fetchone()
|
||||
|
||||
if last_key is None:
|
||||
return None
|
||||
|
||||
# Разные формы SQL сохраняют индексный range scan и для generic plan.
|
||||
# В SQL подставляется только константа; значения остаются параметрами.
|
||||
cursor_condition = ""
|
||||
params = [UUID(chat_id)]
|
||||
if last_key is not None:
|
||||
cursor_condition = "AND (created_at, id) > (%s, %s)"
|
||||
params.extend([last_key["created_at"], last_key["id"]])
|
||||
params.append(limit + 1)
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT id, chat_id, sender_id, text, attachment_ids, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = %s
|
||||
{cursor_condition}
|
||||
ORDER BY created_at, id
|
||||
LIMIT %s
|
||||
""",
|
||||
params,
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
|
||||
return [serialize_message(row) for row in rows]
|
||||
@@ -0,0 +1,175 @@
|
||||
"""Refresh bounded KV snapshots using renewable, certificate-authenticated tokens."""
|
||||
import json
|
||||
import logging
|
||||
from math import isfinite
|
||||
import os
|
||||
import ssl
|
||||
from threading import Event, Lock, Thread
|
||||
from time import monotonic
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.request import HTTPSHandler, HTTPRedirectHandler, Request, build_opener
|
||||
|
||||
from .telemetry import log
|
||||
|
||||
SCOPES = {"api-a": "api", "api-b": "api", "publisher": "publisher",
|
||||
"worker": "worker", "recovery": "recovery"}
|
||||
|
||||
|
||||
class CredentialsUnavailable(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class RefreshError(Exception):
|
||||
def __init__(self, operation, reason, status=None):
|
||||
self.operation = operation
|
||||
self.reason = reason
|
||||
self.status = status
|
||||
|
||||
|
||||
class NoRedirect(HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
return None
|
||||
|
||||
|
||||
class CredentialSource:
|
||||
def __init__(self):
|
||||
self.snapshot = {}
|
||||
self.valid_until = 0
|
||||
self.token = None
|
||||
self.renew_at = self.token_until = 0
|
||||
self.lock = Lock()
|
||||
self.stop = Event()
|
||||
self.last_failure = None
|
||||
|
||||
def request(self, path, operation, data=None):
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if self.token and operation != "login":
|
||||
headers["X-Vault-Token"] = self.token
|
||||
request = Request(self.address + "/v1/" + path,
|
||||
data=None if data is None else json.dumps(data).encode(),
|
||||
headers=headers)
|
||||
try:
|
||||
with self.opener.open(request, timeout=2) as response:
|
||||
return json.load(response)
|
||||
except HTTPError as exc:
|
||||
with exc:
|
||||
reason = "forbidden" if exc.code == 403 else "http_error"
|
||||
if exc.code == 404 and operation == "kv":
|
||||
reason = "kv_missing"
|
||||
elif exc.code == 400 and operation == "login":
|
||||
reason = "certificate_auth_rejected"
|
||||
elif exc.code == 429 or exc.code >= 500:
|
||||
reason = "unavailable"
|
||||
raise RefreshError(operation, reason, exc.code) from None
|
||||
except (URLError, OSError) as exc:
|
||||
cause = exc.reason if isinstance(exc, URLError) else exc
|
||||
reason = "tls_error" if isinstance(cause, ssl.SSLError) else "unavailable"
|
||||
raise RefreshError(operation, reason) from None
|
||||
except ValueError:
|
||||
raise RefreshError(operation, "invalid_response") from None
|
||||
|
||||
def set_token(self, response, operation):
|
||||
try:
|
||||
auth = response["auth"]
|
||||
token, lease = auth["client_token"], auth["lease_duration"]
|
||||
if not isinstance(token, str) or not token or type(lease) is not int or lease <= 0:
|
||||
raise ValueError
|
||||
except (TypeError, KeyError, ValueError):
|
||||
raise RefreshError(operation, "invalid_response") from None
|
||||
now = monotonic()
|
||||
self.token = token
|
||||
self.token_until = now + lease
|
||||
self.renew_at = now + lease * 0.6
|
||||
|
||||
def refresh(self):
|
||||
if self.token and monotonic() >= self.token_until:
|
||||
self.token = None
|
||||
if self.token and monotonic() >= self.renew_at:
|
||||
try:
|
||||
self.set_token(self.request("auth/token/renew-self", "renew", {}), "renew")
|
||||
except RefreshError as exc:
|
||||
if exc.status not in (400, 403):
|
||||
raise
|
||||
self.token = None
|
||||
self.report_failure(exc)
|
||||
if not self.token:
|
||||
response = self.request("auth/cert/login", "login", {"name": self.role})
|
||||
self.set_token(response, "login")
|
||||
try:
|
||||
document = self.request("kv/data/messenger/" + self.scope, "kv")["data"]
|
||||
contents = document["data"]
|
||||
fields = ("database_url",) if self.scope == "publisher" else (
|
||||
"database_url", "s3_user", "s3_password"
|
||||
)
|
||||
if any(not isinstance(contents[key], str) or not contents[key] for key in fields):
|
||||
raise ValueError
|
||||
snapshot = {key: contents[key] for key in fields}
|
||||
snapshot["version"] = document["metadata"]["version"]
|
||||
except RefreshError as exc:
|
||||
if exc.status == 403:
|
||||
self.token = None
|
||||
raise
|
||||
except (KeyError, TypeError, ValueError):
|
||||
raise RefreshError("kv", "invalid_response") from None
|
||||
with self.lock:
|
||||
self.snapshot = snapshot
|
||||
self.valid_until = monotonic() + self.max_age
|
||||
|
||||
def report_failure(self, exc):
|
||||
failure = (exc.operation, exc.reason, exc.status)
|
||||
if failure != self.last_failure:
|
||||
log("openbao_credentials_failure", logging.WARNING, role=self.role,
|
||||
operation=exc.operation, reason=exc.reason, http_status=exc.status)
|
||||
self.last_failure = failure
|
||||
|
||||
def refresh_once(self):
|
||||
try:
|
||||
self.refresh()
|
||||
except RefreshError as exc:
|
||||
if exc.reason in ("forbidden", "kv_missing", "invalid_response", "certificate_auth_rejected"):
|
||||
with self.lock:
|
||||
self.snapshot = {}
|
||||
self.valid_until = 0
|
||||
self.report_failure(exc)
|
||||
else:
|
||||
if self.last_failure is not None:
|
||||
log("openbao_credentials_restored", role=self.role)
|
||||
self.last_failure = None
|
||||
|
||||
def run(self):
|
||||
while not self.stop.wait(self.interval):
|
||||
self.refresh_once()
|
||||
|
||||
def start(self):
|
||||
self.role = os.environ.get("BAO_ROLE")
|
||||
if not self.role:
|
||||
return # Only migration/operator commands use dedicated local files.
|
||||
self.scope = SCOPES.get(self.role)
|
||||
if not self.scope or os.environ.get("BAO_SCOPE", self.scope) != self.scope:
|
||||
raise ValueError("Invalid OpenBao role/scope mapping")
|
||||
self.address = os.environ["BAO_ADDR"].rstrip("/")
|
||||
if not self.address.startswith("https://"):
|
||||
raise ValueError("OpenBao must use HTTPS")
|
||||
self.max_age = float(os.getenv("CREDENTIAL_MAX_AGE", "30"))
|
||||
self.interval = float(os.getenv("CREDENTIAL_REFRESH_SECONDS", "2"))
|
||||
if any(not isfinite(value) or value <= 0 for value in (self.max_age, self.interval)):
|
||||
raise ValueError("OpenBao refresh intervals must be finite and positive")
|
||||
try:
|
||||
context = ssl.create_default_context(cafile=os.environ["TLS_CA_FILE"])
|
||||
context.load_cert_chain("/run/identity/bao.crt", "/run/identity/bao.key")
|
||||
except OSError:
|
||||
self.report_failure(RefreshError("startup", "tls_configuration"))
|
||||
raise CredentialsUnavailable("OpenBao TLS configuration is unusable") from None
|
||||
self.opener = build_opener(NoRedirect(), HTTPSHandler(context=context))
|
||||
self.stop.clear()
|
||||
self.refresh_once()
|
||||
Thread(target=self.run, daemon=True, name="openbao-refresh").start()
|
||||
|
||||
def get(self):
|
||||
with self.lock:
|
||||
if monotonic() >= self.valid_until:
|
||||
raise CredentialsUnavailable("Рабочие учётные данные недоступны")
|
||||
return self.snapshot.copy()
|
||||
|
||||
|
||||
credentials = CredentialSource()
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
"""Role-scoped TLS database pools with generation switching and graceful draining."""
|
||||
from contextlib import contextmanager
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
from threading import Lock
|
||||
|
||||
from opentelemetry.metrics import Observation
|
||||
from psycopg import Cursor
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg_pool import ConnectionPool
|
||||
|
||||
from .credentials import credentials
|
||||
from .telemetry import meter, span
|
||||
|
||||
|
||||
class TracedCursor(Cursor):
|
||||
def execute(self, query, params=None, **kwargs):
|
||||
with span("postgresql.execute", attributes={"db.system.name": "postgresql"}):
|
||||
return super().execute(query, params, **kwargs)
|
||||
|
||||
|
||||
def get_database_url():
|
||||
return Path(os.environ["DATABASE_URL_FILE"]).read_text().strip()
|
||||
|
||||
|
||||
@dataclass
|
||||
class Generation:
|
||||
conninfo: str
|
||||
pool: ConnectionPool
|
||||
borrowers: int = 0
|
||||
retired: bool = False
|
||||
|
||||
|
||||
active = None
|
||||
lock = Lock()
|
||||
logging.getLogger("psycopg.pool").setLevel(logging.CRITICAL)
|
||||
|
||||
|
||||
def pool_stat(name):
|
||||
def observe(_):
|
||||
generation = active
|
||||
if generation is None:
|
||||
return [Observation(0)]
|
||||
stats = generation.pool.get_stats()
|
||||
value = stats["pool_size"] - stats["pool_available"] if name == "used" else stats.get(name, 0)
|
||||
return [Observation(value)]
|
||||
return observe
|
||||
|
||||
|
||||
def open_database():
|
||||
for metric, stat in (("used", "used"), ("waiting", "requests_waiting"), ("capacity", "pool_max")):
|
||||
meter.create_observable_gauge("lab_db_pool_" + metric, callbacks=[pool_stat(stat)])
|
||||
credentials.start()
|
||||
|
||||
|
||||
def close_database():
|
||||
credentials.stop.set()
|
||||
with lock:
|
||||
if active is not None:
|
||||
active.pool.close()
|
||||
|
||||
|
||||
def acquire():
|
||||
global active
|
||||
with lock:
|
||||
conninfo = credentials.get()["database_url"] if os.getenv("BAO_ROLE") else get_database_url()
|
||||
if active is None or active.conninfo != conninfo:
|
||||
pool = ConnectionPool(
|
||||
conninfo, min_size=1, max_size=int(os.getenv("DB_POOL_SIZE", "10")),
|
||||
timeout=5, open=False,
|
||||
kwargs={"row_factory": dict_row, "cursor_factory": TracedCursor,
|
||||
"connect_timeout": 3, "options": "-c statement_timeout=5000"},
|
||||
)
|
||||
try:
|
||||
pool.open(wait=True, timeout=5)
|
||||
except BaseException:
|
||||
pool.close()
|
||||
raise
|
||||
previous, active = active, Generation(conninfo, pool)
|
||||
if previous:
|
||||
previous.retired = True
|
||||
if previous.borrowers == 0:
|
||||
previous.pool.close()
|
||||
active.borrowers += 1
|
||||
return active
|
||||
|
||||
|
||||
@contextmanager
|
||||
def get_connection():
|
||||
generation = acquire()
|
||||
try:
|
||||
manager = generation.pool.connection()
|
||||
with span("postgresql.pool.acquire"):
|
||||
connection = manager.__enter__()
|
||||
try:
|
||||
yield connection
|
||||
except BaseException:
|
||||
with span("postgresql.transaction.rollback"):
|
||||
manager.__exit__(*sys.exc_info())
|
||||
raise
|
||||
else:
|
||||
with span("postgresql.transaction.close"):
|
||||
manager.__exit__(None, None, None)
|
||||
finally:
|
||||
with lock:
|
||||
generation.borrowers -= 1
|
||||
if generation.retired and generation.borrowers == 0:
|
||||
generation.pool.close()
|
||||
@@ -0,0 +1,44 @@
|
||||
"""One-shot fault controls, enabled only by the operator on a disposable stand."""
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
|
||||
from .database import get_connection
|
||||
from .telemetry import log
|
||||
|
||||
ENABLED = os.getenv('PIPELINE_FAULTS') == '1'
|
||||
|
||||
|
||||
def take(conn, attachment_id, version, point):
|
||||
if not ENABLED:
|
||||
return None
|
||||
row = conn.execute("""
|
||||
UPDATE pipeline_faults SET hit_at=clock_timestamp()
|
||||
WHERE attachment_id=%s AND pipeline_version=%s AND point=%s AND hit_at IS NULL
|
||||
RETURNING action
|
||||
""", (attachment_id, version, point)).fetchone()
|
||||
return row['action'] if row else None
|
||||
|
||||
|
||||
def checkpoint(job, point):
|
||||
if not ENABLED:
|
||||
return None
|
||||
key = (job['attachment_id'], job['pipeline_version'], point)
|
||||
with get_connection() as conn:
|
||||
action = take(conn, *key)
|
||||
if action == 'crash':
|
||||
log('pipeline_fault', logging.WARNING, point=point, action='crash', job_id=str(job['id']))
|
||||
os._exit(86)
|
||||
if action == 'pause':
|
||||
log('pipeline_fault', logging.WARNING, point=point, action='pause', job_id=str(job['id']))
|
||||
deadline = time.monotonic() + 90
|
||||
while time.monotonic() < deadline:
|
||||
with get_connection() as conn:
|
||||
row = conn.execute("""
|
||||
SELECT released FROM pipeline_faults
|
||||
WHERE attachment_id=%s AND pipeline_version=%s AND point=%s
|
||||
""", key).fetchone()
|
||||
if row is None or row['released']:
|
||||
break
|
||||
time.sleep(0.1)
|
||||
return action
|
||||
@@ -0,0 +1,25 @@
|
||||
"""Isolated image decoder: bounded address space, CPU and parent wall timeout."""
|
||||
import resource
|
||||
import sys
|
||||
import warnings
|
||||
|
||||
if sys.platform.startswith('linux'):
|
||||
resource.setrlimit(resource.RLIMIT_AS, (512 * 1024**2, 512 * 1024**2))
|
||||
resource.setrlimit(resource.RLIMIT_CPU, (8, 8))
|
||||
from PIL import Image
|
||||
Image.MAX_IMAGE_PIXELS = 40_000_000
|
||||
warnings.simplefilter('error', Image.DecompressionBombWarning)
|
||||
try:
|
||||
with Image.open(sys.argv[1], formats=("PNG", "JPEG")) as image:
|
||||
if image.width * image.height > 40_000_000:
|
||||
sys.exit(13)
|
||||
actual = {'PNG': 'image/png', 'JPEG': 'image/jpeg'}.get(image.format)
|
||||
if actual != sys.argv[2] or getattr(image, 'n_frames', 1) != 1:
|
||||
sys.exit(15)
|
||||
image.verify()
|
||||
with Image.open(sys.argv[1], formats=("PNG", "JPEG")) as image:
|
||||
image.load()
|
||||
except (Image.DecompressionBombError, Image.DecompressionBombWarning):
|
||||
sys.exit(13)
|
||||
except Exception:
|
||||
sys.exit(15)
|
||||
+164
@@ -0,0 +1,164 @@
|
||||
"""PostgreSQL owns execution state and the publication pointer."""
|
||||
import os
|
||||
import random
|
||||
|
||||
from psycopg.types.json import Jsonb
|
||||
|
||||
from .database import get_connection
|
||||
from .telemetry import propagator, span
|
||||
|
||||
MAX_ATTEMPTS = int(os.getenv('JOB_MAX_ATTEMPTS', '5'))
|
||||
LEASE_SECONDS = int(os.getenv('JOB_TIMEOUT_SECONDS', '60'))
|
||||
|
||||
|
||||
def enqueue(conn, attachment_id, version, *, accepted=False):
|
||||
context = {}
|
||||
propagator.inject(context)
|
||||
job = conn.execute("""
|
||||
INSERT INTO image_jobs(attachment_id,pipeline_version,trace_context,accepted_at)
|
||||
VALUES (%s,%s,%s,CASE WHEN %s THEN clock_timestamp() END) RETURNING *
|
||||
""", (attachment_id, version, Jsonb(context), accepted)).fetchone()
|
||||
with span('outbox.enqueue'):
|
||||
schedule(conn, job['id'])
|
||||
return job
|
||||
|
||||
|
||||
def schedule(conn, job_id, delay=0):
|
||||
conn.execute('''
|
||||
INSERT INTO job_outbox(job_id,publish_after)
|
||||
VALUES (%s, clock_timestamp() + %s * interval '1 second')
|
||||
ON CONFLICT (job_id) DO UPDATE SET publish_after=excluded.publish_after
|
||||
''', (job_id, delay))
|
||||
|
||||
|
||||
def event(conn, job, name, detail=None):
|
||||
conn.execute('INSERT INTO job_events(job_id,attempt,event,detail) VALUES (%s,%s,%s,%s)',
|
||||
(job['id'], job['attempt'], name, detail))
|
||||
|
||||
|
||||
def carrier(job):
|
||||
return dict(schema_version=1, type='attachment.process.v1', job_id=str(job['id']),
|
||||
attachment_id=str(job['attachment_id']), pipeline_version=job['pipeline_version'],
|
||||
attempt=job['attempt'], created_at=job['created_at'].isoformat().replace('+00:00', 'Z'))
|
||||
|
||||
|
||||
def claim(message):
|
||||
with get_connection() as conn:
|
||||
job = conn.execute('SELECT * FROM image_jobs WHERE id=%s FOR NO KEY UPDATE',
|
||||
(message['job_id'],)).fetchone()
|
||||
if (job is None or job['attachment_id'] != message['attachment_id']
|
||||
or job['pipeline_version'] != message['pipeline_version']
|
||||
or job['attempt'] != message['attempt']):
|
||||
return None
|
||||
if job['state'] != 'queued':
|
||||
event(conn, job, 'delivery_ignored', job['state'])
|
||||
return None
|
||||
attachment = lock_attachment(conn, job)
|
||||
if attachment['desired_version'] != job['pipeline_version']:
|
||||
supersede(conn, job)
|
||||
return None
|
||||
job = conn.execute('''
|
||||
UPDATE image_jobs SET state='processing', fence=fence+1,
|
||||
lease_until=clock_timestamp() + %s * interval '1 second'
|
||||
WHERE id=%s RETURNING *
|
||||
''', (LEASE_SECONDS, job['id'])).fetchone()
|
||||
update_attachment(conn, job, 'processing')
|
||||
event(conn, job, 'claimed', str(job['fence']))
|
||||
return job, attachment
|
||||
|
||||
|
||||
def lock_attachment(conn, job):
|
||||
return conn.execute('SELECT * FROM attachments WHERE id=%s FOR NO KEY UPDATE',
|
||||
(job['attachment_id'],)).fetchone()
|
||||
|
||||
|
||||
def update_attachment(conn, job, state, error=None):
|
||||
# While building a new version, continue serving the previously published version.
|
||||
conn.execute('''
|
||||
UPDATE attachments SET status=%s, error_code=%s, updated_at=clock_timestamp()
|
||||
WHERE id=%s AND desired_version=%s AND active_version IS NULL
|
||||
''', (state, error, job['attachment_id'], job['pipeline_version']))
|
||||
|
||||
|
||||
def supersede(conn, job):
|
||||
conn.execute("UPDATE image_jobs SET state='superseded', lease_until=NULL WHERE id=%s", (job['id'],))
|
||||
event(conn, job, 'superseded')
|
||||
|
||||
|
||||
def owned(conn, job):
|
||||
current = conn.execute('''
|
||||
SELECT *, lease_until > clock_timestamp() AS live FROM image_jobs WHERE id=%s FOR NO KEY UPDATE
|
||||
''', (job['id'],)).fetchone()
|
||||
return current['state'] == 'processing' and current['fence'] == job['fence'] and current['live']
|
||||
|
||||
|
||||
def finish(job, manifest):
|
||||
with get_connection() as conn:
|
||||
if not owned(conn, job):
|
||||
event(conn, job, 'fence_rejected', str(job['fence']))
|
||||
return 'ignored', None
|
||||
attachment = lock_attachment(conn, job)
|
||||
if not owned(conn, job):
|
||||
event(conn, job, 'fence_rejected', str(job['fence']))
|
||||
return 'ignored', None
|
||||
if attachment['desired_version'] != job['pipeline_version']:
|
||||
supersede(conn, job)
|
||||
return 'ignored', None
|
||||
ready = conn.execute("""
|
||||
UPDATE image_jobs SET first_ready_at=clock_timestamp(), state='ready', manifest=%s, lease_until=NULL,error_code=NULL WHERE id=%s RETURNING first_ready_at
|
||||
""", (Jsonb(manifest), job['id'])).fetchone()
|
||||
conn.execute("""
|
||||
UPDATE attachments SET status='ready', active_version=%s, error_code=NULL,
|
||||
object_key=%s, updated_at=clock_timestamp() WHERE id=%s
|
||||
""", (job['pipeline_version'], manifest['original']['key'], attachment['id']))
|
||||
event(conn, job, 'published')
|
||||
latency = ((ready['first_ready_at'] - job['accepted_at']).total_seconds()
|
||||
if job['accepted_at'] else None)
|
||||
return 'ready', latency
|
||||
|
||||
|
||||
def fail_locked(conn, job, reason, permanent=False):
|
||||
attachment = lock_attachment(conn, job)
|
||||
if attachment['desired_version'] != job['pipeline_version']:
|
||||
supersede(conn, job)
|
||||
return 'ignored'
|
||||
failures = job['failures'] + 1
|
||||
if permanent or failures >= MAX_ATTEMPTS:
|
||||
code = reason if permanent else 'retry_exhausted'
|
||||
conn.execute("""
|
||||
UPDATE image_jobs SET state='failed', error_code=%s, lease_until=NULL, failures=%s WHERE id=%s
|
||||
""", (code, failures, job['id']))
|
||||
conn.execute('INSERT INTO job_dead_letters(job_id,attempt,error_code) VALUES (%s,%s,%s)',
|
||||
(job['id'], job['attempt'], code))
|
||||
update_attachment(conn, job, 'failed', code)
|
||||
event(conn, job, 'dead_letter', reason)
|
||||
return 'failed'
|
||||
delay = min(30, 2 ** (failures - 1)) * random.uniform(0.75, 1.25)
|
||||
conn.execute("""
|
||||
UPDATE image_jobs SET state='queued', attempt=attempt+1, failures=%s,
|
||||
lease_until=NULL,error_code=%s WHERE id=%s
|
||||
""", (failures, reason, job['id']))
|
||||
schedule(conn, job['id'], delay)
|
||||
update_attachment(conn, job, 'queued')
|
||||
event(conn, job, 'retry_scheduled', reason)
|
||||
return 'retry'
|
||||
|
||||
|
||||
def fail(job, reason, permanent=False):
|
||||
with get_connection() as conn:
|
||||
if owned(conn, job):
|
||||
return fail_locked(conn, job, reason, permanent)
|
||||
else:
|
||||
event(conn, job, 'fence_rejected', str(job['fence']))
|
||||
return 'ignored'
|
||||
|
||||
|
||||
def recover_one():
|
||||
with get_connection() as conn:
|
||||
job = conn.execute("""
|
||||
SELECT * FROM image_jobs WHERE state='processing' AND lease_until <= clock_timestamp()
|
||||
ORDER BY lease_until LIMIT 1 FOR NO KEY UPDATE SKIP LOCKED
|
||||
""").fetchone()
|
||||
if job:
|
||||
fail_locked(conn, job, 'lease_expired')
|
||||
return job is not None
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Shared admission budget and a separate per-process limit on expensive hashes."""
|
||||
from contextlib import contextmanager
|
||||
import os
|
||||
from threading import BoundedSemaphore
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
from .database import get_connection
|
||||
|
||||
WINDOW = int(os.getenv("LOGIN_WINDOW_SECONDS", "10"))
|
||||
LIMIT = int(os.getenv("LOGIN_WINDOW_LIMIT", "40"))
|
||||
KDF_SLOTS = int(os.getenv("LOGIN_KDF_SLOTS", "2"))
|
||||
if min(WINDOW, LIMIT, KDF_SLOTS) < 1:
|
||||
raise ValueError("Login budgets must be positive")
|
||||
SLOTS = BoundedSemaphore(KDF_SLOTS)
|
||||
|
||||
|
||||
def limited(wait):
|
||||
return HTTPException(429, "Слишком много попыток", headers={"Retry-After": str(wait)})
|
||||
|
||||
|
||||
def admit():
|
||||
with get_connection() as conn:
|
||||
# Sample the DB clock after admission is serialized across replicas.
|
||||
conn.execute("SELECT pg_advisory_xact_lock(70702)")
|
||||
now = conn.execute("SELECT floor(extract(epoch FROM clock_timestamp()))::bigint AS n").fetchone()["n"]
|
||||
bucket = now // WINDOW
|
||||
row = conn.execute("""
|
||||
INSERT INTO login_limits(scope, bucket, attempts) VALUES ('login', %s, 1)
|
||||
ON CONFLICT(scope, bucket) DO UPDATE SET attempts = login_limits.attempts + 1
|
||||
WHERE login_limits.attempts < %s RETURNING attempts
|
||||
""", (bucket, LIMIT)).fetchone()
|
||||
if row and row["attempts"] == 1:
|
||||
conn.execute("DELETE FROM login_limits WHERE bucket < %s", (bucket - 1,))
|
||||
if row is None:
|
||||
raise limited(WINDOW - now % WINDOW)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def kdf_slot():
|
||||
if not SLOTS.acquire(blocking=False):
|
||||
raise limited(1)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
SLOTS.release()
|
||||
+522
@@ -0,0 +1,522 @@
|
||||
"""Мессенджер: PostgreSQL хранит данные и сессии."""
|
||||
|
||||
import base64
|
||||
import binascii
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from fastapi import FastAPI, HTTPException, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
|
||||
|
||||
from psycopg import OperationalError, Error as DatabaseError
|
||||
from psycopg_pool import PoolTimeout
|
||||
|
||||
from .auth import (
|
||||
create_token,
|
||||
format_datetime,
|
||||
hash_password,
|
||||
hash_token,
|
||||
parse_basic,
|
||||
parse_bearer,
|
||||
session_expiration,
|
||||
verify_password,
|
||||
password_hasher,
|
||||
)
|
||||
from .credentials import CredentialsUnavailable
|
||||
from .login_limits import admit, kdf_slot
|
||||
from .telemetry import HTTP, INSTANCE_ID, configure
|
||||
from .database import open_database, close_database, get_connection
|
||||
from .user_repository import (
|
||||
create_user as insert_user,
|
||||
create_session,
|
||||
find_session_user,
|
||||
find_user_by_username,
|
||||
revoke_session,
|
||||
replace_password_hash,
|
||||
serialize_user,
|
||||
)
|
||||
|
||||
from .chat_repository import (
|
||||
create_chat as insert_chat,
|
||||
get_chat as find_chat,
|
||||
list_chats as find_chats,
|
||||
create_message as insert_message,
|
||||
list_messages as find_messages,
|
||||
)
|
||||
|
||||
app = FastAPI(title="MTUSI Messenger", version="1.7.0")
|
||||
# Serve the mandatory contract in Swagger, including auth and request schemas.
|
||||
OPENAPI_SCHEMA = json.loads(
|
||||
(Path(__file__).resolve().parents[1] / "contracts/openapi.json").read_text()
|
||||
)
|
||||
app.openapi = lambda: OPENAPI_SCHEMA
|
||||
|
||||
configure("api")
|
||||
DUMMY_HASH = hash_password(create_token())
|
||||
|
||||
ERROR_CODES = {
|
||||
400: "invalid_request",
|
||||
401: "unauthorized",
|
||||
404: "not_found",
|
||||
409: "conflict",
|
||||
413: "payload_too_large",
|
||||
415: "unsupported_media_type",
|
||||
429: "rate_limited",
|
||||
500: "internal_error",
|
||||
503: "unavailable",
|
||||
}
|
||||
|
||||
|
||||
def error_response(request, status_code, code, message):
|
||||
return JSONResponse(
|
||||
status_code=status_code,
|
||||
content={
|
||||
"error": {
|
||||
"code": code,
|
||||
"message": message,
|
||||
"request_id": request.state.request_id,
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def request_id_middleware(request: Request, call_next):
|
||||
request.state.request_id = str(uuid4())
|
||||
try:
|
||||
response = await call_next(request)
|
||||
except Exception:
|
||||
response = error_response(
|
||||
request, 500, "internal_error", "Внутренняя ошибка сервера"
|
||||
)
|
||||
response.headers["X-Request-Id"] = request.state.request_id
|
||||
response.headers["X-Instance-Id"] = INSTANCE_ID
|
||||
return response
|
||||
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def http_error_handler(request: Request, exc: StarletteHTTPException):
|
||||
response = error_response(
|
||||
request,
|
||||
exc.status_code,
|
||||
ERROR_CODES.get(exc.status_code, "invalid_request"),
|
||||
str(exc.detail),
|
||||
)
|
||||
if exc.headers:
|
||||
response.headers.update(exc.headers)
|
||||
return response
|
||||
|
||||
|
||||
@app.exception_handler(CredentialsUnavailable)
|
||||
@app.exception_handler(DatabaseError)
|
||||
@app.exception_handler(PoolTimeout)
|
||||
async def database_error_handler(request: Request, exc):
|
||||
return error_response(request, 503, "unavailable", "База данных временно недоступна")
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_error_handler(request: Request, exc: RequestValidationError):
|
||||
return error_response(request, 400, "invalid_request", "Некорректные данные запроса")
|
||||
|
||||
|
||||
async def read_json(request: Request):
|
||||
"""415 — только для неправильного Content-Type; 400 — для неверного JSON."""
|
||||
content_type = (
|
||||
request.headers.get("content-type", "").split(";")[0].strip().lower()
|
||||
)
|
||||
if content_type != "application/json":
|
||||
raise HTTPException(415, "Неподдерживаемый Content-Type")
|
||||
|
||||
try:
|
||||
raw = bytearray()
|
||||
async for chunk in request.stream():
|
||||
if len(raw) + len(chunk) > 65536:
|
||||
raise HTTPException(413, "JSON слишком большой")
|
||||
raw.extend(chunk)
|
||||
data = json.loads(raw)
|
||||
except (ValueError, UnicodeError):
|
||||
raise HTTPException(400, "Неверный JSON") from None
|
||||
|
||||
# [], строка, число, true, false, null — это корректный JSON,
|
||||
# но НЕ объект, обязательный по контракту.
|
||||
if not isinstance(data, dict):
|
||||
raise HTTPException(400, "Ожидается JSON-объект")
|
||||
return data
|
||||
|
||||
|
||||
def get_current_user(request: Request):
|
||||
token = parse_bearer(request.headers.get("Authorization"))
|
||||
if token is None:
|
||||
raise HTTPException(
|
||||
401,
|
||||
"Требуется действующий Bearer-токен",
|
||||
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
|
||||
)
|
||||
|
||||
try:
|
||||
user = find_session_user(hash_token(token))
|
||||
except (OperationalError, PoolTimeout):
|
||||
raise HTTPException(
|
||||
503,
|
||||
"База данных временно недоступна",
|
||||
) from None
|
||||
if user is None:
|
||||
raise HTTPException(
|
||||
401,
|
||||
"Недействительная или истёкшая сессия",
|
||||
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
|
||||
)
|
||||
|
||||
return user
|
||||
|
||||
|
||||
def get_limit(request: Request):
|
||||
"""Проверяем длину ДО int(): 5000 цифр должны дать 400, а не 500."""
|
||||
limit_raw = request.query_params.get("limit", "50")
|
||||
if not limit_raw.isascii() or not limit_raw.isdecimal():
|
||||
raise HTTPException(400, "Неверный limit")
|
||||
|
||||
significant = limit_raw.lstrip("0")
|
||||
if not significant or len(significant) > 3:
|
||||
raise HTTPException(400, "Неверный limit")
|
||||
|
||||
limit = int(significant) # Теперь строка содержит максимум 3 цифры.
|
||||
if not 1 <= limit <= 100:
|
||||
raise HTTPException(400, "limit должен быть от 1 до 100")
|
||||
return limit
|
||||
|
||||
|
||||
def encode_cursor(first_id, last_id):
|
||||
raw = f"{first_id}|{last_id}".encode("ascii")
|
||||
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
|
||||
|
||||
|
||||
def decode_cursor(cursor):
|
||||
try:
|
||||
if not cursor or len(cursor) > 256:
|
||||
raise ValueError("empty or too long")
|
||||
padded = cursor + "=" * (-len(cursor) % 4)
|
||||
raw = base64.b64decode(
|
||||
padded, altchars=b"-_", validate=True
|
||||
).decode("ascii")
|
||||
first_id, last_id = raw.split("|")
|
||||
return str(UUID(first_id)), str(UUID(last_id))
|
||||
except (ValueError, UnicodeError, binascii.Error):
|
||||
raise HTTPException(400, "Неверный cursor") from None
|
||||
|
||||
|
||||
# ---- Health ----
|
||||
|
||||
@app.get("/health/live")
|
||||
def health_live():
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.get("/health/ready")
|
||||
def health_ready():
|
||||
try:
|
||||
with get_connection() as conn:
|
||||
conn.execute("SELECT 1")
|
||||
from .storage import s3, BUCKET
|
||||
s3.list_objects_v2(Bucket=BUCKET, Prefix="originals/", MaxKeys=1)
|
||||
except (OperationalError, PoolTimeout):
|
||||
raise HTTPException(503, "База данных недоступна") from None
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
# ---- Users ----
|
||||
|
||||
@app.post("/api/v1/users", status_code=201)
|
||||
async def create_user(request: Request):
|
||||
data = await read_json(request)
|
||||
|
||||
if set(data) != {"username", "display_name", "password"}:
|
||||
raise HTTPException(400, "Неверные поля пользователя")
|
||||
|
||||
username = data["username"]
|
||||
display_name = data["display_name"]
|
||||
password = data["password"]
|
||||
|
||||
if not isinstance(username, str) or not re.fullmatch(
|
||||
r"[a-z0-9_]{3,32}", username
|
||||
):
|
||||
raise HTTPException(400, "Недопустимый username")
|
||||
|
||||
if (
|
||||
not isinstance(display_name, str)
|
||||
or not 1 <= len(display_name) <= 100
|
||||
or not display_name.strip()
|
||||
):
|
||||
raise HTTPException(400, "Недопустимое имя пользователя")
|
||||
|
||||
if not isinstance(password, str) or not 12 <= len(password) <= 128:
|
||||
raise HTTPException(400, "Пароль должен содержать 12–128 символов")
|
||||
|
||||
def bounded_hash():
|
||||
with kdf_slot():
|
||||
return hash_password(password)
|
||||
|
||||
password_hash = await run_in_threadpool(bounded_hash)
|
||||
user = await run_in_threadpool(insert_user, username, display_name, password_hash)
|
||||
if user is None:
|
||||
raise HTTPException(409, "Username уже занят")
|
||||
|
||||
return user
|
||||
|
||||
|
||||
@app.get("/api/v1/users/me")
|
||||
def get_me(request: Request):
|
||||
return get_current_user(request)
|
||||
|
||||
|
||||
@app.post("/api/v1/auth/sessions", status_code=201)
|
||||
def login(request: Request):
|
||||
admit()
|
||||
credentials = parse_basic(request.headers.get("Authorization"))
|
||||
|
||||
if credentials is None:
|
||||
raise HTTPException(
|
||||
401,
|
||||
"Неверные учётные данные",
|
||||
headers={
|
||||
"WWW-Authenticate":
|
||||
'Basic realm="messenger", charset="UTF-8"'
|
||||
},
|
||||
)
|
||||
|
||||
username, password = credentials
|
||||
user_row = find_user_by_username(username)
|
||||
|
||||
with kdf_slot():
|
||||
password_hash = user_row["password_hash"] if user_row else DUMMY_HASH
|
||||
valid = verify_password(password_hash, password)
|
||||
replacement = (
|
||||
hash_password(password)
|
||||
if user_row and valid and password_hasher.check_needs_rehash(password_hash)
|
||||
else None
|
||||
)
|
||||
if not user_row or not valid:
|
||||
raise HTTPException(
|
||||
401, "Неверные учётные данные",
|
||||
headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'},
|
||||
)
|
||||
if replacement is not None:
|
||||
replace_password_hash(user_row["id"], password_hash, replacement)
|
||||
|
||||
token = create_token()
|
||||
expires_at = session_expiration()
|
||||
|
||||
create_session(user_row["id"], hash_token(token), expires_at)
|
||||
|
||||
return {
|
||||
"token": token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": format_datetime(expires_at),
|
||||
"user": serialize_user(user_row),
|
||||
}
|
||||
|
||||
|
||||
@app.delete("/api/v1/auth/sessions/current", status_code=204)
|
||||
def logout(request: Request):
|
||||
get_current_user(request)
|
||||
token = parse_bearer(request.headers.get("Authorization"))
|
||||
|
||||
if not revoke_session(hash_token(token)):
|
||||
raise HTTPException(
|
||||
401,
|
||||
"Недействительная сессия",
|
||||
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
|
||||
)
|
||||
|
||||
from fastapi import Response
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
|
||||
# ---- Chats ----
|
||||
|
||||
|
||||
@app.post("/api/v1/chats", status_code=201)
|
||||
async def create_chat(request: Request):
|
||||
user = await run_in_threadpool(get_current_user, request)
|
||||
data = await read_json(request)
|
||||
|
||||
if set(data) != {"title", "member_ids"}:
|
||||
raise HTTPException(400, "Неверные поля чата")
|
||||
|
||||
title = data["title"]
|
||||
member_ids = data["member_ids"]
|
||||
|
||||
if not isinstance(title, str) or not 1 <= len(title) <= 100 or not title.strip():
|
||||
raise HTTPException(400, "Недопустимое название чата")
|
||||
|
||||
if not isinstance(member_ids, list) or not 1 <= len(member_ids) <= 100:
|
||||
raise HTTPException(400, "Неверный список участников")
|
||||
|
||||
normalized_ids = []
|
||||
|
||||
for member_id in member_ids:
|
||||
if not isinstance(member_id, str):
|
||||
raise HTTPException(400, "Неверный ID участника")
|
||||
|
||||
try:
|
||||
normalized_ids.append(str(UUID(member_id)))
|
||||
except ValueError:
|
||||
raise HTTPException(400, "Неверный UUID участника") from None
|
||||
|
||||
if len(normalized_ids) != len(set(normalized_ids)):
|
||||
raise HTTPException(400, "Участники повторяются")
|
||||
|
||||
if user["id"] not in normalized_ids:
|
||||
raise HTTPException(400, "Создатель должен быть участником")
|
||||
|
||||
chat = await run_in_threadpool(insert_chat, user["id"], title, normalized_ids)
|
||||
|
||||
if chat is None:
|
||||
raise HTTPException(400, "Неизвестный участник")
|
||||
|
||||
return chat
|
||||
|
||||
|
||||
@app.get("/api/v1/chats")
|
||||
def list_chats(request: Request):
|
||||
user = get_current_user(request)
|
||||
limit = get_limit(request)
|
||||
cursor = request.query_params.get("cursor")
|
||||
|
||||
last_chat_id = None
|
||||
|
||||
if cursor is not None:
|
||||
cursor_user_id, last_chat_id = decode_cursor(cursor)
|
||||
|
||||
if cursor_user_id != user["id"]:
|
||||
raise HTTPException(400, "Неверный cursor")
|
||||
|
||||
rows = find_chats(user["id"], limit, last_chat_id)
|
||||
|
||||
if rows is None:
|
||||
raise HTTPException(400, "Неверный cursor")
|
||||
|
||||
has_more = len(rows) > limit
|
||||
page = rows[:limit]
|
||||
|
||||
next_cursor = (
|
||||
encode_cursor(user["id"], page[-1]["id"])
|
||||
if has_more and page
|
||||
else None
|
||||
)
|
||||
|
||||
return {"items": page, "next_cursor": next_cursor}
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}")
|
||||
def get_chat(chat_id: str, request: Request):
|
||||
user = get_current_user(request)
|
||||
|
||||
try:
|
||||
chat_id = str(UUID(chat_id))
|
||||
except ValueError:
|
||||
raise HTTPException(400, "Неверный UUID чата") from None
|
||||
|
||||
chat = find_chat(chat_id, user["id"])
|
||||
|
||||
if chat is None:
|
||||
raise HTTPException(404, "Чат не найден")
|
||||
|
||||
return chat
|
||||
|
||||
|
||||
# ---- Messages ----
|
||||
|
||||
|
||||
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
|
||||
async def send_message(chat_id: str, request: Request):
|
||||
user = await run_in_threadpool(get_current_user, request)
|
||||
chat = await run_in_threadpool(get_chat, chat_id, request)
|
||||
data = await read_json(request)
|
||||
|
||||
if "text" not in data or set(data) - {"text", "attachment_ids"}:
|
||||
raise HTTPException(400, "Неверные поля сообщения")
|
||||
|
||||
text = data["text"]
|
||||
|
||||
attachment_ids = data.get("attachment_ids", [])
|
||||
if not isinstance(attachment_ids, list) or len(attachment_ids) > 10:
|
||||
raise HTTPException(400, "Неверный список вложений")
|
||||
try:
|
||||
if any(not isinstance(a, str) for a in attachment_ids):
|
||||
raise ValueError()
|
||||
attachment_ids = [str(UUID(a)) for a in attachment_ids]
|
||||
if len(set(attachment_ids)) != len(attachment_ids):
|
||||
raise ValueError()
|
||||
except ValueError:
|
||||
raise HTTPException(400, "Неверные ID вложений") from None
|
||||
if not isinstance(text, str) or len(text) > 4000 or (not text.strip() and not attachment_ids):
|
||||
raise HTTPException(400, "Недопустимый текст сообщения")
|
||||
|
||||
key = request.headers.get("Idempotency-Key", "")
|
||||
if not re.fullmatch(r"[A-Za-z0-9._:-]{1,128}", key):
|
||||
raise HTTPException(400, "Неверный Idempotency-Key")
|
||||
message = await run_in_threadpool(insert_message, chat["id"], user["id"], text, key, attachment_ids)
|
||||
if message == "attachment_failed":
|
||||
raise HTTPException(409, "Обработка вложения завершилась ошибкой")
|
||||
if message == "conflict":
|
||||
raise HTTPException(409, "Ключ использован для другого сообщения")
|
||||
|
||||
if message is None:
|
||||
raise HTTPException(404, "Чат не найден")
|
||||
|
||||
return message
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}/messages")
|
||||
def list_messages(chat_id: str, request: Request):
|
||||
chat = get_chat(chat_id, request)
|
||||
limit = get_limit(request)
|
||||
cursor = request.query_params.get("cursor")
|
||||
|
||||
last_message_id = None
|
||||
|
||||
if cursor is not None:
|
||||
cursor_chat_id, last_message_id = decode_cursor(cursor)
|
||||
|
||||
if cursor_chat_id != chat["id"]:
|
||||
raise HTTPException(400, "Неверный cursor")
|
||||
|
||||
rows = find_messages(chat["id"], limit, last_message_id)
|
||||
|
||||
if rows is None:
|
||||
raise HTTPException(400, "Неверный cursor")
|
||||
|
||||
has_more = len(rows) > limit
|
||||
page = rows[:limit]
|
||||
|
||||
next_cursor = (
|
||||
encode_cursor(chat["id"], page[-1]["id"])
|
||||
if has_more and page
|
||||
else None
|
||||
)
|
||||
|
||||
return {"items": page, "next_cursor": next_cursor}
|
||||
|
||||
|
||||
@app.on_event("startup")
|
||||
async def start_database_pool():
|
||||
await run_in_threadpool(open_database)
|
||||
|
||||
|
||||
@app.on_event("shutdown")
|
||||
async def stop_database_pool():
|
||||
await run_in_threadpool(close_database)
|
||||
|
||||
from .attachments import register
|
||||
register(app, get_current_user, get_chat)
|
||||
|
||||
app.add_middleware(HTTP)
|
||||
@@ -0,0 +1,16 @@
|
||||
"""One-shot migrations, serialized and recorded in PostgreSQL."""
|
||||
from pathlib import Path
|
||||
import psycopg
|
||||
from .database import get_database_url
|
||||
|
||||
with psycopg.connect(get_database_url()) as conn:
|
||||
with conn.transaction():
|
||||
conn.execute("SELECT pg_advisory_xact_lock(310026)")
|
||||
conn.execute("CREATE TABLE IF NOT EXISTS schema_migrations(name TEXT PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW())")
|
||||
for path in sorted((Path(__file__).resolve().parents[1] / "db/migrations").glob("*.sql")):
|
||||
if not conn.execute("SELECT 1 FROM schema_migrations WHERE name=%s", (path.name,)).fetchone():
|
||||
conn.execute(path.read_text())
|
||||
conn.execute("INSERT INTO schema_migrations(name) VALUES (%s)", (path.name,))
|
||||
print("Applied", path.name, flush=True)
|
||||
else:
|
||||
print("Already applied", path.name, flush=True)
|
||||
@@ -0,0 +1,91 @@
|
||||
"""Local administrative commands. Run from the trusted Compose project."""
|
||||
import argparse
|
||||
import json
|
||||
|
||||
from .broker import channel, send
|
||||
from .database import close_database, get_connection, open_database
|
||||
from .jobs import carrier, enqueue, event, schedule
|
||||
|
||||
|
||||
def reprocess(attachment_id, version):
|
||||
with get_connection() as conn:
|
||||
row = conn.execute('SELECT * FROM attachments WHERE id=%s FOR NO KEY UPDATE', (attachment_id,)).fetchone()
|
||||
if not row or version <= row['desired_version']:
|
||||
raise ValueError('Version must increase for an existing attachment')
|
||||
if row['active_version'] is None and row['staging_key'] is None and row['object_key'].startswith('staging/'):
|
||||
raise ValueError('Original expired')
|
||||
conn.execute("""
|
||||
UPDATE attachments SET desired_version=%s,
|
||||
status=CASE WHEN active_version IS NULL THEN 'queued' ELSE status END,
|
||||
error_code=NULL,updated_at=clock_timestamp() WHERE id=%s
|
||||
""", (version, attachment_id))
|
||||
job = enqueue(conn, attachment_id, version)
|
||||
event(conn, job, 'reprocess_requested')
|
||||
return carrier(job)
|
||||
|
||||
|
||||
def replay(job_id):
|
||||
with get_connection() as conn:
|
||||
row = conn.execute('SELECT * FROM image_jobs WHERE id=%s FOR NO KEY UPDATE', (job_id,)).fetchone()
|
||||
if not row or row['state'] != 'failed':
|
||||
raise ValueError('Replay requires a failed job')
|
||||
attachment = conn.execute('SELECT * FROM attachments WHERE id=%s FOR NO KEY UPDATE',
|
||||
(row['attachment_id'],)).fetchone()
|
||||
if attachment['desired_version'] != row['pipeline_version']:
|
||||
raise ValueError('Replay requires the current pipeline version')
|
||||
if attachment['staging_key'] is None and attachment['object_key'].startswith('staging/'):
|
||||
raise ValueError('Staging retention expired')
|
||||
conn.execute("""
|
||||
UPDATE job_dead_letters SET replayed_at=clock_timestamp() WHERE job_id=%s AND attempt=%s
|
||||
""", (job_id, row['attempt']))
|
||||
updated = conn.execute("""
|
||||
UPDATE image_jobs SET state='queued', attempt=attempt+1, failures=0,
|
||||
error_code=NULL WHERE id=%s RETURNING *
|
||||
""", (job_id,)).fetchone()
|
||||
conn.execute("""
|
||||
UPDATE attachments SET status='queued',error_code=NULL,updated_at=clock_timestamp()
|
||||
WHERE id=%s AND active_version IS NULL
|
||||
""", (row['attachment_id'],))
|
||||
schedule(conn, job_id)
|
||||
event(conn, updated, 'operator_replay')
|
||||
return carrier(updated)
|
||||
|
||||
|
||||
def redeliver(job_id):
|
||||
with get_connection() as conn:
|
||||
row = conn.execute('SELECT * FROM image_jobs WHERE id=%s', (job_id,)).fetchone()
|
||||
if not row:
|
||||
raise ValueError('Job not found')
|
||||
message = carrier(row)
|
||||
with channel() as (_, ch):
|
||||
ch.confirm_delivery()
|
||||
send(ch, message, row['trace_context'])
|
||||
return message
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
commands = parser.add_subparsers(dest='command', required=True)
|
||||
new = commands.add_parser('reprocess')
|
||||
new.add_argument('attachment_id')
|
||||
new.add_argument('version', type=int, choices=[1, 2])
|
||||
commands.add_parser('replay').add_argument('job_id')
|
||||
commands.add_parser('redeliver').add_argument('job_id')
|
||||
args = parser.parse_args()
|
||||
open_database()
|
||||
try:
|
||||
if args.command == 'reprocess':
|
||||
result = reprocess(args.attachment_id, args.version)
|
||||
elif args.command == 'replay':
|
||||
result = replay(args.job_id)
|
||||
else:
|
||||
result = redeliver(args.job_id)
|
||||
print(json.dumps(result))
|
||||
except ValueError as exc:
|
||||
parser.exit(2, f'{exc}\n')
|
||||
finally:
|
||||
close_database()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,29 @@
|
||||
"""Check recent progress by the service loop in this container."""
|
||||
from pathlib import Path
|
||||
import time
|
||||
|
||||
PROGRESS = Path('/tmp/pipeline-progress')
|
||||
MAX_IDLE_SECONDS = 60
|
||||
_last_write = float('-inf')
|
||||
|
||||
|
||||
def mark_progress():
|
||||
global _last_write
|
||||
now = time.monotonic()
|
||||
if now - _last_write >= 1:
|
||||
PROGRESS.touch()
|
||||
_last_write = now
|
||||
|
||||
|
||||
def clear_progress():
|
||||
global _last_write
|
||||
PROGRESS.unlink(missing_ok=True)
|
||||
_last_write = float('-inf')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
healthy = time.time() - PROGRESS.stat().st_mtime < MAX_IDLE_SECONDS
|
||||
except FileNotFoundError:
|
||||
healthy = False
|
||||
raise SystemExit(0 if healthy else 1)
|
||||
@@ -0,0 +1,33 @@
|
||||
import logging
|
||||
import signal
|
||||
from threading import Event
|
||||
|
||||
import pika
|
||||
from psycopg import OperationalError
|
||||
from psycopg_pool import PoolTimeout
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
|
||||
from .credentials import CredentialsUnavailable
|
||||
from .pipeline_health import mark_progress, clear_progress
|
||||
from .database import open_database, close_database
|
||||
from .telemetry import configure, log
|
||||
|
||||
|
||||
def serve(loop, role):
|
||||
configure(role)
|
||||
stopping = Event()
|
||||
for sig in (signal.SIGTERM, signal.SIGINT):
|
||||
signal.signal(sig, lambda *_: stopping.set())
|
||||
clear_progress()
|
||||
open_database()
|
||||
try:
|
||||
while not stopping.is_set():
|
||||
try:
|
||||
loop(stopping, mark_progress)
|
||||
except (CredentialsUnavailable, OperationalError, PoolTimeout, BotoCoreError, ClientError, pika.exceptions.AMQPError, OSError) as exc:
|
||||
clear_progress()
|
||||
log('dependency_failure', logging.WARNING, error_type=type(exc).__name__)
|
||||
stopping.wait(1)
|
||||
finally:
|
||||
clear_progress()
|
||||
close_database()
|
||||
@@ -0,0 +1,59 @@
|
||||
"""Drain committed outbox rows, deleting only after a positive broker confirm."""
|
||||
import logging
|
||||
import os
|
||||
|
||||
from .broker import channel, send
|
||||
from .database import get_connection
|
||||
from .faults import take
|
||||
from .jobs import carrier, event
|
||||
from .process import serve
|
||||
from .telemetry import SpanKind, log, propagator, span
|
||||
|
||||
|
||||
def publish_one(ch):
|
||||
with get_connection() as conn:
|
||||
job = conn.execute("""
|
||||
SELECT j.* FROM job_outbox o JOIN image_jobs j ON j.id=o.job_id
|
||||
WHERE o.publish_after <= clock_timestamp()
|
||||
ORDER BY o.publish_after LIMIT 1 FOR UPDATE OF o SKIP LOCKED
|
||||
""").fetchone()
|
||||
if job is None:
|
||||
return False
|
||||
if job['state'] != 'queued':
|
||||
conn.execute('DELETE FROM job_outbox WHERE job_id=%s', (job['id'],))
|
||||
return True
|
||||
args = (job['attachment_id'], job['pipeline_version'])
|
||||
crash_before = take(conn, *args, 'before_publish') == 'crash'
|
||||
if not crash_before:
|
||||
parent = propagator.extract(job['trace_context'] or {})
|
||||
labels = {'messaging.system': 'rabbitmq', 'messaging.destination.name': 'attachment.process.v1',
|
||||
'job.attempt': job['attempt']}
|
||||
with span('attachment.process.v1 publish', context=parent,
|
||||
kind=SpanKind.PRODUCER, attributes=labels):
|
||||
headers = {}
|
||||
propagator.inject(headers)
|
||||
send(ch, carrier(job), headers)
|
||||
log('broker_confirmed', attempt=job['attempt'])
|
||||
crash_after = take(conn, *args, 'after_confirm') == 'crash'
|
||||
if not crash_after:
|
||||
conn.execute('DELETE FROM job_outbox WHERE job_id=%s', (job['id'],))
|
||||
event(conn, job, 'broker_confirmed')
|
||||
if crash_before or crash_after:
|
||||
point = 'before_publish' if crash_before else 'after_confirm'
|
||||
log('pipeline_fault', logging.WARNING, point=point, action='crash', job_id=str(job['id']))
|
||||
os._exit(86)
|
||||
return True
|
||||
|
||||
|
||||
def loop(stopping, progress):
|
||||
with channel() as (connection, ch):
|
||||
ch.confirm_delivery()
|
||||
while not stopping.is_set():
|
||||
if not publish_one(ch):
|
||||
connection.process_data_events(time_limit=0.2)
|
||||
stopping.wait(0.1)
|
||||
progress()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
serve(loop, 'publisher')
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Read one authoritative backlog and exact, matured ready SLO cohorts."""
|
||||
from time import time
|
||||
|
||||
from .broker import QUEUE
|
||||
from .database import get_connection
|
||||
from .telemetry import meter, oldest_age, queue_depth, ready_cohort
|
||||
|
||||
sample_time = meter.create_gauge('lab_queue_sample_timestamp', unit='s')
|
||||
DEADLINE = 10
|
||||
WINDOWS = {'30s': 30, '2m': 120, '5m': 300, '15m': 900, '1h': 3600}
|
||||
|
||||
|
||||
def observe():
|
||||
with get_connection() as conn:
|
||||
backlog = conn.execute("""
|
||||
SELECT count(*) FILTER (WHERE state='queued') AS depth,
|
||||
COALESCE(EXTRACT(EPOCH FROM statement_timestamp()-min(created_at)), 0) AS age
|
||||
FROM image_jobs WHERE state IN ('queued','processing')
|
||||
""").fetchone()
|
||||
cohorts = conn.execute("""
|
||||
WITH bounds AS (
|
||||
SELECT statement_timestamp() - %s * interval '1 second' AS maturity
|
||||
)
|
||||
SELECT w.label, count(j.accepted_at) AS total,
|
||||
count(*) FILTER (WHERE j.accepted_at IS NOT NULL AND (
|
||||
j.first_ready_at IS NULL OR
|
||||
j.first_ready_at > j.accepted_at + %s * interval '1 second')) AS bad
|
||||
FROM unnest(%s::text[], %s::int[]) AS w(label, seconds)
|
||||
CROSS JOIN bounds LEFT JOIN image_jobs j
|
||||
ON j.accepted_at > bounds.maturity - w.seconds * interval '1 second'
|
||||
AND j.accepted_at <= bounds.maturity
|
||||
GROUP BY w.label
|
||||
""", (DEADLINE, DEADLINE, list(WINDOWS), list(WINDOWS.values()))).fetchall()
|
||||
queue_depth.set(backlog['depth'], {'queue': QUEUE})
|
||||
oldest_age.set(max(0, float(backlog['age'])), {'queue': QUEUE})
|
||||
sample_time.set(time())
|
||||
for row in cohorts:
|
||||
for outcome in ('total', 'bad'):
|
||||
ready_cohort.set(row[outcome], {'window': row['label'], 'outcome': outcome})
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
"""Reclaim expired jobs and remove staging after safe publication or retention."""
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import os
|
||||
import time
|
||||
|
||||
from botocore.exceptions import ClientError
|
||||
|
||||
from .database import get_connection
|
||||
from .jobs import recover_one
|
||||
from .process import serve
|
||||
from .queue_metrics import observe
|
||||
from .storage import BUCKET, s3
|
||||
|
||||
RETENTION = int(os.getenv('STAGING_RETENTION_SECONDS', '86400'))
|
||||
|
||||
|
||||
def lock_staging(conn, key):
|
||||
return conn.execute('SELECT pg_try_advisory_xact_lock(hashtextextended(%s,0)) AS ok',
|
||||
(key,)).fetchone()['ok']
|
||||
|
||||
|
||||
def detach_staging(key, cutoff):
|
||||
with get_connection() as conn:
|
||||
if not lock_staging(conn, key):
|
||||
return False
|
||||
row = conn.execute("""
|
||||
SELECT id,status,active_version,object_key,updated_at
|
||||
FROM attachments WHERE staging_key=%s FOR NO KEY UPDATE
|
||||
""", (key,)).fetchone()
|
||||
if not row:
|
||||
return False
|
||||
if row['active_version'] is not None:
|
||||
if row['object_key'] == key or row['object_key'].startswith('staging/'):
|
||||
return False
|
||||
elif row['status'] != 'failed' or row['updated_at'] >= cutoff:
|
||||
return False
|
||||
conn.execute('UPDATE attachments SET staging_key=NULL WHERE id=%s', (row['id'],))
|
||||
# Commit the detach before deleting. Replay and reprocess can no longer use
|
||||
# a failed attachment's staging even if the DELETE succeeds but times out.
|
||||
return True
|
||||
|
||||
|
||||
def delete_unreferenced(key):
|
||||
with get_connection() as conn:
|
||||
if not lock_staging(conn, key):
|
||||
return
|
||||
if conn.execute("""
|
||||
SELECT 1 FROM attachments
|
||||
WHERE staging_key=%s OR (object_key=%s AND status <> 'failed')
|
||||
""", (key, key)).fetchone():
|
||||
return
|
||||
try:
|
||||
s3.delete_object(Bucket=BUCKET, Key=key)
|
||||
except ClientError as exc:
|
||||
if exc.response.get('Error', {}).get('Code') != 'NoSuchKey':
|
||||
raise
|
||||
|
||||
|
||||
def cleanup():
|
||||
cutoff = datetime.now(timezone.utc) - timedelta(seconds=RETENTION)
|
||||
# Start from PostgreSQL so an already absent object cannot leave a dangling
|
||||
# staging pointer that would otherwise be invisible to the S3 listing.
|
||||
after = 'staging/'
|
||||
while True:
|
||||
with get_connection() as conn:
|
||||
rows = conn.execute("""
|
||||
SELECT staging_key FROM attachments
|
||||
WHERE staging_key > %s AND staging_key LIKE 'staging/%%'
|
||||
AND (active_version IS NOT NULL OR (status='failed' AND updated_at < %s))
|
||||
ORDER BY staging_key LIMIT 100
|
||||
""", (after, cutoff)).fetchall()
|
||||
if not rows:
|
||||
break
|
||||
for row in rows:
|
||||
key = row['staging_key']
|
||||
if detach_staging(key, cutoff):
|
||||
delete_unreferenced(key)
|
||||
after = rows[-1]['staging_key']
|
||||
|
||||
# An upload that did not commit, or a detached object whose delete failed,
|
||||
# becomes eligible for collection from S3 after retention.
|
||||
params = {'Bucket': BUCKET, 'Prefix': 'staging/'}
|
||||
while True:
|
||||
page = s3.list_objects_v2(**params)
|
||||
for obj in page.get('Contents', []):
|
||||
if obj['LastModified'] < cutoff and obj['Key'].startswith('staging/'):
|
||||
delete_unreferenced(obj['Key'])
|
||||
if not page.get('IsTruncated'):
|
||||
break
|
||||
params['ContinuationToken'] = page['NextContinuationToken']
|
||||
|
||||
|
||||
def loop(stopping, progress):
|
||||
next_cleanup = next_observation = 0
|
||||
while not stopping.is_set():
|
||||
# Bound each batch so an expired-job backlog cannot starve cleanup.
|
||||
for _ in range(100):
|
||||
if stopping.is_set() or not recover_one():
|
||||
break
|
||||
progress()
|
||||
if stopping.is_set():
|
||||
break
|
||||
if time.monotonic() >= next_observation:
|
||||
observe()
|
||||
next_observation = time.monotonic() + 3
|
||||
if time.monotonic() >= next_cleanup:
|
||||
cleanup()
|
||||
next_cleanup = time.monotonic() + 15
|
||||
progress()
|
||||
stopping.wait(0.5)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
serve(loop, 'recovery')
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Bounded subprocess for untrusted image decoding and resizing."""
|
||||
import resource
|
||||
import sys
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image, ImageOps
|
||||
|
||||
# Linux runtime. macOS does not implement RLIMIT_AS with the same semantics.
|
||||
if sys.platform.startswith('linux'):
|
||||
resource.setrlimit(resource.RLIMIT_AS, (512 * 1024**2, 512 * 1024**2))
|
||||
resource.setrlimit(resource.RLIMIT_CPU, (15, 16))
|
||||
Image.MAX_IMAGE_PIXELS = 40_000_000
|
||||
warnings.simplefilter('error', Image.DecompressionBombWarning)
|
||||
|
||||
|
||||
def fit(image, bound):
|
||||
width, height = image.size
|
||||
largest = max(width, height)
|
||||
if largest <= bound:
|
||||
return image
|
||||
return image.resize((max(1, width * bound // largest), max(1, height * bound // largest)),
|
||||
Image.Resampling.LANCZOS)
|
||||
|
||||
|
||||
def render(directory, version):
|
||||
with Image.open(directory / 'original', formats=("PNG", "JPEG")) as source:
|
||||
image = ImageOps.exif_transpose(source)
|
||||
if 'A' in image.getbands() or 'transparency' in image.info:
|
||||
rgba = image.convert('RGBA')
|
||||
del image
|
||||
image = Image.new('RGB', rgba.size, 'white')
|
||||
image.paste(rgba, mask=rgba.getchannel('A'))
|
||||
del rgba
|
||||
else:
|
||||
image = image.convert('RGB')
|
||||
image.info.clear()
|
||||
jpeg_quality, webp_quality = {1: (85, 82), 2: (90, 88)}[version]
|
||||
fit(image, 256).save(directory / 'thumbnail', format='JPEG', quality=jpeg_quality)
|
||||
ImageOps.fit(image, (128, 128), Image.Resampling.LANCZOS).save(
|
||||
directory / 'crop', format='JPEG', quality=jpeg_quality)
|
||||
fit(image, 1280).save(directory / 'optimized', format='WEBP', quality=webp_quality, method=4)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
render(Path(sys.argv[1]), int(sys.argv[2]))
|
||||
except (OSError, ValueError, Image.DecompressionBombError, Image.DecompressionBombWarning):
|
||||
sys.exit(15)
|
||||
@@ -0,0 +1,40 @@
|
||||
"""Private S3 access using bounded credentials and sanitized spans."""
|
||||
import os
|
||||
from threading import Lock
|
||||
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
|
||||
from .credentials import credentials
|
||||
from .telemetry import span
|
||||
|
||||
BUCKET = os.getenv("S3_BUCKET", "messenger-attachments")
|
||||
|
||||
|
||||
class Storage:
|
||||
def __init__(self):
|
||||
self.lock = Lock()
|
||||
self.keys = None
|
||||
self.client = None
|
||||
|
||||
def __getattr__(self, name):
|
||||
def call(*args, **kwargs):
|
||||
with self.lock:
|
||||
snapshot = credentials.get()
|
||||
keys = snapshot["s3_user"], snapshot["s3_password"]
|
||||
if keys != self.keys:
|
||||
self.client = boto3.client(
|
||||
"s3", endpoint_url="https://s3:9000", region_name="us-east-1",
|
||||
aws_access_key_id=keys[0], aws_secret_access_key=keys[1],
|
||||
verify=os.environ["TLS_CA_FILE"],
|
||||
config=Config(connect_timeout=2, read_timeout=5,
|
||||
retries={"total_max_attempts": 1}, s3={"addressing_style": "path"}),
|
||||
)
|
||||
self.keys = keys
|
||||
client = self.client
|
||||
with span(f"s3.{name}"):
|
||||
return getattr(client, name)(*args, **kwargs)
|
||||
return call
|
||||
|
||||
|
||||
s3 = Storage()
|
||||
@@ -0,0 +1,165 @@
|
||||
"""Bounded OTLP SDKs and a deliberately small set of telemetry attributes."""
|
||||
from contextlib import contextmanager
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import resource
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
from time import perf_counter, process_time, time
|
||||
from uuid import uuid4
|
||||
|
||||
from opentelemetry import metrics, trace
|
||||
from opentelemetry._logs import set_logger_provider
|
||||
from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
|
||||
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
|
||||
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
|
||||
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
|
||||
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
|
||||
from opentelemetry.sdk.metrics import MeterProvider
|
||||
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
|
||||
from opentelemetry.sdk.metrics.view import ExplicitBucketHistogramAggregation, View
|
||||
from opentelemetry.sdk.resources import Resource
|
||||
from opentelemetry.sdk.trace import TracerProvider
|
||||
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
||||
from opentelemetry.sdk.trace.sampling import ALWAYS_ON
|
||||
from opentelemetry.trace import SpanKind, Status, StatusCode
|
||||
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
|
||||
|
||||
INSTANCE_ID = str(uuid4())
|
||||
JOB = {'job_type': 'attachment.process.v1'}
|
||||
propagator = TraceContextTextMapPropagator()
|
||||
tracer = trace.get_tracer(__name__)
|
||||
meter = metrics.get_meter(__name__)
|
||||
http_requests = meter.create_counter('lab_http_requests')
|
||||
http_duration = meter.create_histogram('lab_http_duration', unit='s')
|
||||
job_results = meter.create_counter('lab_job_results')
|
||||
job_duration = meter.create_histogram('lab_job_duration', unit='s')
|
||||
time_to_ready = meter.create_histogram('lab_time_to_ready', unit='s')
|
||||
queue_depth = meter.create_gauge('lab_queue_depth')
|
||||
oldest_age = meter.create_gauge('lab_oldest_job_age', unit='s')
|
||||
ready_cohort = meter.create_gauge('lab_ready_cohort')
|
||||
worker_busy = 0
|
||||
service_name = 'messenger'
|
||||
log_handler = None
|
||||
|
||||
|
||||
def configure(role):
|
||||
global service_name, log_handler
|
||||
service_name = f'messenger-{role}'
|
||||
if not os.getenv('OTEL_EXPORTER_OTLP_ENDPOINT'):
|
||||
return
|
||||
attributes = Resource.create({
|
||||
'service.name': service_name, 'service.version': '1.7.0',
|
||||
'service.instance.id': INSTANCE_ID, 'deployment.environment.name': 'lab',
|
||||
})
|
||||
traces = TracerProvider(resource=attributes, sampler=ALWAYS_ON)
|
||||
traces.add_span_processor(BatchSpanProcessor(
|
||||
OTLPSpanExporter(timeout=2), max_queue_size=512, max_export_batch_size=128))
|
||||
trace.set_tracer_provider(traces)
|
||||
logs = LoggerProvider(resource=attributes)
|
||||
logs.add_log_record_processor(BatchLogRecordProcessor(
|
||||
OTLPLogExporter(timeout=2), max_queue_size=512, max_export_batch_size=128))
|
||||
set_logger_provider(logs)
|
||||
log_handler = LoggingHandler(logger_provider=logs)
|
||||
views = [
|
||||
View(instrument_name='lab_http_duration', aggregation=ExplicitBucketHistogramAggregation(
|
||||
[0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2, 5, 10, 30, 60])),
|
||||
View(instrument_name='lab_job_duration', aggregation=ExplicitBucketHistogramAggregation(
|
||||
[0.025, 0.05, 0.1, 0.25, 0.5, 1, 2, 5, 10, 20, 30, 60, 120])),
|
||||
View(instrument_name='lab_time_to_ready', aggregation=ExplicitBucketHistogramAggregation(
|
||||
[0.1, 0.25, 0.5, 1, 2, 5, 10, 20, 30, 60, 120, 300])),
|
||||
]
|
||||
reader = PeriodicExportingMetricReader(OTLPMetricExporter(timeout=2),
|
||||
export_interval_millis=5000, export_timeout_millis=2000)
|
||||
metrics.set_meter_provider(MeterProvider(resource=attributes, metric_readers=[reader], views=views))
|
||||
meter.create_observable_counter('lab_process_cpu', unit='s',
|
||||
callbacks=[lambda _: [metrics.Observation(process_time())]])
|
||||
# /proc reports resident pages of this process (the container runs Linux).
|
||||
meter.create_observable_gauge('lab_process_rss', unit='By', callbacks=[rss])
|
||||
meter.create_observable_gauge('lab_process_alive', callbacks=[lambda _: [metrics.Observation(1)]])
|
||||
meter.create_observable_gauge('lab_process_heartbeat', unit='s',
|
||||
callbacks=[lambda _: [metrics.Observation(time())]])
|
||||
if role == 'worker':
|
||||
meter.create_observable_gauge('lab_worker_busy', callbacks=[lambda _: [metrics.Observation(worker_busy)]])
|
||||
meter.create_observable_gauge('lab_worker_capacity', callbacks=[lambda _: [metrics.Observation(1)]])
|
||||
|
||||
|
||||
def rss(_):
|
||||
try:
|
||||
with open('/proc/self/statm') as stats:
|
||||
value = int(stats.read().split()[1]) * os.sysconf('SC_PAGE_SIZE')
|
||||
except OSError:
|
||||
value = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss * (1 if sys.platform == 'darwin' else 1024)
|
||||
return [metrics.Observation(value)]
|
||||
|
||||
|
||||
def log(event, severity=logging.INFO, **fields):
|
||||
payload = {'timestamp': datetime.now(timezone.utc).isoformat(),
|
||||
'severity': logging.getLevelName(severity), 'service.name': service_name,
|
||||
'event': event, **fields}
|
||||
context = trace.get_current_span().get_span_context()
|
||||
if context.is_valid:
|
||||
payload.update(trace_id=f'{context.trace_id:032x}', span_id=f'{context.span_id:016x}')
|
||||
body = json.dumps(payload, separators=(',', ':'))
|
||||
print(body, flush=True)
|
||||
if log_handler:
|
||||
record = logging.LogRecord(__name__, severity, __file__, 0, body, (), None)
|
||||
record.event = event
|
||||
log_handler.handle(record)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def span(name, **options):
|
||||
if not options.get("kind") and not trace.get_current_span().get_span_context().is_valid:
|
||||
yield trace.get_current_span()
|
||||
return
|
||||
with tracer.start_as_current_span(name, record_exception=False,
|
||||
set_status_on_exception=False, **options) as active:
|
||||
try:
|
||||
yield active
|
||||
except Exception as exc:
|
||||
active.set_status(StatusCode.ERROR)
|
||||
active.set_attribute('error.type', type(exc).__name__)
|
||||
raise
|
||||
|
||||
|
||||
class HTTP:
|
||||
def __init__(self, app):
|
||||
self.app = app
|
||||
|
||||
async def __call__(self, scope, receive, send):
|
||||
if scope['type'] != 'http' or scope['path'] in ('/health/live', '/health/ready'):
|
||||
await self.app(scope, receive, send)
|
||||
return
|
||||
|
||||
method = scope['method']
|
||||
if method not in ('GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'):
|
||||
method = 'OTHER'
|
||||
headers = {key.decode(): value.decode('latin1') for key, value in scope['headers']
|
||||
if key in (b'traceparent', b'tracestate')}
|
||||
status = 500
|
||||
started = perf_counter()
|
||||
|
||||
async def capture(message):
|
||||
nonlocal status
|
||||
if message['type'] == 'http.response.start':
|
||||
status = message['status']
|
||||
await send(message)
|
||||
|
||||
with span(method, kind=SpanKind.SERVER, context=propagator.extract(headers)) as active:
|
||||
try:
|
||||
await self.app(scope, receive, capture)
|
||||
finally:
|
||||
route = getattr(scope.get('route'), 'path', 'unmatched')
|
||||
active.update_name(f'{method} {route}')
|
||||
active.set_attributes({'http.request.method': method, 'http.route': route,
|
||||
'http.response.status_code': status})
|
||||
if status >= 500:
|
||||
active.set_status(Status(StatusCode.ERROR))
|
||||
labels = {'method': method, 'route': route, 'status_class': f'{status // 100}xx'}
|
||||
http_requests.add(1, labels)
|
||||
http_duration.record(perf_counter() - started, labels)
|
||||
log('http_request', logging.ERROR if status >= 500 else logging.INFO,
|
||||
method=method, route=route, status=status,
|
||||
request_id=scope.get('state', {}).get('request_id'))
|
||||
@@ -0,0 +1,100 @@
|
||||
from uuid import uuid4
|
||||
|
||||
from psycopg.errors import UniqueViolation
|
||||
|
||||
from .database import get_connection
|
||||
|
||||
|
||||
def serialize_user(row):
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"username": row["username"],
|
||||
"display_name": row["display_name"],
|
||||
"created_at": row["created_at"].isoformat(
|
||||
timespec="microseconds"
|
||||
).replace("+00:00", "Z"),
|
||||
}
|
||||
|
||||
|
||||
def create_user(username, display_name, password_hash):
|
||||
with get_connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
try:
|
||||
cur.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),
|
||||
)
|
||||
return serialize_user(cur.fetchone())
|
||||
except UniqueViolation:
|
||||
conn.rollback()
|
||||
return None
|
||||
|
||||
|
||||
def find_user_by_username(username):
|
||||
with get_connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, username, display_name,
|
||||
password_hash, created_at
|
||||
FROM users
|
||||
WHERE username = %s
|
||||
""",
|
||||
(username,),
|
||||
)
|
||||
return cur.fetchone()
|
||||
|
||||
|
||||
def create_session(user_id, token_hash, expires_at):
|
||||
with get_connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO sessions (
|
||||
id, user_id, token_hash, expires_at
|
||||
)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
""",
|
||||
(uuid4(), user_id, token_hash, expires_at),
|
||||
)
|
||||
|
||||
|
||||
def revoke_session(token_hash):
|
||||
with get_connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE sessions
|
||||
SET revoked_at = NOW()
|
||||
WHERE token_hash = %s
|
||||
AND revoked_at IS NULL
|
||||
AND expires_at > NOW()
|
||||
RETURNING id
|
||||
""",
|
||||
(token_hash,),
|
||||
)
|
||||
return cur.fetchone() is not None
|
||||
|
||||
|
||||
def find_session_user(token_hash):
|
||||
with get_connection() as conn:
|
||||
row = conn.execute("""
|
||||
SELECT u.id, u.username, u.display_name, u.created_at
|
||||
FROM sessions s JOIN users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = %s AND s.revoked_at IS NULL
|
||||
AND s.expires_at > NOW()
|
||||
""", (token_hash,)).fetchone()
|
||||
return serialize_user(row) if row else None
|
||||
|
||||
|
||||
def replace_password_hash(user_id, previous, replacement):
|
||||
with get_connection() as conn:
|
||||
conn.execute("""
|
||||
UPDATE users SET password_hash = %s WHERE id = %s AND password_hash = %s
|
||||
""", (replacement, user_id, previous))
|
||||
+185
@@ -0,0 +1,185 @@
|
||||
"""One in-flight delivery per worker process. ACK follows the durable decision."""
|
||||
from datetime import datetime
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from time import perf_counter
|
||||
from uuid import UUID
|
||||
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
from PIL import Image
|
||||
|
||||
from .credentials import credentials
|
||||
from .database import get_connection
|
||||
from .broker import QUEUE, channel
|
||||
from .faults import checkpoint
|
||||
from .jobs import claim, fail, finish
|
||||
from .process import serve
|
||||
from .storage import BUCKET, s3
|
||||
from . import telemetry as otel
|
||||
|
||||
VARIANTS = {'thumbnail': 'image/jpeg', 'crop': 'image/jpeg', 'optimized': 'image/webp'}
|
||||
|
||||
|
||||
class PermanentError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def original(attachment):
|
||||
key = attachment['object_key']
|
||||
if key.startswith('staging/'):
|
||||
with get_connection() as conn:
|
||||
# Keep cleanup out until the entire source has been buffered.
|
||||
conn.execute('SELECT pg_advisory_xact_lock_shared(hashtextextended(%s,0))', (key,))
|
||||
current = conn.execute('SELECT staging_key FROM attachments WHERE id=%s',
|
||||
(attachment['id'],)).fetchone()
|
||||
if not current or current['staging_key'] != key:
|
||||
raise PermanentError('source_missing')
|
||||
data = read_original(key)
|
||||
else:
|
||||
data = read_original(key)
|
||||
if (len(data) != attachment['size_bytes']
|
||||
or hashlib.sha256(data).hexdigest() != attachment['sha256']):
|
||||
raise PermanentError('source_checksum_mismatch')
|
||||
return data
|
||||
|
||||
|
||||
def read_original(key):
|
||||
try:
|
||||
body = s3.get_object(Bucket=BUCKET, Key=key)['Body']
|
||||
except ClientError as exc:
|
||||
if exc.response.get('Error', {}).get('Code') in ('NoSuchKey', '404'):
|
||||
raise PermanentError('source_missing') from None
|
||||
raise
|
||||
with otel.span('s3.read_original'):
|
||||
try:
|
||||
return body.read(10 * 1024**2 + 1)
|
||||
finally:
|
||||
body.close()
|
||||
|
||||
|
||||
def put(job, variant, data, mime, dimensions=None):
|
||||
checksum = hashlib.sha256(data).hexdigest()
|
||||
key = f'results/{job["attachment_id"]}/v{job["pipeline_version"]}/{variant}/{checksum}'
|
||||
s3.put_object(Bucket=BUCKET, Key=key, Body=data, ContentType=mime)
|
||||
entry = dict(key=key, sha256=checksum, size_bytes=len(data), content_type=mime)
|
||||
if dimensions:
|
||||
entry.update(width=dimensions[0], height=dimensions[1])
|
||||
return entry
|
||||
|
||||
|
||||
def process(job, attachment):
|
||||
data = original(attachment)
|
||||
with tempfile.TemporaryDirectory(prefix='pipeline-') as target:
|
||||
directory = Path(target)
|
||||
(directory / 'original').write_bytes(data)
|
||||
with otel.span('image.render'):
|
||||
proc = subprocess.run([sys.executable, '-m', 'src.render_image', target,
|
||||
str(job['pipeline_version'])], timeout=20, check=False)
|
||||
if proc.returncode:
|
||||
raise PermanentError('invalid_image' if proc.returncode == 15 else 'processing_limit')
|
||||
action = checkpoint(job, 'before_s3')
|
||||
if action == 'permanent':
|
||||
raise PermanentError('invalid_image')
|
||||
if action == 'temporary':
|
||||
raise OSError('injected transient error')
|
||||
manifest = {'original': put(job, 'original', data, attachment['content_type'])}
|
||||
for variant, mime in VARIANTS.items():
|
||||
path = directory / variant
|
||||
with Image.open(path) as image:
|
||||
dimensions = image.size
|
||||
manifest[variant] = put(job, variant, path.read_bytes(), mime, dimensions)
|
||||
checkpoint(job, 'after_s3')
|
||||
return manifest
|
||||
|
||||
|
||||
def handle(ch, method, properties, body):
|
||||
headers = (properties.headers or {}) if properties else {}
|
||||
context = otel.propagator.extract({key: value for key, value in headers.items()
|
||||
if key in ('traceparent', 'tracestate') and isinstance(value, str)})
|
||||
labels = {'messaging.system': 'rabbitmq', 'messaging.destination.name': QUEUE,
|
||||
'messaging.message.redelivered': bool(method.redelivered)}
|
||||
with otel.span(f'{QUEUE} process', context=context, kind=otel.SpanKind.CONSUMER,
|
||||
attributes=labels) as active:
|
||||
handle_delivery(ch, method, body, active)
|
||||
|
||||
|
||||
def handle_delivery(ch, method, body, active):
|
||||
try:
|
||||
message = json.loads(body)
|
||||
if (type(message['schema_version']) is not int or message['schema_version'] != 1
|
||||
or message['type'] != QUEUE
|
||||
or any(type(message[field]) is not int or message[field] < 1
|
||||
for field in ('pipeline_version', 'attempt'))):
|
||||
raise ValueError('Invalid carrier')
|
||||
if datetime.fromisoformat(message['created_at']).tzinfo is None:
|
||||
raise ValueError('Missing UTC offset')
|
||||
for field in ('job_id', 'attachment_id'):
|
||||
message[field] = UUID(message[field])
|
||||
except (ValueError, TypeError, KeyError, AttributeError):
|
||||
ch.basic_reject(method.delivery_tag, requeue=False)
|
||||
return
|
||||
active.set_attribute('job.attempt', message['attempt'])
|
||||
with otel.span('job.claim'):
|
||||
claimed = claim(message)
|
||||
if claimed:
|
||||
job, attachment = claimed
|
||||
started = perf_counter()
|
||||
otel.worker_busy = 1
|
||||
outcome = 'interrupted'
|
||||
try:
|
||||
outcome = process_job(job, attachment)
|
||||
if outcome == 'ready':
|
||||
checkpoint(job, 'after_commit')
|
||||
finally:
|
||||
otel.worker_busy = 0
|
||||
labels = dict(otel.JOB, outcome=outcome)
|
||||
otel.job_duration.record(perf_counter() - started, labels)
|
||||
otel.job_results.add(1, labels)
|
||||
active.set_attribute('job.outcome', outcome)
|
||||
if outcome in ('failed', 'retry', 'interrupted'):
|
||||
active.set_status(otel.StatusCode.ERROR)
|
||||
otel.log('job_attempt', attempt=job['attempt'], outcome=outcome)
|
||||
else:
|
||||
active.set_attribute('job.outcome', 'ignored')
|
||||
otel.log('delivery_ignored')
|
||||
ch.basic_ack(method.delivery_tag)
|
||||
|
||||
|
||||
def process_job(job, attachment):
|
||||
try:
|
||||
manifest = process(job, attachment)
|
||||
except PermanentError as exc:
|
||||
return fail(job, str(exc), permanent=True)
|
||||
except subprocess.TimeoutExpired:
|
||||
return fail(job, 'processing_limit', permanent=True)
|
||||
except ClientError:
|
||||
return fail(job, 'storage_unavailable')
|
||||
except (BotoCoreError, OSError):
|
||||
return fail(job, 'temporary_failure')
|
||||
|
||||
with otel.span('job.publish_ready'):
|
||||
outcome, latency = finish(job, manifest)
|
||||
if latency is not None:
|
||||
otel.time_to_ready.record(max(0, latency), otel.JOB)
|
||||
return outcome
|
||||
|
||||
|
||||
def loop(stopping, progress):
|
||||
with channel() as (connection, ch):
|
||||
ch.basic_qos(prefetch_count=1)
|
||||
while not stopping.is_set():
|
||||
credentials.get()
|
||||
method, properties, body = ch.basic_get(QUEUE, auto_ack=False)
|
||||
if method:
|
||||
handle(ch, method, properties, body)
|
||||
else:
|
||||
connection.process_data_events(time_limit=0.2)
|
||||
progress()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
serve(loop, 'worker')
|
||||
Reference in New Issue
Block a user