lab6: добавить наблюдаемость и закрыть критерии оценки 5

This commit is contained in:
Wladislava1
2026-11-16 22:04:25 +03:00
parent 470d9d6f1e
commit 802e4b58c2
61 changed files with 7420 additions and 23 deletions
+228
View File
@@ -0,0 +1,228 @@
"""Проверка PNG/JPEG и доступ к приватному bucket. Ключ объекта назначает сервер."""
import io
import os
from datetime import datetime, timezone
from minio import Minio
from minio.error import S3Error
from PIL import Image, UnidentifiedImageError
from PIL.Image import DecompressionBombError
from errors import ApiError, DependencyDown
MAX_BYTES = 10 * 1024 * 1024
MAX_PIXELS = 40_000_000
BUCKET = os.environ.get("S3_BUCKET", "messenger-attachments")
Image.MAX_IMAGE_PIXELS = MAX_PIXELS
_client = None
def read_secret(path):
with open(path, encoding="utf-8") as handle:
return handle.read().strip()
def client():
global _client
if _client is None:
endpoint = os.environ.get("S3_ENDPOINT", "minio:9000").strip()
access = read_secret(os.environ["S3_ACCESS_KEY_FILE"])
secret = read_secret(os.environ["S3_SECRET_KEY_FILE"])
secure = os.environ.get("S3_SECURE", "false").strip().lower() == "true"
_client = Minio(endpoint, access_key=access, secret_key=secret, secure=secure)
return _client
def bucket_ready():
try:
return client().bucket_exists(BUCKET)
except Exception:
return False
def put_bytes(key, data, content_type, created_at):
stamp = created_at.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
try:
client().put_object(
BUCKET,
key,
io.BytesIO(data),
length=len(data),
content_type=content_type,
metadata={"created-at": stamp},
)
except S3Error as exc:
raise DependencyDown() from exc
def delete_quiet(key):
try:
client().remove_object(BUCKET, key)
return True
except Exception:
return False
def open_object(key):
try:
return client().get_object(BUCKET, key)
except S3Error as exc:
code = getattr(exc, "code", "")
if code in ("NoSuchKey", "NoSuchBucket"):
return None
raise DependencyDown() from exc
def object_key(chat_id, attachment_id):
return "chats/{}/attachments/{}/original".format(chat_id, attachment_id)
def staging_object_key(attachment_id):
return "staging/{}/original".format(attachment_id)
def variant_object_key(attachment_id, pipeline_version, name):
return "ready/{}/v{}/{}".format(attachment_id, int(pipeline_version), name)
def header_size(data, declared):
if declared == "image/png":
return _png_size(data)
if declared == "image/jpeg":
return _jpeg_size(data)
return None
def read_bytes(key):
body = open_object(key)
if body is None:
return None
try:
return body.read()
finally:
body.close()
body.release_conn()
def declared_type(header):
if not header:
return None
media = header.split(";", 1)[0].strip().lower()
if media in ("image/png", "image/jpeg"):
return media
return None
def _png_size(data):
if len(data) < 24 or data[:8] != b"\x89PNG\r\n\x1a\n" or data[12:16] != b"IHDR":
return None
width = int.from_bytes(data[16:20], "big")
height = int.from_bytes(data[20:24], "big")
return width, height
def _jpeg_size(data):
if len(data) < 4 or data[:2] != b"\xff\xd8":
return None
index = 2
limit = len(data)
while index + 8 < limit:
if data[index] != 0xFF:
return None
while index < limit and data[index] == 0xFF:
index += 1
if index >= limit:
return None
marker = data[index]
index += 1
if marker in (0xD8, 0xD9):
continue
if index + 2 > limit:
return None
segment = int.from_bytes(data[index:index + 2], "big")
if segment < 2 or index + segment > limit:
return None
if marker in (0xC0, 0xC1, 0xC2):
if segment < 7:
return None
height = int.from_bytes(data[index + 3:index + 5], "big")
width = int.from_bytes(data[index + 5:index + 7], "big")
return width, height
index += segment
return None
def _too_many_pixels(width, height):
if width <= 0 or height <= 0:
raise ApiError(415, "unsupported_media_type", "Файл не является PNG или JPEG")
if width > MAX_PIXELS or height > MAX_PIXELS or width * height > MAX_PIXELS:
raise ApiError(413, "payload_too_large", "В изображении больше 40 миллионов пикселей")
def inspect_image(data, declared):
if declared == "image/png":
size = _png_size(data)
elif declared == "image/jpeg":
size = _jpeg_size(data)
else:
size = None
detected = None
if data.startswith(b"\x89PNG\r\n\x1a\n"):
detected = "image/png"
elif data.startswith(b"\xff\xd8\xff"):
detected = "image/jpeg"
if size is None or detected != declared:
raise ApiError(415, "unsupported_media_type", "Файл не является PNG или JPEG")
_too_many_pixels(size[0], size[1])
try:
with Image.open(io.BytesIO(data)) as image:
image.load()
except DecompressionBombError as exc:
raise ApiError(413, "payload_too_large", "В изображении больше 40 миллионов пикселей") from exc
except (UnidentifiedImageError, OSError, SyntaxError, ValueError) as exc:
raise ApiError(415, "unsupported_media_type", "Файл не является PNG или JPEG") from exc
return declared
def list_objects(prefix=""):
found = []
prefixes = (prefix,) if prefix else ("chats/", "staging/", "ready/")
try:
for one in prefixes:
found.extend(_list_prefix(one))
except S3Error as exc:
raise DependencyDown() from exc
return found
def _list_prefix(prefix):
found = []
try:
for item in client().list_objects(BUCKET, prefix=prefix, recursive=True):
if item.is_dir:
continue
stat = client().stat_object(BUCKET, item.object_name)
raw = None
if stat.metadata:
meta = {str(key).lower(): value for key, value in stat.metadata.items()}
raw = meta.get("x-amz-meta-created-at") or meta.get("created-at")
created = _parse_stamp(raw) if raw else None
if created is None and item.last_modified is not None:
created = item.last_modified
found.append({"key": item.object_name, "created_at": created})
except S3Error as exc:
raise DependencyDown() from exc
return found
def _parse_stamp(value):
text = value.strip().replace("Z", "+00:00")
try:
parsed = datetime.fromisoformat(text)
except ValueError:
return None
if parsed.tzinfo is None:
parsed = parsed.replace(tzinfo=timezone.utc)
return parsed
+143
View File
@@ -0,0 +1,143 @@
"""RabbitMQ: publisher confirm при публикации, consumer ack отдельно в worker."""
import json
import os
from contextlib import contextmanager
import pika
from opentelemetry.trace import SpanKind
from psycopg.types.json import Json
from blobs import read_secret
from telemetry import start_span
PROCESS_QUEUE = "attachments.process"
RETRY_QUEUE = "attachments.retry"
FAILED_QUEUE = "attachments.failed"
def broker_url():
return read_secret(os.environ["BROKER_URL_FILE"])
def _parameters():
params = pika.URLParameters(broker_url())
params.heartbeat = 60
params.blocked_connection_timeout = 10
params.socket_timeout = 10
params.connection_attempts = 1
return params
def ensure_topology(channel):
channel.queue_declare(queue=PROCESS_QUEUE, durable=True)
channel.queue_declare(
queue=RETRY_QUEUE,
durable=True,
arguments={
"x-dead-letter-exchange": "",
"x-dead-letter-routing-key": PROCESS_QUEUE,
},
)
channel.queue_declare(queue=FAILED_QUEUE, durable=True)
@contextmanager
def broker_channel():
connection = pika.BlockingConnection(_parameters())
channel = connection.channel()
channel.confirm_delivery()
ensure_topology(channel)
try:
yield channel
finally:
try:
connection.close()
except Exception:
pass
def publish_raw(channel, queue, body, expiration_ms=None):
fields = {
"delivery_mode": 2,
"content_type": "application/json",
}
if expiration_ms is not None:
fields["expiration"] = str(int(expiration_ms))
with start_span(
"attachments.publish",
kind=SpanKind.PRODUCER,
attributes={
"messaging.system": "rabbitmq",
"messaging.destination.name": queue,
"messaging.operation": "publish",
},
):
channel.basic_publish(
exchange="",
routing_key=queue,
body=body,
properties=pika.BasicProperties(**fields),
mandatory=True,
)
def publish_pending(conn, only_job_id=None):
published = 0
while published < 20:
with conn.transaction():
conn.execute("SET LOCAL statement_timeout = '20s'")
params = []
sql = """
SELECT o.id, o.payload
FROM outbox o
JOIN attachment_jobs j ON j.id = o.job_id
WHERE o.published_at IS NULL
AND (j.next_attempt_at IS NULL OR j.next_attempt_at <= now())
"""
if only_job_id is not None:
sql += " AND o.job_id = %s"
params.append(only_job_id)
sql += """
ORDER BY o.created_at
FOR UPDATE OF o SKIP LOCKED
LIMIT 1
"""
row = conn.execute(sql, params).fetchone()
if row is None:
return published
body = json.dumps(
row["payload"],
ensure_ascii=False,
sort_keys=True,
separators=(",", ":"),
).encode("utf-8")
with broker_channel() as channel:
publish_raw(channel, PROCESS_QUEUE, body)
conn.execute(
"UPDATE outbox SET published_at = now() WHERE id = %s AND published_at IS NULL",
(row["id"],),
)
published += 1
if only_job_id is not None:
return published
return published
def publish_delay(body, delay_ms):
with broker_channel() as channel:
publish_raw(channel, RETRY_QUEUE, body, expiration_ms=max(1000, int(delay_ms)))
def publish_failed(body):
with broker_channel() as channel:
publish_raw(channel, FAILED_QUEUE, body)
def queue_depth(queue):
with broker_channel() as channel:
declared = channel.queue_declare(queue=queue, passive=True)
return int(declared.method.message_count)
def dump_payload(payload):
return Json(payload)
+32
View File
@@ -0,0 +1,32 @@
class ApiError(Exception):
def __init__(self, status, code, message, headers=None):
self.status = status
self.code = code
self.message = message
self.headers = headers or {}
class DependencyDown(Exception):
"""Postgres или Redis не ответили. Наружу это 503 без имени хранилища."""
class IdempotencyConflict(Exception):
"""Тот же Idempotency-Key уже зафиксирован с другим телом."""
class AttachmentRejected(Exception):
"""Вложение есть, но прикрепить его к сообщению нельзя."""
class AttachmentNotReady(Exception):
"""Байты ещё нельзя отдать: queued, processing или failed."""
def error_body(code, message, request_id):
return {
"error": {
"code": code,
"message": message,
"request_id": request_id,
}
}
+49
View File
@@ -0,0 +1,49 @@
"""Точечные сбои для проверки. Без строки в fault_injections код их не включает."""
import uuid
from psycopg.pq import TransactionStatus
def _idle(conn):
# Чтение выше могло открыть транзакцию. Её откат не теряет запись:
# сама запись начинается следующим transaction() и делает COMMIT.
if conn.info.transaction_status != TransactionStatus.IDLE:
conn.rollback()
def take_fault(conn, kind, attachment_id=None):
_idle(conn)
with conn.transaction():
row = conn.execute(
"""
UPDATE fault_injections AS target
SET armed = false
WHERE target.id = (
SELECT id
FROM fault_injections
WHERE armed
AND kind = %s
AND (attachment_id IS NULL OR attachment_id = %s)
ORDER BY created_at
FOR UPDATE SKIP LOCKED
LIMIT 1
)
RETURNING id
""",
(kind, attachment_id),
).fetchone()
return row is not None
def arm_fault(conn, kind, attachment_id=None):
fault_id = uuid.uuid4()
_idle(conn)
with conn.transaction():
conn.execute(
"""
INSERT INTO fault_injections (id, kind, attachment_id, armed)
VALUES (%s, %s, %s, true)
""",
(fault_id, kind, attachment_id),
)
return str(fault_id)
+129
View File
@@ -0,0 +1,129 @@
"""Варианты изображения. Оригинал не перекодируется."""
import io
from PIL import Image, ImageOps, UnidentifiedImageError
from PIL.Image import DecompressionBombError
from blobs import MAX_PIXELS, header_size
THUMB_BOX = 256
CROP_SIZE = 128
OPT_BOX = 1280
JPEG_QUALITY = 85
WEBP_QUALITY = 80
WEBP_METHOD = 4
Image.MAX_IMAGE_PIXELS = MAX_PIXELS
class PermanentJobError(Exception):
def __init__(self, code):
super().__init__(code)
self.code = code
class TransientJobError(Exception):
def __init__(self, code):
super().__init__(code)
self.code = code
def _rgb(image):
if image.mode == "RGBA" or image.mode == "LA" or (image.mode == "P" and "transparency" in image.info):
rgba = image.convert("RGBA")
background = Image.new("RGB", rgba.size, (255, 255, 255))
background.paste(rgba, mask=rgba.getchannel("A"))
return background
if image.mode == "RGB":
return image
return image.convert("RGB")
def load_rgb(data, declared):
size = header_size(data, declared)
detected = None
if data.startswith(b"\x89PNG\r\n\x1a\n"):
detected = "image/png"
elif data.startswith(b"\xff\xd8\xff"):
detected = "image/jpeg"
if size is None or detected != declared:
raise PermanentJobError("invalid_image")
width, height = size
if width <= 0 or height <= 0 or width > MAX_PIXELS or height > MAX_PIXELS or width * height > MAX_PIXELS:
raise PermanentJobError("invalid_image")
try:
with Image.open(io.BytesIO(data)) as image:
image.load()
oriented = ImageOps.exif_transpose(image)
rgb = _rgb(oriented)
rgb.load()
return rgb
except DecompressionBombError as exc:
raise PermanentJobError("invalid_image") from exc
except (UnidentifiedImageError, OSError, SyntaxError, ValueError) as exc:
raise PermanentJobError("invalid_image") from exc
def fit_inside(image, box):
width, height = image.size
if width <= box and height <= box:
return image.copy()
if width >= height:
new_w = box
new_h = max(1, (height * box) // width)
else:
new_h = box
new_w = max(1, (width * box) // height)
return image.resize((new_w, new_h), Image.Resampling.LANCZOS)
def center_square(image, size):
width, height = image.size
side = min(width, height)
left = (width - side) // 2
top = (height - side) // 2
cropped = image.crop((left, top, left + side, top + side))
if cropped.size != (size, size):
cropped = cropped.resize((size, size), Image.Resampling.LANCZOS)
return cropped
def _jpeg(image):
buffer = io.BytesIO()
image.save(buffer, format="JPEG", quality=JPEG_QUALITY, optimize=True)
return {
"bytes": buffer.getvalue(),
"content_type": "image/jpeg",
"width": image.size[0],
"height": image.size[1],
}
def _webp(image):
buffer = io.BytesIO()
image.save(buffer, format="WEBP", quality=WEBP_QUALITY, method=WEBP_METHOD)
return {
"bytes": buffer.getvalue(),
"content_type": "image/webp",
"width": image.size[0],
"height": image.size[1],
}
def render(data, declared):
rgb = load_rgb(data, declared)
size = header_size(data, declared)
thumb = fit_inside(rgb, THUMB_BOX)
crop = center_square(rgb, CROP_SIZE)
optimized = fit_inside(rgb, OPT_BOX)
return {
"original": {
"bytes": data,
"content_type": declared,
"width": size[0],
"height": size[1],
},
"thumbnail": _jpeg(thumb),
"crop": _jpeg(crop),
"optimized": _webp(optimized),
}
+896
View File
@@ -0,0 +1,896 @@
"""Состояния задания. Эффект один на (attachment_id, pipeline_version, вариант)."""
import hashlib
import json
import os
import random
import threading
import uuid
from datetime import datetime, timezone
from psycopg.pq import TransactionStatus
from psycopg.types.json import Json
from opentelemetry.trace import SpanKind, Status, StatusCode
from blobs import delete_quiet, put_bytes, read_bytes, variant_object_key
from errors import DependencyDown
from broker import publish_delay, publish_failed, publish_raw, broker_channel, PROCESS_QUEUE
from faults import take_fault
from images import PermanentJobError, TransientJobError, render
from telemetry import (
extract_context,
now_monotonic,
record_job,
record_time_to_ready,
start_span,
structured_log,
)
REQUIRED = ("original", "thumbnail", "crop", "optimized")
PUBLIC_CODES = ("invalid_image", "processing_failed", "retry_exhausted", "processing_timeout")
class LostLease(Exception):
pass
def _idle(conn):
if conn.info.transaction_status != TransactionStatus.IDLE:
conn.rollback()
def max_attempts():
raw = os.environ.get("JOB_MAX_ATTEMPTS", "5")
value = int(raw)
if not 1 <= value <= 20:
raise RuntimeError("JOB_MAX_ATTEMPTS")
return value
def lease_seconds():
raw = os.environ.get("JOB_TIMEOUT_SECONDS", "60")
value = int(raw)
if value < 5:
raise RuntimeError("JOB_TIMEOUT_SECONDS")
return value
def retention_seconds():
raw = os.environ.get("STAGING_RETENTION_SECONDS", "86400")
value = int(raw)
if value < 60:
raise RuntimeError("STAGING_RETENTION_SECONDS")
return value
def utc_now():
return datetime.now(timezone.utc)
def dump_time(value):
if value.tzinfo is None:
value = value.replace(tzinfo=timezone.utc)
text = value.astimezone(timezone.utc).isoformat(timespec="microseconds")
if text.endswith("+00:00"):
text = text[:-6] + "Z"
return text
def backoff_seconds(failed_attempt):
base = min(30.0, 0.5 * (2 ** (failed_attempt - 1)))
return base + random.uniform(0, base * 0.25)
def job_message(job_id, attachment_id, pipeline_version, attempt, created_at, carrier=None):
if not isinstance(created_at, str):
created_at = dump_time(created_at)
payload = {
"schema_version": 1,
"job_id": str(job_id),
"type": "attachment.process.v1",
"attachment_id": str(attachment_id),
"pipeline_version": int(pipeline_version),
"attempt": int(attempt),
"created_at": created_at,
}
if carrier:
traceparent = carrier.get("traceparent")
tracestate = carrier.get("tracestate")
if isinstance(traceparent, str) and len(traceparent) == 55:
payload["traceparent"] = traceparent
if isinstance(tracestate, str) and 0 < len(tracestate) <= 512:
payload["tracestate"] = tracestate
return payload
def _uuid(value):
try:
return str(uuid.UUID(str(value)))
except (ValueError, AttributeError, TypeError):
return None
def _stamp(value):
if not isinstance(value, str) or not value.endswith("Z"):
return None
try:
datetime.fromisoformat(value[:-1] + "+00:00")
except ValueError:
return None
return value
def parse_job(body):
try:
payload = json.loads(body.decode("utf-8"))
except (UnicodeError, ValueError, AttributeError):
return None
if not isinstance(payload, dict):
return None
allowed = {
"schema_version",
"job_id",
"type",
"attachment_id",
"pipeline_version",
"attempt",
"created_at",
"traceparent",
"tracestate",
}
if set(payload) - allowed:
return None
required = allowed - {"traceparent", "tracestate"}
if not required <= set(payload):
return None
if payload.get("schema_version") != 1 or payload.get("type") != "attachment.process.v1":
return None
job_id = _uuid(payload.get("job_id"))
attachment_id = _uuid(payload.get("attachment_id"))
created_at = _stamp(payload.get("created_at"))
version = payload.get("pipeline_version")
attempt = payload.get("attempt")
if job_id is None or attachment_id is None or created_at is None:
return None
if type(version) is not int or type(attempt) is not int:
return None
if version < 1 or attempt < 1:
return None
if "traceparent" in payload:
traceparent = payload["traceparent"]
if not isinstance(traceparent, str) or len(traceparent) != 55:
return None
if "tracestate" in payload:
tracestate = payload["tracestate"]
if not isinstance(tracestate, str) or len(tracestate) > 512:
return None
payload["job_id"] = job_id
payload["attachment_id"] = attachment_id
return payload
def _event(conn, job, kind, detail=None):
conn.execute(
"""
INSERT INTO job_events (job_id, attachment_id, pipeline_version, kind, detail)
VALUES (%s, %s, %s, %s, %s)
""",
(job["id"], job["attachment_id"], job["pipeline_version"], kind, detail),
)
def _message_body(job, attempt, created_at):
payload = job_message(job["id"], job["attachment_id"], job["pipeline_version"], attempt, created_at)
return json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")
def fail_job(conn, job, code):
if code not in PUBLIC_CODES and code != "superseded":
code = "processing_failed"
_idle(conn)
with conn.transaction():
conn.execute(
"""
UPDATE attachment_jobs
SET status = 'failed', error_code = %s, lease_owner = NULL,
lease_until = NULL, next_attempt_at = NULL, updated_at = now()
WHERE id = %s AND status IN ('queued', 'processing')
""",
(code, job["id"]),
)
if code in PUBLIC_CODES:
conn.execute(
"""
UPDATE attachments
SET status = 'failed', error_code = %s, updated_at = now()
WHERE id = %s AND pipeline_version = %s
AND status IN ('queued', 'processing')
""",
(code, job["attachment_id"], job["pipeline_version"]),
)
_event(conn, job, "failed", code)
try:
publish_failed(_message_body(job, job["attempt"], job["created_at"]))
except Exception:
# Реестр failed уже в базе. Повторная доставка увидит failed и подтвердит сообщение.
return
def schedule_retry(conn, job, code, owner):
attempt = int(job["attempt"])
if attempt >= int(job["max_attempts"]):
fail_job(conn, job, "retry_exhausted")
return
delay = backoff_seconds(attempt)
new_attempt = attempt + 1
created = utc_now()
payload = job_message(job["id"], job["attachment_id"], job["pipeline_version"], new_attempt, created)
_idle(conn)
with conn.transaction():
updated = conn.execute(
"""
UPDATE attachment_jobs
SET status = 'queued', attempt = %s, lease_owner = NULL, lease_until = NULL,
next_attempt_at = now() + make_interval(secs => %s),
error_code = NULL, updated_at = now()
WHERE id = %s AND status = 'processing' AND lease_owner = %s
RETURNING id
""",
(new_attempt, delay, job["id"], owner),
).fetchone()
if updated is None:
return
conn.execute(
"""
UPDATE attachments
SET status = 'queued', error_code = NULL, updated_at = now()
WHERE id = %s AND pipeline_version = %s AND status = 'processing'
""",
(job["attachment_id"], job["pipeline_version"]),
)
conn.execute(
"""
INSERT INTO outbox (id, job_id, attempt, payload, created_at)
VALUES (%s, %s, %s, %s, %s)
""",
(uuid.uuid4(), job["id"], new_attempt, Json(payload), created),
)
_event(conn, job, "retry", code)
def release_expired(conn):
released = 0
_idle(conn)
with conn.transaction():
rows = conn.execute(
"""
UPDATE attachment_jobs
SET status = 'queued', lease_owner = NULL, lease_until = NULL, updated_at = now()
WHERE status = 'processing' AND lease_until < now()
RETURNING id, attachment_id, pipeline_version, attempt, created_at
"""
).fetchall()
for row in rows:
payload = job_message(row["id"], row["attachment_id"], row["pipeline_version"], row["attempt"], utc_now())
conn.execute(
"""
INSERT INTO outbox (id, job_id, attempt, payload, created_at)
SELECT %s, %s, %s, %s, now()
WHERE NOT EXISTS (
SELECT 1 FROM outbox WHERE job_id = %s AND published_at IS NULL
)
""",
(uuid.uuid4(), row["id"], row["attempt"], Json(payload), row["id"]),
)
conn.execute(
"""
UPDATE attachments
SET status = 'queued', updated_at = now()
WHERE id = %s AND pipeline_version = %s AND status = 'processing'
""",
(row["attachment_id"], row["pipeline_version"]),
)
_event(conn, row, "lease_expired", None)
released += 1
return released
def cleanup_staging(conn):
removed = 0
_idle(conn)
with conn.transaction():
rows = conn.execute(
"""
SELECT a.id, a.staging_key
FROM attachments a
WHERE a.staging_key IS NOT NULL
AND a.staging_deleted_at IS NULL
AND a.status IN ('ready', 'failed')
AND NOT EXISTS (
SELECT 1 FROM attachment_jobs j
WHERE j.attachment_id = a.id
AND j.status IN ('queued', 'processing')
)
"""
).fetchall()
for row in rows:
if delete_quiet(row["staging_key"]):
with conn.transaction():
conn.execute(
"""
UPDATE attachments
SET staging_deleted_at = now()
WHERE id = %s AND staging_deleted_at IS NULL
""",
(row["id"],),
)
removed += 1
return removed
def _load_job(conn, job_id):
return conn.execute(
"""
SELECT id, attachment_id, pipeline_version, status, attempt, max_attempts,
lease_owner, lease_until, next_attempt_at, error_code, created_at
FROM attachment_jobs
WHERE id = %s
""",
(job_id,),
).fetchone()
def _load_attachment(conn, attachment_id):
return conn.execute(
"""
SELECT id, content_type, sha256, object_key, staging_key, staging_deleted_at,
status, pipeline_version
FROM attachments
WHERE id = %s
""",
(attachment_id,),
).fetchone()
def _acquire(conn, job, owner, seconds):
_idle(conn)
with conn.transaction():
locked = conn.execute(
"""
UPDATE attachment_jobs
SET status = 'processing', lease_owner = %s,
lease_until = now() + make_interval(secs => %s),
updated_at = now()
WHERE id = %s
AND status IN ('queued', 'processing')
AND attempt = %s
AND pipeline_version = %s
AND (lease_owner IS NULL OR lease_owner = %s OR lease_until < now())
RETURNING id
""",
(owner, seconds, job["id"], job["attempt"], job["pipeline_version"], owner),
).fetchone()
if locked is None:
return False
conn.execute(
"""
UPDATE attachments
SET status = 'processing', updated_at = now()
WHERE id = %s AND pipeline_version = %s AND status IN ('queued', 'processing')
""",
(job["attachment_id"], job["pipeline_version"]),
)
_event(conn, job, "leased", None)
return True
def _variants(conn, attachment_id, version):
rows = conn.execute(
"""
SELECT name, object_key, sha256
FROM attachment_variants
WHERE attachment_id = %s AND pipeline_version = %s
""",
(attachment_id, version),
).fetchall()
return {row["name"]: row for row in rows}
def _source(conn, attachment):
if attachment["staging_key"] and attachment["staging_deleted_at"] is None:
data = read_bytes(attachment["staging_key"])
if data:
return data
data = read_bytes(attachment["object_key"])
if data:
return data
row = conn.execute(
"""
SELECT object_key
FROM attachment_variants
WHERE attachment_id = %s AND name = 'original'
ORDER BY pipeline_version DESC
LIMIT 1
""",
(attachment["id"],),
).fetchone()
if row is None:
raise TransientJobError("processing_failed")
data = read_bytes(row["object_key"])
if not data:
raise TransientJobError("processing_failed")
return data
def _render_limited(data, declared, seconds):
budget = max(5, seconds - 5)
box = []
errors = []
def run():
try:
box.append(render(data, declared))
except Exception as exc:
errors.append(exc)
thread = threading.Thread(target=run, daemon=True)
thread.start()
thread.join(budget)
if thread.is_alive():
raise TransientJobError("processing_timeout")
if errors:
exc = errors[0]
if isinstance(exc, (PermanentJobError, TransientJobError)):
raise exc
raise PermanentJobError("invalid_image")
return box[0]
def _beat(pool, job_id, owner, seconds, stop):
pause = max(2, seconds // 3)
while not stop.wait(pause):
try:
with pool.connection() as conn:
with conn.transaction():
conn.execute(
"""
UPDATE attachment_jobs
SET lease_until = now() + make_interval(secs => %s), updated_at = now()
WHERE id = %s AND lease_owner = %s AND status = 'processing'
""",
(seconds, job_id, owner),
)
except Exception:
return
def _supersede(conn, job):
_idle(conn)
with conn.transaction():
conn.execute(
"""
UPDATE attachment_jobs
SET status = 'superseded', error_code = 'superseded', lease_owner = NULL,
lease_until = NULL, next_attempt_at = NULL, updated_at = now()
WHERE id = %s AND status IN ('queued', 'processing')
""",
(job["id"],),
)
_event(conn, job, "superseded", None)
def _finalize(conn, job, owner, rendered):
_idle(conn)
with conn.transaction():
current = conn.execute(
"""
SELECT lease_owner, status, pipeline_version
FROM attachment_jobs
WHERE id = %s
FOR UPDATE
""",
(job["id"],),
).fetchone()
if current is None or current["lease_owner"] != owner or current["status"] != "processing":
raise LostLease()
attachment = conn.execute(
"""
SELECT pipeline_version, status
FROM attachments
WHERE id = %s
FOR UPDATE
""",
(job["attachment_id"],),
).fetchone()
if attachment is None or int(attachment["pipeline_version"]) > int(job["pipeline_version"]):
conn.execute(
"""
UPDATE attachment_jobs
SET status = 'superseded', error_code = 'superseded', lease_owner = NULL,
lease_until = NULL, updated_at = now()
WHERE id = %s
""",
(job["id"],),
)
_event(conn, job, "superseded", None)
return "superseded"
now = utc_now()
for name in REQUIRED:
item = rendered[name]
conn.execute(
"""
INSERT INTO attachment_variants (
attachment_id, pipeline_version, name, content_type, size_bytes,
width, height, sha256, object_key, created_at
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
ON CONFLICT (attachment_id, pipeline_version, name) DO NOTHING
""",
(
job["attachment_id"],
job["pipeline_version"],
name,
item["content_type"],
len(item["bytes"]),
item["width"],
item["height"],
item["sha256"],
item["object_key"],
now,
),
)
stored = conn.execute(
"""
SELECT count(*) AS n
FROM attachment_variants
WHERE attachment_id = %s AND pipeline_version = %s
AND name IN ('original', 'thumbnail', 'crop', 'optimized')
""",
(job["attachment_id"], job["pipeline_version"]),
).fetchone()
if int(stored["n"]) < len(REQUIRED):
raise TransientJobError("processing_failed")
original = rendered["original"]
conn.execute(
"""
UPDATE attachments
SET status = 'ready', error_code = NULL, pipeline_version = %s,
object_key = %s, updated_at = %s
WHERE id = %s AND pipeline_version <= %s
""",
(
job["pipeline_version"],
original["object_key"],
now,
job["attachment_id"],
job["pipeline_version"],
),
)
conn.execute(
"""
UPDATE attachment_jobs
SET status = 'ready', error_code = NULL, lease_owner = NULL,
lease_until = NULL, next_attempt_at = NULL, updated_at = %s
WHERE id = %s AND lease_owner = %s
""",
(now, job["id"], owner),
)
_event(conn, job, "ready", None)
return "ready"
def _drop_staging(conn, attachment):
_idle(conn)
with conn.transaction():
active = conn.execute(
"""
SELECT count(*) AS n
FROM attachment_jobs
WHERE attachment_id = %s AND status IN ('queued', 'processing')
""",
(attachment["id"],),
).fetchone()
if int(active["n"]) > 0 or not attachment["staging_key"]:
return
if delete_quiet(attachment["staging_key"]):
with conn.transaction():
conn.execute(
"""
UPDATE attachments
SET staging_deleted_at = now()
WHERE id = %s AND staging_deleted_at IS NULL
""",
(attachment["id"],),
)
def process_delivery(pool, body, owner):
payload = parse_job(body)
if payload is None:
return "ack"
carrier = {}
if "traceparent" in payload:
carrier["traceparent"] = payload["traceparent"]
if "tracestate" in payload:
carrier["tracestate"] = payload["tracestate"]
parent = extract_context(carrier) if carrier else None
started = now_monotonic()
with start_span(
"attachments.process consume",
kind=SpanKind.CONSUMER,
context=parent,
attributes={
"messaging.system": "rabbitmq",
"messaging.destination.name": PROCESS_QUEUE,
"messaging.operation": "process",
"job.type": "attachment.process.v1",
},
) as span:
return _process_delivery_body(pool, body, owner, payload, span, started)
def _process_delivery_body(pool, body, owner, payload, span, started):
import logging
logger = logging.getLogger("worker")
with pool.connection() as conn:
job = _load_job(conn, payload["job_id"])
if job is None:
return "ack"
if job["status"] in ("ready", "failed", "superseded"):
return "ack"
if int(payload["attempt"]) != int(job["attempt"]) or int(payload["pipeline_version"]) != int(job["pipeline_version"]):
return "ack"
if job["next_attempt_at"] is not None and job["next_attempt_at"] > utc_now():
delay = (job["next_attempt_at"] - utc_now()).total_seconds()
publish_delay(body, int(delay * 1000))
return "ack"
with pool.connection() as conn:
attachment = _load_attachment(conn, job["attachment_id"])
if attachment is None:
fail_job(conn, job, "invalid_image")
record_job("failed", now_monotonic() - started)
return "ack"
if int(attachment["pipeline_version"]) > int(job["pipeline_version"]):
_supersede(conn, job)
record_job("superseded", now_monotonic() - started)
return "ack"
if not _acquire(conn, job, owner, lease_seconds()):
publish_delay(body, 2000)
return "ack"
structured_log(logger, "job_leased", job_id=str(job["id"]), attempt=int(job["attempt"]))
stop = threading.Event()
beater = threading.Thread(
target=_beat,
args=(pool, job["id"], owner, lease_seconds(), stop),
daemon=True,
)
beater.start()
try:
with start_span("s3.read_source", kind=SpanKind.CLIENT):
with pool.connection() as conn:
if take_fault(conn, "crash_before_effect", job["attachment_id"]):
os_exit()
if take_fault(conn, "transient_once", job["attachment_id"]):
raise TransientJobError("processing_failed")
present = _variants(conn, job["attachment_id"], job["pipeline_version"])
source = None if set(REQUIRED) <= set(present) else _source(conn, attachment)
if source is None:
rendered = _rendered_from_rows(conn, job, present)
if source is not None:
if hashlib.sha256(source).hexdigest() != attachment["sha256"]:
raise PermanentJobError("invalid_image")
with start_span("image.render", kind=SpanKind.INTERNAL):
rendered = _render_limited(source, attachment["content_type"], lease_seconds())
with start_span("s3.write_variants", kind=SpanKind.CLIENT):
for name in REQUIRED:
item = rendered[name]
item["sha256"] = hashlib.sha256(item["bytes"]).hexdigest()
item["object_key"] = variant_object_key(job["attachment_id"], job["pipeline_version"], name)
if name in present:
continue
put_bytes(item["object_key"], item["bytes"], item["content_type"], utc_now())
with pool.connection() as conn:
if take_fault(conn, "crash_after_objects", job["attachment_id"]):
os_exit()
with start_span("db.finalize_ready", kind=SpanKind.CLIENT):
with pool.connection() as conn:
_finalize(conn, job, owner, rendered)
with pool.connection() as conn:
if take_fault(conn, "crash_after_commit", job["attachment_id"]):
os_exit()
with pool.connection() as conn:
_drop_staging(conn, attachment)
duration = now_monotonic() - started
record_job("ready", duration)
if job.get("created_at") is not None:
created = job["created_at"]
if created.tzinfo is None:
created = created.replace(tzinfo=timezone.utc)
record_time_to_ready((utc_now() - created).total_seconds())
structured_log(logger, "job_ready", job_id=str(job["id"]), duration_ms=round(duration * 1000, 3))
span.set_status(Status(StatusCode.OK))
return "ack"
except PermanentJobError as exc:
with pool.connection() as conn:
fail_job(conn, job, exc.code)
record_job("failed", now_monotonic() - started)
span.set_status(Status(StatusCode.ERROR, exc.code))
structured_log(logger, "job_failed", level=30, job_id=str(job["id"]), error_code=exc.code)
return "ack"
except LostLease:
return "ack"
except (TransientJobError, DependencyDown) as exc:
code = exc.code if isinstance(exc, TransientJobError) else "processing_failed"
with pool.connection() as conn:
schedule_retry(conn, job, code, owner)
record_job("retry", now_monotonic() - started)
span.set_status(Status(StatusCode.ERROR, code))
structured_log(logger, "job_retry", level=30, job_id=str(job["id"]), error_code=code)
return "ack"
finally:
stop.set()
def os_exit():
os._exit(75)
def _rendered_from_rows(conn, job, present):
# Повтор после уже записанного эффекта не перекодирует файлы.
rendered = {}
for name in REQUIRED:
row = present[name]
data = read_bytes(row["object_key"])
if data is None:
raise TransientJobError("processing_failed")
meta = conn.execute(
"""
SELECT content_type, width, height, sha256, object_key
FROM attachment_variants
WHERE attachment_id = %s AND pipeline_version = %s AND name = %s
""",
(job["attachment_id"], job["pipeline_version"], name),
).fetchone()
rendered[name] = {
"bytes": data,
"content_type": meta["content_type"],
"width": int(meta["width"]),
"height": int(meta["height"]),
"sha256": meta["sha256"],
"object_key": meta["object_key"],
}
return rendered
def bump_pipeline(conn, attachment_id):
_idle(conn)
with conn.transaction():
row = conn.execute(
"SELECT id, pipeline_version FROM attachments WHERE id = %s FOR UPDATE",
(attachment_id,),
).fetchone()
if row is None:
return None
version = int(row["pipeline_version"]) + 1
job_id = uuid.uuid4()
created = utc_now()
final_key = variant_object_key(attachment_id, version, "original")
conn.execute(
"""
UPDATE attachments
SET pipeline_version = %s, status = 'queued', error_code = NULL,
object_key = %s, updated_at = %s
WHERE id = %s
""",
(version, final_key, created, attachment_id),
)
attempts = max_attempts()
conn.execute(
"""
INSERT INTO attachment_jobs (
id, attachment_id, pipeline_version, status, attempt, max_attempts, created_at, updated_at
) VALUES (%s, %s, %s, 'queued', 1, %s, %s, %s)
""",
(job_id, attachment_id, version, attempts, created, created),
)
payload = job_message(job_id, attachment_id, version, 1, created)
conn.execute(
"""
INSERT INTO outbox (id, job_id, attempt, payload, created_at)
VALUES (%s, %s, 1, %s, %s)
""",
(uuid.uuid4(), job_id, Json(payload), created),
)
conn.execute(
"""
INSERT INTO job_events (job_id, attachment_id, pipeline_version, kind, detail)
VALUES (%s, %s, %s, 'version', %s)
""",
(job_id, attachment_id, version, str(version)),
)
return {"job_id": str(job_id), "pipeline_version": version}
def replay_job(conn, job_id):
_idle(conn)
with conn.transaction():
job = conn.execute(
"""
SELECT id, attachment_id, pipeline_version, status, attempt, max_attempts, created_at
FROM attachment_jobs
WHERE id = %s
FOR UPDATE
""",
(job_id,),
).fetchone()
if job is None:
return {"result": "missing"}
if job["status"] == "ready":
return {"result": "already_ready"}
names = conn.execute(
"""
SELECT name FROM attachment_variants
WHERE attachment_id = %s AND pipeline_version = %s
""",
(job["attachment_id"], job["pipeline_version"]),
).fetchall()
have = {row["name"] for row in names}
if set(REQUIRED) <= have:
conn.execute(
"""
UPDATE attachment_jobs
SET status = 'ready', error_code = NULL, lease_owner = NULL,
lease_until = NULL, next_attempt_at = NULL, updated_at = now()
WHERE id = %s AND status <> 'ready'
""",
(job["id"],),
)
return {"result": "already_done"}
if job["status"] != "failed":
return {"result": "not_failed"}
created = utc_now()
conn.execute(
"""
UPDATE attachment_jobs
SET status = 'queued', attempt = 1, error_code = NULL, lease_owner = NULL,
lease_until = NULL, next_attempt_at = NULL, updated_at = %s
WHERE id = %s
""",
(created, job["id"]),
)
conn.execute(
"""
UPDATE attachments
SET status = 'queued', error_code = NULL, updated_at = %s
WHERE id = %s AND pipeline_version = %s AND status = 'failed'
""",
(created, job["attachment_id"], job["pipeline_version"]),
)
payload = job_message(job["id"], job["attachment_id"], job["pipeline_version"], 1, created)
conn.execute(
"""
INSERT INTO outbox (id, job_id, attempt, payload, created_at)
VALUES (%s, %s, 1, %s, %s)
""",
(uuid.uuid4(), job["id"], Json(payload), created),
)
_event(conn, job, "replay", None)
return {"result": "queued"}
def republish(conn, job_id, attempt=None):
job = conn.execute(
"""
SELECT id, attachment_id, pipeline_version, attempt, created_at
FROM attachment_jobs
WHERE id = %s
""",
(job_id,),
).fetchone()
if job is None:
return False
chosen = int(job["attempt"] if attempt is None else attempt)
body = _message_body(job, chosen, utc_now())
with broker_channel() as channel:
publish_raw(channel, PROCESS_QUEUE, body)
return True
+519
View File
@@ -0,0 +1,519 @@
import json
import logging
import os
import re
import time
import uuid
from contextlib import asynccontextmanager
import anyio
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse, Response, StreamingResponse
from opentelemetry import trace
from opentelemetry.trace import SpanKind, Status, StatusCode
from pydantic import ValidationError
from starlette.exceptions import HTTPException as StarletteHTTPException
from blobs import MAX_BYTES, declared_type, inspect_image, open_object
from errors import ApiError, AttachmentNotReady, AttachmentRejected, DependencyDown, IdempotencyConflict, error_body
from schemas import CreateChat, CreateMessage, CreateUser
from store import Store, instance_id
from telemetry import record_http, route_template, setup as setup_telemetry, structured_log
LOGGER = logging.getLogger("messenger")
store = Store()
INSTANCE_ID = instance_id()
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
BEARER_CHALLENGE = 'Bearer realm="messenger"'
IDEMPOTENCY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
MAX_JSON_BYTES = 65536
@asynccontextmanager
async def lifespan(_app):
setup_telemetry(os.environ.get("OTEL_SERVICE_NAME", "messenger-api"))
await anyio.to_thread.run_sync(store.startup)
yield
store.shutting_down = True
await anyio.to_thread.run_sync(store.shutdown)
app = FastAPI(
title="mtusi-messenger",
version="lab6",
lifespan=lifespan,
redirect_slashes=False,
docs_url="/docs",
redoc_url=None,
openapi_url="/openapi.json",
)
def request_id_of(request: Request):
rid = getattr(request.state, "request_id", None)
if rid:
return rid
return str(uuid.uuid4())
def stamp(request: Request, response):
response.headers["X-Request-Id"] = request_id_of(request)
response.headers["X-Instance-Id"] = INSTANCE_ID
return response
def json_ok(request: Request, payload, status_code=200):
return stamp(request, JSONResponse(payload, status_code=status_code))
def json_error(request: Request, status, code, message, extra_headers=None):
headers = {"X-Request-Id": request_id_of(request), "X-Instance-Id": INSTANCE_ID}
if extra_headers:
headers.update(extra_headers)
return JSONResponse(error_body(code, message, request_id_of(request)), status_code=status, headers=headers)
@app.middleware("http")
async def wrap_request(request: Request, call_next):
incoming = request.headers.get("X-Request-Id", "")
if incoming and len(incoming) <= 200 and incoming.isprintable() and incoming.strip():
request.state.request_id = incoming.strip()
else:
request.state.request_id = str(uuid.uuid4())
if store.shutting_down and request.url.path != "/health/live":
return json_error(request, 503, "unavailable", "Сервис временно недоступен")
started = time.perf_counter()
route = route_template(request.url.path)
is_health = request.url.path in ("/health/live", "/health/ready")
if is_health:
response = await call_next(request)
return stamp(request, response)
tracer = trace.get_tracer("messenger")
with tracer.start_as_current_span(
f"{request.method} {route}",
kind=SpanKind.SERVER,
attributes={
"http.request.method": request.method,
"http.route": route,
"service.instance.id": INSTANCE_ID,
},
) as span:
span.set_attribute("http.request_id", request.state.request_id)
try:
response = await call_next(request)
except Exception as exc:
span.record_exception(exc)
span.set_status(Status(StatusCode.ERROR, type(exc).__name__))
raise
stamped = stamp(request, response)
span.set_attribute("http.response.status_code", stamped.status_code)
if stamped.status_code >= 500:
span.set_status(Status(StatusCode.ERROR))
duration = time.perf_counter() - started
record_http(request.method, request.url.path, stamped.status_code, duration)
structured_log(
LOGGER,
"http_request",
method=request.method,
route=route,
status=stamped.status_code,
request_id=request.state.request_id,
duration_ms=round(duration * 1000, 3),
)
return stamped
@app.exception_handler(ApiError)
async def api_error_handler(request: Request, exc: ApiError):
return json_error(request, exc.status, exc.code, exc.message, exc.headers)
@app.exception_handler(RequestValidationError)
async def request_validation_handler(request: Request, _exc: RequestValidationError):
return json_error(request, 400, "invalid_request", "Некорректный запрос")
@app.exception_handler(ValidationError)
async def pydantic_handler(request: Request, _exc: ValidationError):
return json_error(request, 400, "invalid_request", "Некорректный запрос")
@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
if exc.status_code == 404:
return json_error(request, 404, "not_found", "Объект не найден")
return json_error(request, exc.status_code if exc.status_code < 500 else 500, "invalid_request", "Некорректный запрос")
@app.exception_handler(Exception)
async def unexpected_handler(request: Request, exc: Exception):
if isinstance(exc, ApiError):
return json_error(request, exc.status, exc.code, exc.message, exc.headers)
LOGGER.error("unhandled %s", type(exc).__name__)
return json_error(request, 500, "internal_error", "Внутренняя ошибка")
def unavailable():
raise ApiError(503, "unavailable", "Сервис временно недоступен")
def bearer_unauthorized():
raise ApiError(401, "unauthorized", "Требуется авторизация", {"WWW-Authenticate": BEARER_CHALLENGE})
def basic_unauthorized():
raise ApiError(401, "unauthorized", "Неверные учётные данные", {"WWW-Authenticate": BASIC_CHALLENGE})
def invalid():
raise ApiError(400, "invalid_request", "Некорректный запрос")
async def call_store(func, *args):
try:
return await anyio.to_thread.run_sync(func, *args)
except DependencyDown:
unavailable()
except IdempotencyConflict:
raise ApiError(409, "conflict", "Ключ уже использован с другим телом")
except AttachmentRejected:
raise ApiError(409, "conflict", "Вложение нельзя прикрепить")
except AttachmentNotReady:
raise ApiError(409, "conflict", "Вложение недоступно")
def parse_basic(request: Request):
header = request.headers.get("Authorization", "")
if not header.lower().startswith("basic "):
basic_unauthorized()
raw = header.split(" ", 1)[1].strip()
try:
import base64
decoded = base64.b64decode(raw, validate=True).decode("utf-8")
except (ValueError, UnicodeError):
basic_unauthorized()
if ":" not in decoded:
basic_unauthorized()
username, password = decoded.split(":", 1)
return username, password
def parse_bearer(request: Request):
header = request.headers.get("Authorization", "")
# Basic на бизнес-методе не открывает сессию. X-User-Id не смотрим.
if not header.lower().startswith("bearer "):
bearer_unauthorized()
token = header.split(" ", 1)[1].strip()
if len(token) < 32 or len(token) > 512 or any(ch.isspace() for ch in token):
bearer_unauthorized()
return token
async def current_user(request: Request):
token = parse_bearer(request)
user = await call_store(store.user_for_token, token)
if user is None:
bearer_unauthorized()
request.state.user_id = user["id"]
request.state.token = token
return user
def parse_chat_id(chat_id):
try:
return str(uuid.UUID(chat_id))
except ValueError:
invalid()
def parse_limit(raw):
if raw is None:
return 50
if not isinstance(raw, str) or len(raw) > 3 or not raw.isdigit():
invalid()
value = int(raw)
if value < 1 or value > 100:
invalid()
return value
async def read_json(request: Request):
ctype = request.headers.get("content-type", "")
if "application/json" not in ctype.lower():
raise ApiError(415, "unsupported_media_type", "Нужен application/json")
length = request.headers.get("content-length")
if length is not None and (not length.isdigit() or int(length) > MAX_JSON_BYTES):
raise ApiError(413, "payload_too_large", "Слишком большое тело")
raw = await request.body()
if len(raw) > MAX_JSON_BYTES:
raise ApiError(413, "payload_too_large", "Слишком большое тело")
try:
payload = json.loads(raw)
except (ValueError, UnicodeError):
invalid()
if not isinstance(payload, dict):
invalid()
return payload
def parse_idempotency_key(request: Request):
key = request.headers.get("Idempotency-Key")
if key is None or not IDEMPOTENCY_RE.fullmatch(key):
invalid()
return key
@app.get("/health/live")
async def liveness(request: Request):
return json_ok(request, {"status": "ok"})
@app.get("/health/ready")
async def readiness(request: Request):
if store.shutting_down:
raise ApiError(503, "unavailable", "Сервис временно недоступен")
ok = await call_store(store.ready)
if not ok:
unavailable()
return json_ok(request, {"status": "ok"})
@app.post("/api/v1/users", status_code=201)
async def register_user(request: Request, body: CreateUser):
user = await call_store(store.create_user, body.username, body.display_name, body.password)
if user is None:
raise ApiError(409, "conflict", "Имя пользователя занято")
return json_ok(request, user, 201)
@app.post("/api/v1/auth/sessions", status_code=201)
async def create_session(request: Request):
username, password = parse_basic(request)
session = await call_store(store.login, username, password)
if session is None:
basic_unauthorized()
request.state.user_id = session["user"]["id"]
return json_ok(request, session, 201)
@app.delete("/api/v1/auth/sessions/current", status_code=204)
async def revoke_session(request: Request):
user = await current_user(request)
request.state.user_id = user["id"]
removed = await call_store(store.revoke, request.state.token)
if not removed:
bearer_unauthorized()
return stamp(request, Response(status_code=204))
@app.get("/api/v1/users/me")
async def me(request: Request):
user = await current_user(request)
return json_ok(request, user)
@app.post("/api/v1/chats", status_code=201)
async def create_chat(request: Request):
user = await current_user(request)
payload = await read_json(request)
try:
body = CreateChat.model_validate(payload)
except ValidationError:
invalid()
try:
chat = await call_store(store.create_chat, body.title, body.member_ids, user["id"])
except ValueError:
invalid()
return json_ok(request, chat, 201)
@app.get("/api/v1/chats")
async def list_chats(request: Request):
user = await current_user(request)
limit = parse_limit(request.query_params.get("limit"))
cursor = request.query_params.get("cursor")
if cursor is not None and (not cursor or len(cursor) > 512):
invalid()
try:
items, next_cursor = await call_store(store.list_chats, user["id"], limit, cursor)
except ValueError:
invalid()
return json_ok(request, {"items": items, "next_cursor": next_cursor})
@app.get("/api/v1/chats/{chat_id}")
async def get_chat(request: Request, chat_id: str):
user = await current_user(request)
chat = await call_store(store.get_chat, parse_chat_id(chat_id), user["id"])
if chat is None:
raise ApiError(404, "not_found", "Объект не найден")
return json_ok(request, chat)
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
async def create_message(request: Request, chat_id: str):
user = await current_user(request)
canonical = parse_chat_id(chat_id)
payload = await read_json(request)
key = parse_idempotency_key(request)
try:
body = CreateMessage.model_validate(payload)
except ValidationError:
invalid()
try:
message = await call_store(
store.add_message, canonical, user["id"], body.text, key, body.attachment_ids
)
except ValueError:
invalid()
if message is None:
raise ApiError(404, "not_found", "Объект не найден")
return json_ok(request, message, 201)
@app.get("/api/v1/chats/{chat_id}/messages")
async def list_messages(request: Request, chat_id: str):
user = await current_user(request)
canonical = parse_chat_id(chat_id)
limit = parse_limit(request.query_params.get("limit"))
cursor = request.query_params.get("cursor")
if cursor is not None and (not cursor or len(cursor) > 512):
invalid()
try:
result = await call_store(store.list_messages, canonical, user["id"], limit, cursor)
except ValueError:
invalid()
if result is None:
raise ApiError(404, "not_found", "Объект не найден")
items, next_cursor = result
return json_ok(request, {"items": items, "next_cursor": next_cursor})
def check_filename(value):
if not isinstance(value, str) or not value or len(value) > 255:
invalid()
if "/" in value or "\\" in value or "\x00" in value:
invalid()
if any(ord(char) < 32 or ord(char) == 127 for char in value):
invalid()
return value
def parse_attachment_id(value):
try:
return str(uuid.UUID(value))
except (TypeError, ValueError):
invalid()
async def read_upload(request: Request):
header = request.headers.get("content-length")
if header is not None:
try:
announced = int(header)
except ValueError:
invalid()
if announced > MAX_BYTES:
raise ApiError(413, "payload_too_large", "Файл больше 10 МиБ")
if announced < 1:
raise ApiError(415, "unsupported_media_type", "Нужен PNG или JPEG")
chunks = []
total = 0
async for chunk in request.stream():
total += len(chunk)
if total > MAX_BYTES:
raise ApiError(413, "payload_too_large", "Файл больше 10 МиБ")
chunks.append(chunk)
if total < 1:
raise ApiError(415, "unsupported_media_type", "Нужен PNG или JPEG")
return b"".join(chunks)
@app.post("/api/v1/chats/{chat_id}/attachments", status_code=202)
async def upload_attachment(request: Request, chat_id: str):
user = await current_user(request)
canonical = parse_chat_id(chat_id)
member = await call_store(store.is_member, canonical, user["id"])
if not member:
raise ApiError(404, "not_found", "Объект не найден")
filename = check_filename(request.query_params.get("filename"))
media = declared_type(request.headers.get("content-type"))
if media is None:
raise ApiError(415, "unsupported_media_type", "Нужен PNG или JPEG")
data = await read_upload(request)
content_type = await anyio.to_thread.run_sync(inspect_image, data, media)
saved = await call_store(
store.save_attachment, canonical, user["id"], filename, content_type, data
)
if saved is None:
raise ApiError(404, "not_found", "Объект не найден")
return json_ok(request, saved, 202)
@app.get("/api/v1/attachments/{attachment_id}")
async def get_attachment(request: Request, attachment_id: str):
user = await current_user(request)
canonical = parse_attachment_id(attachment_id)
found = await call_store(store.get_attachment, canonical, user["id"])
if found is None:
raise ApiError(404, "not_found", "Объект не найден")
return json_ok(request, found)
@app.get("/api/v1/attachments/{attachment_id}/content")
async def download_attachment(request: Request, attachment_id: str):
user = await current_user(request)
canonical = parse_attachment_id(attachment_id)
variant = request.query_params.get("variant")
if variant is None:
variant = "original"
if variant not in ("original", "thumbnail", "crop", "optimized"):
invalid()
opened = await call_store(store.open_attachment, canonical, user["id"], variant)
if opened is None:
raise ApiError(404, "not_found", "Объект не найден")
def chunks():
body = open_object(opened["object_key"])
if body is None:
return
try:
for piece in body.stream(64 * 1024):
yield piece
finally:
body.close()
body.release_conn()
probe = await anyio.to_thread.run_sync(open_object, opened["object_key"])
if probe is None:
raise ApiError(404, "not_found", "Объект не найден")
probe.close()
probe.release_conn()
response = StreamingResponse(chunks(), media_type=opened["content_type"])
response.headers["Content-Length"] = str(opened["size_bytes"])
return stamp(request, response)
def setup_logging():
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
if __name__ == "__main__":
import uvicorn
setup_logging()
setup_telemetry(os.environ.get("OTEL_SERVICE_NAME", "messenger-api"))
host = os.environ.get("APP_HOST", "0.0.0.0")
port = int(os.environ.get("APP_PORT", "8080"))
uvicorn.run(
app,
host=host,
port=port,
timeout_graceful_shutdown=5,
timeout_keep_alive=2,
access_log=False,
log_config=None,
)
+112
View File
@@ -0,0 +1,112 @@
"""Однократные миграции. Запускается отдельным контейнером, не каждой репликой API."""
import logging
import os
import sys
import time
from pathlib import Path
import psycopg
from psycopg.rows import dict_row
LOGGER = logging.getLogger("migrate")
MIGRATION_LOCK = 421003
CONNECT_TIMEOUT = 3
def read_secret_file(path):
with open(path, encoding="utf-8") as handle:
return handle.read().strip()
def database_url():
path = os.environ.get("DATABASE_URL_FILE")
if path:
return read_secret_file(path)
url = os.environ.get("DATABASE_URL", "").strip()
if not url:
raise RuntimeError("DATABASE_URL_FILE")
return url
def split_sql(script):
parts = []
buf = []
for line in script.splitlines():
if line.strip().startswith("--"):
continue
buf.append(line)
if line.strip().endswith(";"):
statement = "\n".join(buf).strip()
if statement.endswith(";"):
statement = statement[:-1].strip()
if statement:
parts.append(statement)
buf = []
tail = "\n".join(buf).strip().rstrip(";").strip()
if tail:
parts.append(tail)
return parts
def wait_postgres(conninfo):
last = None
for _ in range(60):
try:
with psycopg.connect(conninfo, connect_timeout=CONNECT_TIMEOUT) as conn:
conn.execute("SELECT 1")
return
except psycopg.OperationalError as exc:
last = type(exc).__name__
time.sleep(1)
LOGGER.error("postgres not ready: %s", last)
raise SystemExit(1)
def apply(conninfo):
directory = Path(__file__).resolve().parents[1] / "migrations"
with psycopg.connect(conninfo, connect_timeout=CONNECT_TIMEOUT, row_factory=dict_row) as conn:
conn.execute("SELECT pg_advisory_lock(%s)", (MIGRATION_LOCK,))
conn.commit()
try:
conn.execute(
"""
CREATE TABLE IF NOT EXISTS schema_migrations (
version text PRIMARY KEY,
applied_at timestamptz NOT NULL DEFAULT now()
)
"""
)
conn.commit()
for path in sorted(directory.glob("*.sql")):
version = path.stem
found = conn.execute(
"SELECT 1 FROM schema_migrations WHERE version = %s",
(version,),
).fetchone()
conn.rollback()
if found:
LOGGER.info("migration %s already applied", version)
continue
with conn.transaction():
for statement in split_sql(path.read_text(encoding="utf-8")):
conn.execute(statement)
conn.execute(
"INSERT INTO schema_migrations (version) VALUES (%s)",
(version,),
)
LOGGER.info("migration %s applied", version)
finally:
conn.execute("SELECT pg_advisory_unlock(%s)", (MIGRATION_LOCK,))
conn.commit()
def main():
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
conninfo = database_url()
wait_postgres(conninfo)
apply(conninfo)
return 0
if __name__ == "__main__":
sys.exit(main())
+26
View File
@@ -0,0 +1,26 @@
from argon2 import PasswordHasher
from argon2.exceptions import InvalidHash, VerificationError, VerifyMismatchError
# Параметры ближе к учебному стенду, чем к максимальным: time=2, 19 MiB, Argon2id.
# Хеш всё равно медленный password KDF, не SHA-256 и не открытый текст.
hasher = PasswordHasher(
time_cost=2,
memory_cost=19456,
parallelism=1,
hash_len=32,
salt_len=16,
)
# Чтобы неизвестный username не отвечал заметно быстрее известного.
DUMMY_HASH = hasher.hash("dummy-password-not-a-user")
def hash_password(password):
return hasher.hash(password)
def verify_password(password, encoded):
try:
return hasher.verify(encoded, password)
except (VerifyMismatchError, VerificationError, InvalidHash):
return False
+174
View File
@@ -0,0 +1,174 @@
"""Сверка строк attachments и объектов bucket.
Свежий объект моложе grace не удаляется: загрузка могла записать файл
раньше, чем строка в базе. Строка, на которую ссылается сообщение, тоже
не удаляется, даже если файла уже нет. По умолчанию только план, без удалений.
"""
import argparse
import json
import os
import sys
import time
from datetime import datetime, timezone
import psycopg
from psycopg.rows import dict_row
from blobs import BUCKET, delete_quiet, list_objects
def grace_seconds():
raw = os.environ.get("RECONCILE_GRACE_SECONDS", "120")
value = int(raw)
if value < 1:
raise RuntimeError("RECONCILE_GRACE_SECONDS")
return value
def database_url():
path = os.environ.get("DATABASE_URL_FILE")
if not path:
raise RuntimeError("DATABASE_URL_FILE")
with open(path, encoding="utf-8") as handle:
return handle.read().strip()
def aware(value):
if value is None:
return None
if value.tzinfo is None:
return value.replace(tzinfo=timezone.utc)
return value.astimezone(timezone.utc)
def plan(grace):
started = time.perf_counter()
objects = list_objects()
listed = time.perf_counter()
now = datetime.now(timezone.utc)
with psycopg.connect(database_url(), row_factory=dict_row) as conn:
rows = conn.execute(
"""
SELECT a.id, a.object_key, a.staging_key, a.created_at, a.status,
EXISTS (
SELECT 1 FROM message_attachments m
WHERE m.attachment_id = a.id
) AS in_use
FROM attachments a
"""
).fetchall()
variant_rows = conn.execute("SELECT object_key FROM attachment_variants").fetchall()
by_key = {}
for row in rows:
by_key[row["object_key"]] = row
if row["staging_key"]:
by_key[row["staging_key"]] = row
for item in variant_rows:
by_key.setdefault(item["object_key"], {"status": "variant"})
object_keys = {item["key"] for item in objects}
actions = []
preserved = []
for item in objects:
row = by_key.get(item["key"])
if row is not None:
continue
created = aware(item["created_at"]) or now
age = (now - created).total_seconds()
entry = {"key": item["key"], "age_seconds": round(age, 3)}
if age < grace:
entry["reason"] = "fresh_object"
preserved.append(entry)
continue
entry["action"] = "delete_orphan_object"
actions.append(entry)
for row in rows:
if row["object_key"] in object_keys:
continue
created = aware(row["created_at"]) or now
age = (now - created).total_seconds()
entry = {
"attachment_id": str(row["id"]),
"key": row["object_key"],
"age_seconds": round(age, 3),
}
if row["status"] != "ready":
entry["reason"] = "not_ready"
preserved.append(entry)
continue
if row["in_use"]:
entry["reason"] = "missing_but_in_use"
preserved.append(entry)
continue
if age < grace:
entry["reason"] = "fresh_row"
preserved.append(entry)
continue
entry["action"] = "delete_orphan_row"
actions.append(entry)
return {
"bucket": BUCKET,
"grace_seconds": grace,
"objects": len(objects),
"rows": len(rows),
"list_seconds": round(listed - started, 6),
"plan_seconds": round(time.perf_counter() - started, 6),
"actions": actions,
"preserved": preserved,
}
def apply_plan(report):
deleted_objects = 0
deleted_rows = 0
with psycopg.connect(database_url(), row_factory=dict_row) as conn:
for action in report["actions"]:
if action["action"] == "delete_orphan_object":
if delete_quiet(action["key"]):
deleted_objects += 1
elif action["action"] == "delete_orphan_row":
with conn.transaction():
result = conn.execute(
"""
DELETE FROM attachments
WHERE id = %s
AND status = 'ready'
AND NOT EXISTS (
SELECT 1 FROM message_attachments m
WHERE m.attachment_id = attachments.id
)
AND NOT EXISTS (
SELECT 1 FROM attachment_jobs j
WHERE j.attachment_id = attachments.id
)
AND NOT EXISTS (
SELECT 1 FROM attachment_variants v
WHERE v.attachment_id = attachments.id
)
""",
(action["attachment_id"],),
)
deleted_rows += result.rowcount
report["deleted_objects"] = deleted_objects
report["deleted_rows"] = deleted_rows
return report
def main():
parser = argparse.ArgumentParser(description="Сверить вложения в базе и в bucket")
parser.add_argument("--apply", action="store_true", help="выполнить удаления; без флага только план")
parser.add_argument("--grace", type=int, default=None)
args = parser.parse_args()
grace = args.grace if args.grace is not None else grace_seconds()
if grace < 1:
print("grace должен быть не меньше 1 секунды", file=sys.stderr)
return 2
report = plan(grace)
report["apply"] = bool(args.apply)
if args.apply:
apply_plan(report)
print(json.dumps(report, ensure_ascii=False, sort_keys=True))
return 0
if __name__ == "__main__":
raise SystemExit(main())
+24
View File
@@ -0,0 +1,24 @@
"""Явный повтор failed-задания. Уже готовый эффект второй раз не исполняется."""
import json
import sys
import psycopg
from psycopg.rows import dict_row
from blobs import read_secret
from jobs import replay_job
def main():
if len(sys.argv) != 2:
print("usage: replay.py JOB_ID", file=sys.stderr)
return 2
url = read_secret(__import__("os").environ["DATABASE_URL_FILE"])
with psycopg.connect(url, row_factory=dict_row) as conn:
result = replay_job(conn, sys.argv[1])
print(json.dumps(result, ensure_ascii=False))
return 0
if __name__ == "__main__":
raise SystemExit(main())
+128
View File
@@ -0,0 +1,128 @@
import re
import uuid
from pydantic import BaseModel, ConfigDict, field_validator, model_validator
USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$")
class StrictModel(BaseModel):
model_config = ConfigDict(extra="forbid")
def _visible(value, limit):
if not isinstance(value, str) or not value.strip() or len(value) > limit:
raise ValueError("text")
return value
class CreateUser(StrictModel):
username: str
display_name: str
password: str
@field_validator("username")
@classmethod
def username_ok(cls, value):
if not isinstance(value, str) or not USERNAME_RE.fullmatch(value):
raise ValueError("username")
return value
@field_validator("display_name")
@classmethod
def display_name_ok(cls, value):
return _visible(value, 100)
@field_validator("password")
@classmethod
def password_ok(cls, value):
if not isinstance(value, str) or not value.strip():
raise ValueError("password")
# Длина в code points, не в байтах: bcrypt тут не подходит из-за усечения UTF-8.
if len(value) < 12 or len(value) > 128:
raise ValueError("password")
return value
class CreateChat(StrictModel):
title: str
member_ids: list
@field_validator("title")
@classmethod
def title_ok(cls, value):
return _visible(value, 100)
@field_validator("member_ids")
@classmethod
def member_ids_ok(cls, value):
if not isinstance(value, list) or not (1 <= len(value) <= 100):
raise ValueError("member_ids")
# Канонический UUID (нижний регистр). Иначе один и тот же id
# в разном регистре выглядит как два участника и упирается в PK.
normalized = []
seen = set()
for item in value:
if not isinstance(item, str):
raise ValueError("member_ids")
try:
canonical = str(uuid.UUID(item))
except ValueError as exc:
raise ValueError("member_ids") from exc
if canonical in seen:
raise ValueError("member_ids")
seen.add(canonical)
normalized.append(canonical)
return normalized
class CreateMessage(StrictModel):
text: str
attachment_ids: list = []
@model_validator(mode="before")
@classmethod
def fill_attachments(cls, value):
# Нет поля и явный [] — одно и то же тело для Idempotency-Key.
if not isinstance(value, dict):
return value
data = dict(value)
data.setdefault("attachment_ids", [])
return data
@field_validator("text")
@classmethod
def text_ok(cls, value):
if not isinstance(value, str) or len(value) > 4000:
raise ValueError("text")
if value != "" and not value.strip():
raise ValueError("text")
return value
@field_validator("attachment_ids")
@classmethod
def attachments_ok(cls, value):
if not isinstance(value, list) or len(value) > 10:
raise ValueError("attachment_ids")
normalized = []
seen = set()
for item in value:
if not isinstance(item, str):
raise ValueError("attachment_ids")
try:
canonical = str(uuid.UUID(item))
except ValueError as exc:
raise ValueError("attachment_ids") from exc
if canonical in seen:
raise ValueError("attachment_ids")
seen.add(canonical)
normalized.append(canonical)
return normalized
@model_validator(mode="after")
def text_or_file(self):
if self.text == "" and not self.attachment_ids:
raise ValueError("text")
if self.text and not self.text.strip():
raise ValueError("text")
return self
+924
View File
@@ -0,0 +1,924 @@
import base64
import hashlib
import json
import logging
import os
import secrets
import socket
import time
import uuid
from datetime import datetime, timedelta, timezone
import psycopg
import redis
from psycopg.errors import CheckViolation, ForeignKeyViolation, UniqueViolation
from psycopg.rows import dict_row
from psycopg_pool import ConnectionPool, PoolTimeout
from errors import AttachmentNotReady, AttachmentRejected, DependencyDown, IdempotencyConflict
from passwords import DUMMY_HASH, hash_password, verify_password
LOGGER = logging.getLogger("messenger")
POOL_TIMEOUT_SECONDS = 3
STATEMENT_TIMEOUT_MS = 5000
LOCK_TIMEOUT_MS = 3000
REDIS_MAX_CONNECTIONS = 16
REDIS_SOCKET_TIMEOUT = 2
SCHEMA_VERSION = "004_jobs"
SQL_MESSAGES_FIRST = """
SELECT id, chat_id, sender_id, body AS text, created_at
FROM messages
WHERE chat_id = %s
ORDER BY created_at, id
LIMIT %s
"""
SQL_MESSAGES_AFTER = """
SELECT id, chat_id, sender_id, body AS text, created_at
FROM messages
WHERE chat_id = %s
AND (created_at, id) > (%s, %s)
ORDER BY created_at, id
LIMIT %s
"""
SQL_MESSAGE_BY_ID = """
SELECT id, chat_id, sender_id, body AS text, created_at
FROM messages
WHERE id = %s
"""
def instance_id():
# Docker без hostname: в контейнере это id контейнера, он не меняется,
# пока живёт этот контейнер. stop-one.sh находит контейнер по этому значению.
return socket.gethostname()
def pool_max():
raw = os.environ.get("POOL_MAX", "10")
try:
value = int(raw)
except ValueError as exc:
raise RuntimeError("POOL_MAX") from exc
if not 1 <= value <= 32:
raise RuntimeError("POOL_MAX")
return value
def utc_now():
return datetime.now(timezone.utc)
def dump_time(value):
if value.tzinfo is None:
value = value.replace(tzinfo=timezone.utc)
text = value.astimezone(timezone.utc).isoformat(timespec="microseconds")
if text.endswith("+00:00"):
text = text[:-6] + "Z"
return text
def parse_time(value):
if not isinstance(value, str) or not value.endswith("Z"):
raise ValueError("time")
return datetime.fromisoformat(value[:-1] + "+00:00")
def encode_cursor(scope, created_at, item_id):
raw = "{}|{}|{}".format(scope, created_at, item_id).encode("utf-8")
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
def decode_cursor(cursor, expected_scope):
if not isinstance(cursor, str) or not cursor or len(cursor) > 512:
raise ValueError("cursor")
pad = "=" * (-len(cursor) % 4)
try:
decoded = base64.urlsafe_b64decode(cursor + pad).decode("utf-8")
except (ValueError, UnicodeError) as exc:
raise ValueError("cursor") from exc
parts = decoded.split("|")
if len(parts) != 3:
raise ValueError("cursor")
scope, created_at, item_id = parts
if scope != expected_scope:
raise ValueError("cursor")
parse_time(created_at)
try:
uuid.UUID(item_id)
except ValueError as exc:
raise ValueError("cursor") from exc
return created_at, item_id
def session_key(token):
digest = hashlib.sha256(token.encode("utf-8")).hexdigest()
return "sess:" + digest
def message_fingerprint(text, attachment_ids):
# Канонический JSON: порядок ключей не важен, пропущенный attachment_ids равен [].
canonical = json.dumps(
{"attachment_ids": list(attachment_ids), "text": text},
ensure_ascii=False,
sort_keys=True,
separators=(",", ":"),
)
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
def advisory_key(user_id, path, idem_key):
raw = "\0".join((user_id, "POST", path, idem_key)).encode("utf-8")
digest = hashlib.sha256(raw).digest()
return int.from_bytes(digest[:8], "big", signed=True)
def chat_path(chat_id):
return "/api/v1/chats/" + chat_id + "/messages"
def public_user(row):
return {
"id": str(row["id"]),
"username": row["username"],
"display_name": row["display_name"],
"created_at": dump_time(row["created_at"]),
}
def public_message(row, attachment_ids=None):
return {
"id": str(row["id"]),
"chat_id": str(row["chat_id"]),
"sender_id": str(row["sender_id"]),
"text": row["text"],
"attachment_ids": list(attachment_ids or []),
"created_at": dump_time(row["created_at"]),
}
def public_variant(row):
return {
"name": row["name"],
"content_type": row["content_type"],
"size_bytes": int(row["size_bytes"]),
"width": int(row["width"]),
"height": int(row["height"]),
"sha256": row["sha256"],
}
def public_attachment(row, variants=None):
return {
"id": str(row["id"]),
"chat_id": str(row["chat_id"]),
"owner_id": str(row["owner_id"]),
"filename": row["filename"],
"content_type": row["content_type"],
"size_bytes": int(row["size_bytes"]),
"sha256": row["sha256"],
"status": row["status"],
"variants": [public_variant(item) for item in (variants or [])],
"error_code": row["error_code"],
"created_at": dump_time(row["created_at"]),
"updated_at": dump_time(row["updated_at"]),
}
def public_chat(row, member_ids=None):
members = member_ids if member_ids is not None else row["member_ids"]
return {
"id": str(row["id"]),
"title": row["title"],
"member_ids": [str(item) for item in members],
"created_at": dump_time(row["created_at"]),
}
def read_secret_file(path):
with open(path, encoding="utf-8") as handle:
return handle.read().strip()
def _db_down(exc):
raise DependencyDown() from exc
class Store:
def __init__(self):
self.pool = None
self.redis = None
self.ttl = int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
self.idem_ttl = int(os.environ.get("IDEMPOTENCY_TTL_SECONDS", "86400"))
self.pool_size = pool_max()
self.shutting_down = False
if self.ttl < 1 or self.idem_ttl < 1:
raise RuntimeError("TTL")
kind = os.environ.get("SESSION_STORE", "redis").strip().lower()
if kind != "redis":
raise RuntimeError("SESSION_STORE")
def database_url(self):
path = os.environ.get("DATABASE_URL_FILE")
if path:
return read_secret_file(path)
url = os.environ.get("DATABASE_URL", "").strip()
if not url:
raise RuntimeError("DATABASE_URL_FILE")
return url
def redis_url(self):
path = os.environ.get("CACHE_URL_FILE")
if path:
return read_secret_file(path)
url = os.environ.get("CACHE_URL", "").strip()
if not url:
raise RuntimeError("CACHE_URL_FILE")
return url
def startup(self):
conninfo = self.database_url()
self._wait_schema(conninfo)
self.pool = ConnectionPool(
conninfo,
min_size=1,
max_size=self.pool_size,
timeout=POOL_TIMEOUT_SECONDS,
max_waiting=64,
max_lifetime=300,
kwargs={
"connect_timeout": POOL_TIMEOUT_SECONDS,
"row_factory": dict_row,
"application_name": "mtusi-lab6-" + instance_id(),
"options": "-c statement_timeout={} -c lock_timeout={} -c idle_in_transaction_session_timeout=15000".format(
STATEMENT_TIMEOUT_MS,
LOCK_TIMEOUT_MS,
),
},
open=True,
)
pool = redis.ConnectionPool.from_url(
self.redis_url(),
max_connections=REDIS_MAX_CONNECTIONS,
socket_timeout=REDIS_SOCKET_TIMEOUT,
socket_connect_timeout=REDIS_SOCKET_TIMEOUT,
health_check_interval=30,
decode_responses=True,
)
self.redis = redis.Redis(connection_pool=pool)
self._wait_redis()
self._wait_bucket()
try:
from broker import broker_channel, publish_pending
with broker_channel():
pass
with self._connect() as conn:
publish_pending(conn)
except Exception as exc:
LOGGER.warning("outbox startup deferred %s", type(exc).__name__)
self._start_queue_metrics()
LOGGER.info("ready instance=%s ttl=%s pool_max=%s", instance_id(), self.ttl, self.pool_size)
def _start_queue_metrics(self):
# Метрики возраста очереди должны жить и при остановленном worker.
import threading
def loop():
from broker import PROCESS_QUEUE, RETRY_QUEUE, queue_depth
from telemetry import observe_process, set_queue_stats
while not self.shutting_down:
try:
age = 0.0
with self._connect() as conn:
row = conn.execute(
"""
SELECT EXTRACT(EPOCH FROM (now() - MIN(created_at))) AS age
FROM attachment_jobs
WHERE status IN ('queued', 'processing')
"""
).fetchone()
if row is not None and row["age"] is not None:
age = float(row["age"])
try:
depth = queue_depth(PROCESS_QUEUE)
except Exception:
depth = 0
try:
retry_depth = queue_depth(RETRY_QUEUE)
except Exception:
retry_depth = 0
set_queue_stats(PROCESS_QUEUE, depth, age)
set_queue_stats(RETRY_QUEUE, retry_depth, 0.0)
self.refresh_pool_stats()
observe_process()
except Exception as exc:
LOGGER.warning("queue metrics %s", type(exc).__name__)
time.sleep(5)
threading.Thread(target=loop, name="queue-metrics", daemon=True).start()
def shutdown(self):
self.shutting_down = True
if self.pool is not None:
self.pool.close()
if self.redis is not None:
self.redis.close()
def ready(self):
if self.shutting_down or self.pool is None or self.redis is None:
return False
try:
with self.pool.connection(timeout=POOL_TIMEOUT_SECONDS) as conn:
row = conn.execute(
"SELECT 1 FROM schema_migrations WHERE version = %s",
(SCHEMA_VERSION,),
).fetchone()
if row is None:
return False
self.redis.ping()
from blobs import bucket_ready
if not bucket_ready():
return False
except Exception:
LOGGER.warning("ready check failed")
return False
return True
def _wait_redis(self):
last = None
for _ in range(60):
try:
self.redis.ping()
return
except redis.RedisError as exc:
last = type(exc).__name__
time.sleep(1)
LOGGER.error("redis not ready: %s", last)
raise SystemExit(1)
def _wait_schema(self, conninfo):
# Схему накатывает сервис migrate. Реплики только ждут её, не применяют сами.
last = None
for _ in range(90):
try:
with psycopg.connect(conninfo, connect_timeout=POOL_TIMEOUT_SECONDS, row_factory=dict_row) as conn:
row = conn.execute(
"SELECT 1 FROM schema_migrations WHERE version = %s",
(SCHEMA_VERSION,),
).fetchone()
if row is not None:
return
last = "migration missing"
except psycopg.Error as exc:
last = type(exc).__name__
time.sleep(1)
LOGGER.error("schema not ready: %s", last)
raise SystemExit(1)
def _wait_bucket(self):
from blobs import bucket_ready
for _ in range(60):
if bucket_ready():
return
time.sleep(1)
LOGGER.error("object storage not ready")
raise SystemExit(1)
def refresh_pool_stats(self):
if self.pool is None:
return
try:
from telemetry import set_pool_stats
stats = self.pool.get_stats()
used = int(stats.get("pool_size", 0)) - int(stats.get("pool_available", 0))
waiting = int(stats.get("requests_waiting", 0))
set_pool_stats(max(0, used), waiting)
except Exception:
pass
def _connect(self):
self.refresh_pool_stats()
try:
return self.pool.connection(timeout=POOL_TIMEOUT_SECONDS)
except PoolTimeout as exc:
_db_down(exc)
def create_user(self, username, display_name, password):
password_hash = hash_password(password)
user_id = uuid.uuid4()
created = utc_now()
try:
with self._connect() as conn:
with conn.transaction():
row = conn.execute(
"""
INSERT INTO users (id, username, display_name, password_hash, created_at)
VALUES (%s, %s, %s, %s, %s)
ON CONFLICT (username) DO NOTHING
RETURNING id, username, display_name, created_at
""",
(user_id, username, display_name, password_hash, created),
).fetchone()
except psycopg.OperationalError as exc:
_db_down(exc)
if row is None:
return None
return public_user(row)
def login(self, username, password):
try:
with self._connect() as conn:
row = conn.execute(
"""
SELECT id, username, display_name, password_hash, created_at
FROM users
WHERE username = %s
""",
(username,),
).fetchone()
except psycopg.OperationalError as exc:
_db_down(exc)
if row is None:
verify_password(password, DUMMY_HASH)
return None
if not verify_password(password, row["password_hash"]):
return None
return self._issue(public_user(row))
def _issue(self, user):
token = secrets.token_urlsafe(32)
expires = utc_now() + timedelta(seconds=self.ttl)
payload = json.dumps(
{"user_id": user["id"], "expires_at": dump_time(expires)},
separators=(",", ":"),
)
# pxat — абсолютное время. Рестарт Redis не сдвигает срок.
# В значении тоже лежит expires_at: даже если TTL ключа разъедется, сессия кончится вовремя.
try:
self.redis.set(session_key(token), payload, pxat=int(expires.timestamp() * 1000))
except redis.RedisError as exc:
raise DependencyDown() from exc
return {
"token": token,
"token_type": "Bearer",
"expires_at": dump_time(expires),
"user": user,
}
def user_for_token(self, token):
key = session_key(token)
try:
raw = self.redis.get(key)
except redis.RedisError as exc:
raise DependencyDown() from exc
if not raw:
return None
try:
payload = json.loads(raw)
expires = parse_time(payload["expires_at"])
user_id = payload["user_id"]
uuid.UUID(user_id)
except (ValueError, KeyError, TypeError):
return None
if utc_now() >= expires:
try:
self.redis.delete(key)
except redis.RedisError as exc:
raise DependencyDown() from exc
return None
try:
with self._connect() as conn:
row = conn.execute(
"""
SELECT id, username, display_name, created_at
FROM users
WHERE id = %s
""",
(user_id,),
).fetchone()
except psycopg.OperationalError as exc:
_db_down(exc)
if row is None:
return None
return public_user(row)
def revoke(self, token):
try:
deleted = self.redis.delete(session_key(token))
except redis.RedisError as exc:
raise DependencyDown() from exc
return deleted == 1
def create_chat(self, title, member_ids, caller_id):
try:
caller_uuid = uuid.UUID(str(caller_id))
member_uuids = []
seen = set()
for item in member_ids:
member_uuid = uuid.UUID(str(item))
if member_uuid in seen:
raise ValueError("members")
seen.add(member_uuid)
member_uuids.append(member_uuid)
except ValueError as exc:
raise ValueError("members") from exc
if caller_uuid not in seen:
raise ValueError("members")
chat_id = uuid.uuid4()
created = utc_now()
canonical_members = [str(item) for item in member_uuids]
try:
with self._connect() as conn:
try:
with conn.transaction():
conn.execute(
"INSERT INTO chats (id, title, created_at) VALUES (%s, %s, %s)",
(chat_id, title, created),
)
for ordinal, member_id in enumerate(member_uuids):
conn.execute(
"""
INSERT INTO chat_members (chat_id, user_id, ordinal)
VALUES (%s, %s, %s)
""",
(chat_id, member_id, ordinal),
)
row = conn.execute(
"SELECT id, title, created_at FROM chats WHERE id = %s",
(chat_id,),
).fetchone()
except ForeignKeyViolation as exc:
raise ValueError("members") from exc
except UniqueViolation as exc:
raise ValueError("members") from exc
except psycopg.OperationalError as exc:
_db_down(exc)
return public_chat(row, canonical_members)
def _member(self, conn, chat_id, user_id):
return conn.execute(
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s",
(chat_id, user_id),
).fetchone()
def get_chat(self, chat_id, user_id):
try:
with self._connect() as conn:
if self._member(conn, chat_id, user_id) is None:
return None
row = conn.execute(
"""
SELECT c.id, c.title, c.created_at,
array_agg(m.user_id ORDER BY m.ordinal) AS member_ids
FROM chats c
JOIN chat_members m ON m.chat_id = c.id
WHERE c.id = %s
GROUP BY c.id
""",
(chat_id,),
).fetchone()
except psycopg.OperationalError as exc:
_db_down(exc)
if row is None:
return None
return public_chat(row)
def list_chats(self, user_id, limit, cursor):
after = None
if cursor is not None:
created_at, item_id = decode_cursor(cursor, "chats:" + user_id)
after = (parse_time(created_at), uuid.UUID(item_id))
sql = """
SELECT c.id, c.title, c.created_at,
array_agg(m.user_id ORDER BY m.ordinal) AS member_ids
FROM chats c
JOIN chat_members mine ON mine.chat_id = c.id AND mine.user_id = %s
JOIN chat_members m ON m.chat_id = c.id
"""
params = [user_id]
if after is not None:
sql += " WHERE (c.created_at, c.id) > (%s, %s)"
params.extend(after)
sql += " GROUP BY c.id ORDER BY c.created_at, c.id LIMIT %s"
params.append(limit + 1)
try:
with self._connect() as conn:
rows = conn.execute(sql, params).fetchall()
except psycopg.OperationalError as exc:
_db_down(exc)
page = [public_chat(row) for row in rows[:limit]]
if len(rows) > limit and page:
last = page[-1]
return page, encode_cursor("chats:" + user_id, last["created_at"], last["id"])
return page, None
def _attachment_ids(self, conn, message_ids):
if not message_ids:
return {}
rows = conn.execute(
"""
SELECT message_id, attachment_id
FROM message_attachments
WHERE message_id = ANY(%s::uuid[])
ORDER BY ordinal
""",
(list(message_ids),),
).fetchall()
found = {}
for row in rows:
found.setdefault(str(row["message_id"]), []).append(str(row["attachment_id"]))
return found
def is_member(self, chat_id, user_id):
try:
with self._connect() as conn:
return self._member(conn, chat_id, user_id) is not None
except psycopg.OperationalError as exc:
_db_down(exc)
def _variants(self, conn, attachment_id, pipeline_version):
return conn.execute(
"""
SELECT name, content_type, size_bytes, width, height, sha256
FROM attachment_variants
WHERE attachment_id = %s AND pipeline_version = %s AND name <> 'original'
ORDER BY CASE name
WHEN 'thumbnail' THEN 1
WHEN 'crop' THEN 2
WHEN 'optimized' THEN 3
ELSE 4
END
""",
(attachment_id, pipeline_version),
).fetchall()
def save_attachment(self, chat_id, owner_id, filename, content_type, data):
from psycopg.types.json import Json
from blobs import delete_quiet, put_bytes, staging_object_key, variant_object_key
from broker import publish_pending
from faults import take_fault
from jobs import job_message, max_attempts
from telemetry import inject_trace
attachment_id = uuid.uuid4()
job_id = uuid.uuid4()
created = utc_now()
digest = hashlib.sha256(data).hexdigest()
staging = staging_object_key(attachment_id)
final_key = variant_object_key(attachment_id, 1, "original")
carrier = inject_trace({})
payload = job_message(job_id, attachment_id, 1, 1, created, carrier=carrier)
attempts = max_attempts()
put_bytes(staging, data, content_type, created)
try:
with self._connect() as conn:
with conn.transaction():
if self._member(conn, chat_id, owner_id) is None:
raise LookupError("chat")
row = conn.execute(
"""
INSERT INTO attachments (
id, chat_id, owner_id, filename, content_type,
size_bytes, sha256, object_key, staging_key, status,
pipeline_version, error_code, created_at, updated_at
)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, 'queued', 1, NULL, %s, %s)
RETURNING id, chat_id, owner_id, filename, content_type,
size_bytes, sha256, status, error_code, created_at, updated_at
""",
(
attachment_id,
chat_id,
owner_id,
filename,
content_type,
len(data),
digest,
final_key,
staging,
created,
created,
),
).fetchone()
conn.execute(
"""
INSERT INTO attachment_jobs (
id, attachment_id, pipeline_version, status, attempt,
max_attempts, created_at, updated_at
)
VALUES (%s, %s, 1, 'queued', 1, %s, %s, %s)
""",
(job_id, attachment_id, attempts, created, created),
)
conn.execute(
"""
INSERT INTO outbox (id, job_id, attempt, payload, created_at)
VALUES (%s, %s, 1, %s, %s)
""",
(uuid.uuid4(), job_id, Json(payload), created),
)
except (LookupError, ForeignKeyViolation):
delete_quiet(staging)
return None
except psycopg.OperationalError as exc:
delete_quiet(staging)
_db_down(exc)
except Exception:
delete_quiet(staging)
raise
try:
with self._connect() as conn:
skipped = take_fault(conn, "skip_inline_publish", attachment_id)
if not skipped:
with self._connect() as conn:
publish_pending(conn, only_job_id=job_id)
except Exception as exc:
LOGGER.warning("publish deferred %s", type(exc).__name__)
return public_attachment(row, [])
def get_attachment(self, attachment_id, user_id):
try:
with self._connect() as conn:
row = conn.execute(
"""
SELECT a.id, a.chat_id, a.owner_id, a.filename, a.content_type,
a.size_bytes, a.sha256, a.status, a.error_code, a.pipeline_version,
a.created_at, a.updated_at
FROM attachments a
JOIN chat_members m ON m.chat_id = a.chat_id AND m.user_id = %s
WHERE a.id = %s
""",
(user_id, attachment_id),
).fetchone()
variants = []
if row is not None and row["status"] == "ready":
variants = self._variants(conn, row["id"], row["pipeline_version"])
except psycopg.OperationalError as exc:
_db_down(exc)
if row is None:
return None
return public_attachment(row, variants)
def open_attachment(self, attachment_id, user_id, variant):
try:
with self._connect() as conn:
row = conn.execute(
"""
SELECT a.object_key, a.content_type, a.size_bytes, a.status, a.pipeline_version
FROM attachments a
JOIN chat_members m ON m.chat_id = a.chat_id AND m.user_id = %s
WHERE a.id = %s
""",
(user_id, attachment_id),
).fetchone()
if row is None:
return None
if row["status"] != "ready":
raise AttachmentNotReady()
if variant == "original":
return {
"object_key": row["object_key"],
"content_type": row["content_type"],
"size_bytes": int(row["size_bytes"]),
}
found = conn.execute(
"""
SELECT object_key, content_type, size_bytes
FROM attachment_variants
WHERE attachment_id = %s AND pipeline_version = %s AND name = %s
""",
(attachment_id, row["pipeline_version"], variant),
).fetchone()
except psycopg.OperationalError as exc:
_db_down(exc)
if found is None:
return None
return {
"object_key": found["object_key"],
"content_type": found["content_type"],
"size_bytes": int(found["size_bytes"]),
}
def add_message(self, chat_id, sender_id, text, idem_key, attachment_ids):
# Один ключ сериализуется между репликами через advisory lock в той же
# транзакции, где INSERT сообщения. Откат не оставляет ключ занятым.
path = chat_path(chat_id)
digest = message_fingerprint(text, attachment_ids)
lock_key = advisory_key(sender_id, path, idem_key)
message_id = uuid.uuid4()
try:
with self._connect() as conn:
with conn.transaction():
# Иначе lock_timeout сессии (3 с) оборвёт очередь одинаковых ключей.
conn.execute("SET LOCAL lock_timeout = '15s'")
conn.execute("SELECT pg_advisory_xact_lock(%s)", (lock_key,))
if self._member(conn, chat_id, sender_id) is None:
return None
existing = conn.execute(
"""
SELECT request_hash, message_id,
created_at >= now() - make_interval(secs => %s) AS fresh
FROM idempotency_keys
WHERE user_id = %s AND http_method = 'POST'
AND request_path = %s AND idem_key = %s
""",
(self.idem_ttl, sender_id, path, idem_key),
).fetchone()
if existing is not None and existing["fresh"]:
if existing["request_hash"] != digest:
raise IdempotencyConflict()
row = conn.execute(SQL_MESSAGE_BY_ID, (existing["message_id"],)).fetchone()
if row is None:
raise RuntimeError("idempotency target missing")
linked = self._attachment_ids(conn, [row["id"]]).get(str(row["id"]), [])
return public_message(row, linked)
if existing is not None:
conn.execute(
"""
DELETE FROM idempotency_keys
WHERE user_id = %s AND http_method = 'POST'
AND request_path = %s AND idem_key = %s
""",
(sender_id, path, idem_key),
)
if attachment_ids:
found = conn.execute(
"""
SELECT id, chat_id, status
FROM attachments
WHERE id = ANY(%s::uuid[])
""",
(list(attachment_ids),),
).fetchall()
by_id = {str(item["id"]): item for item in found}
for attachment_id in attachment_ids:
item = by_id.get(attachment_id)
if item is None or str(item["chat_id"]) != chat_id:
return None
if item["status"] == "failed" or item["status"] not in ("queued", "processing", "ready"):
raise AttachmentRejected()
row = conn.execute(
"""
INSERT INTO messages (id, chat_id, sender_id, body, created_at)
VALUES (%s, %s, %s, %s, clock_timestamp())
RETURNING id, chat_id, sender_id, body AS text, created_at
""",
(message_id, chat_id, sender_id, text),
).fetchone()
for ordinal, attachment_id in enumerate(attachment_ids):
conn.execute(
"""
INSERT INTO message_attachments (message_id, attachment_id, ordinal)
VALUES (%s, %s, %s)
""",
(row["id"], attachment_id, ordinal),
)
conn.execute(
"""
INSERT INTO idempotency_keys (
user_id, http_method, request_path, idem_key,
request_hash, message_id, created_at
)
VALUES (%s, 'POST', %s, %s, %s, %s, clock_timestamp())
""",
(sender_id, path, idem_key, digest, row["id"]),
)
return public_message(row, attachment_ids)
except CheckViolation as exc:
raise ValueError("message") from exc
except psycopg.OperationalError as exc:
_db_down(exc)
def list_messages(self, chat_id, user_id, limit, cursor):
after = None
if cursor is not None:
created_at, item_id = decode_cursor(cursor, chat_id)
after = (parse_time(created_at), uuid.UUID(item_id))
try:
with self._connect() as conn:
if self._member(conn, chat_id, user_id) is None:
return None
if after is None:
rows = conn.execute(SQL_MESSAGES_FIRST, (chat_id, limit + 1)).fetchall()
else:
rows = conn.execute(
SQL_MESSAGES_AFTER,
(chat_id, after[0], after[1], limit + 1),
).fetchall()
linked = self._attachment_ids(conn, [row["id"] for row in rows[:limit]])
except psycopg.OperationalError as exc:
_db_down(exc)
page = [public_message(row, linked.get(str(row["id"]), [])) for row in rows[:limit]]
if len(rows) > limit and page:
last = page[-1]
return page, encode_cursor(chat_id, last["created_at"], last["id"])
return page, None
+448
View File
@@ -0,0 +1,448 @@
"""OpenTelemetry: traces, metrics, structured logs. Секреты и тела сообщений не экспортируются."""
from __future__ import annotations
import json
import logging
import os
import socket
import time
from contextlib import contextmanager
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.metrics import CallbackOptions, Observation
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, ParentBased, TraceIdRatioBased
from opentelemetry.trace import Link, SpanKind, Status, StatusCode
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
SERVICE_VERSION = "lab6"
PROPAGATOR = TraceContextTextMapPropagator()
_CONFIGURED = False
_TRACER = None
_METER = None
_STATE = {
"queue_depth": {},
"oldest_job_age": {},
"db_pool_used": 0.0,
"db_pool_waiting": 0.0,
"worker_busy": 0.0,
"worker_capacity": 0.0,
"process_cpu": 0.0,
"process_rss": 0.0,
}
http_requests = None
http_duration = None
jobs_processed = None
job_duration = None
e2e_ready = None
def _endpoint():
return os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT", "http://otel-collector:4318").rstrip("/")
def _headers():
raw = os.environ.get("OTEL_EXPORTER_OTLP_HEADERS", "")
if not raw:
return {}
out = {}
for part in raw.split(","):
if "=" not in part:
continue
key, value = part.split("=", 1)
out[key.strip()] = value.strip()
return out
def _sampler():
ratio = os.environ.get("OTEL_TRACES_SAMPLER_ARG", "1.0")
try:
value = float(ratio)
except ValueError:
value = 1.0
if value >= 1.0:
return ParentBased(ALWAYS_ON)
if value <= 0.0:
return ParentBased(TraceIdRatioBased(0.0))
return ParentBased(TraceIdRatioBased(value))
def _resource(service_name):
attrs = {
"service.name": service_name,
"service.version": os.environ.get("SERVICE_VERSION", SERVICE_VERSION),
"service.instance.id": socket.gethostname(),
"deployment.environment.name": os.environ.get("APP_ENV", "lab"),
}
extra = os.environ.get("OTEL_RESOURCE_ATTRIBUTES", "")
for part in extra.split(","):
if "=" not in part:
continue
key, value = part.split("=", 1)
key = key.strip()
value = value.strip()
if key and value and key not in attrs:
attrs[key] = value
return Resource.create(attrs)
def _obs_queue_depth(_options: CallbackOptions):
for name, value in list(_STATE["queue_depth"].items()):
yield Observation(float(value), {"messaging.destination.name": name})
def _obs_oldest(_options: CallbackOptions):
for name, value in list(_STATE["oldest_job_age"].items()):
yield Observation(float(value), {"messaging.destination.name": name})
def _obs_db_used(_options: CallbackOptions):
yield Observation(float(_STATE["db_pool_used"]))
def _obs_db_waiting(_options: CallbackOptions):
yield Observation(float(_STATE["db_pool_waiting"]))
def _obs_worker_busy(_options: CallbackOptions):
yield Observation(float(_STATE["worker_busy"]))
def _obs_worker_capacity(_options: CallbackOptions):
yield Observation(float(_STATE["worker_capacity"]))
def _obs_cpu(_options: CallbackOptions):
yield Observation(float(_STATE["process_cpu"]))
def _obs_rss(_options: CallbackOptions):
yield Observation(float(_STATE["process_rss"]))
def attach_log_handler(logger_provider):
handler = LoggingHandler(level=logging.INFO, logger_provider=logger_provider)
root = logging.getLogger()
root.setLevel(logging.INFO)
if not any(isinstance(item, LoggingHandler) for item in root.handlers):
root.addHandler(handler)
for name in ("messenger", "worker", "uvicorn", "uvicorn.error", "uvicorn.access"):
logging.getLogger(name).setLevel(logging.INFO)
def setup(service_name):
global _CONFIGURED, _TRACER, _METER
global http_requests, http_duration, jobs_processed, job_duration, e2e_ready
if _CONFIGURED:
# uvicorn мог переустановить handlers после импорта модуля
provider = getattr(setup, "_logger_provider", None)
if provider is not None:
attach_log_handler(provider)
return
if os.environ.get("OTEL_SDK_DISABLED", "").lower() in ("1", "true", "yes"):
_CONFIGURED = True
return
resource = _resource(service_name)
base = _endpoint()
hdr = _headers()
provider = TracerProvider(resource=resource, sampler=_sampler())
provider.add_span_processor(
BatchSpanProcessor(
OTLPSpanExporter(endpoint=f"{base}/v1/traces", headers=hdr, timeout=5),
max_queue_size=512,
max_export_batch_size=128,
schedule_delay_millis=2000,
export_timeout_millis=5000,
)
)
trace.set_tracer_provider(provider)
_TRACER = trace.get_tracer("messenger", SERVICE_VERSION)
reader = PeriodicExportingMetricReader(
OTLPMetricExporter(endpoint=f"{base}/v1/metrics", headers=hdr, timeout=5),
export_interval_millis=10000,
export_timeout_millis=5000,
)
views = (
View(
instrument_name="messenger.http.duration",
aggregation=ExplicitBucketHistogramAggregation(
[0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0]
),
),
View(
instrument_name="messenger.jobs.duration",
aggregation=ExplicitBucketHistogramAggregation(
[0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 15.0, 30.0, 60.0]
),
),
View(
instrument_name="messenger.attachment.time_to_ready",
aggregation=ExplicitBucketHistogramAggregation(
[0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0, 120.0]
),
),
)
meter_provider = MeterProvider(resource=resource, metric_readers=[reader], views=views)
metrics.set_meter_provider(meter_provider)
_METER = metrics.get_meter("messenger", SERVICE_VERSION)
logger_provider = LoggerProvider(resource=resource)
logger_provider.add_log_record_processor(
BatchLogRecordProcessor(
OTLPLogExporter(endpoint=f"{base}/v1/logs", headers=hdr, timeout=5),
max_queue_size=512,
max_export_batch_size=128,
schedule_delay_millis=2000,
export_timeout_millis=5000,
)
)
set_logger_provider(logger_provider)
setup._logger_provider = logger_provider
attach_log_handler(logger_provider)
http_requests = _METER.create_counter(
"messenger.http.requests",
unit="1",
description="HTTP requests by method, route template and status class",
)
http_duration = _METER.create_histogram(
"messenger.http.duration",
unit="s",
description="HTTP request duration in seconds",
)
jobs_processed = _METER.create_counter(
"messenger.jobs.processed",
unit="1",
description="Jobs finished by type and outcome",
)
job_duration = _METER.create_histogram(
"messenger.jobs.duration",
unit="s",
description="Job processing duration in seconds",
)
e2e_ready = _METER.create_histogram(
"messenger.attachment.time_to_ready",
unit="s",
description="Seconds from durable acceptance to ready",
)
_METER.create_observable_up_down_counter(
"messenger.queue.depth",
callbacks=[_obs_queue_depth],
unit="1",
description="Approximate broker queue depth",
)
_METER.create_observable_gauge(
"messenger.queue.oldest_job_age",
callbacks=[_obs_oldest],
unit="s",
description="Age of the oldest unfinished job",
)
_METER.create_observable_gauge(
"messenger.db.pool.used",
callbacks=[_obs_db_used],
unit="1",
description="Checked-out DB pool connections",
)
_METER.create_observable_gauge(
"messenger.db.pool.waiting",
callbacks=[_obs_db_waiting],
unit="1",
description="Waiters for a DB pool connection",
)
_METER.create_observable_gauge(
"messenger.worker.busy",
callbacks=[_obs_worker_busy],
unit="1",
description="Busy worker slots",
)
_METER.create_observable_gauge(
"messenger.worker.capacity",
callbacks=[_obs_worker_capacity],
unit="1",
description="Configured worker concurrency",
)
_METER.create_observable_gauge(
"messenger.process.cpu_seconds",
callbacks=[_obs_cpu],
unit="s",
description="Process user+system CPU seconds",
)
_METER.create_observable_gauge(
"messenger.process.rss_bytes",
callbacks=[_obs_rss],
unit="By",
description="Process RSS bytes",
)
_CONFIGURED = True
def tracer():
return _TRACER or trace.get_tracer("messenger", SERVICE_VERSION)
def status_class(code):
return f"{int(code) // 100}xx"
def route_template(path):
if path in ("/health/live", "/health/ready"):
return path
parts = [p for p in path.strip("/").split("/") if p]
if len(parts) >= 3 and parts[0] == "api" and parts[1] == "v1":
if parts[2] == "users" and len(parts) == 3:
return "/api/v1/users"
if parts[2] == "users" and len(parts) == 4 and parts[3] == "me":
return "/api/v1/users/me"
if parts[2] == "auth" and len(parts) >= 4 and parts[3] == "sessions":
if len(parts) == 4:
return "/api/v1/auth/sessions"
return "/api/v1/auth/sessions/current"
if parts[2] == "chats" and len(parts) == 3:
return "/api/v1/chats"
if parts[2] == "chats" and len(parts) == 4:
return "/api/v1/chats/{chat_id}"
if parts[2] == "chats" and len(parts) == 5 and parts[4] == "messages":
return "/api/v1/chats/{chat_id}/messages"
if parts[2] == "chats" and len(parts) == 5 and parts[4] == "attachments":
return "/api/v1/chats/{chat_id}/attachments"
if parts[2] == "attachments" and len(parts) == 4:
return "/api/v1/attachments/{attachment_id}"
if parts[2] == "attachments" and len(parts) == 5 and parts[4] == "content":
return "/api/v1/attachments/{attachment_id}/content"
return "other"
def record_http(method, path, status, duration_s):
if http_requests is None:
return
if path in ("/health/live", "/health/ready"):
return
route = route_template(path)
attrs = {
"http.request.method": method,
"http.route": route,
"http.response.status_class": status_class(status),
}
http_requests.add(1, attrs)
http_duration.record(duration_s, attrs)
def inject_trace(carrier):
PROPAGATOR.inject(carrier)
return carrier
def extract_context(carrier):
return PROPAGATOR.extract(carrier)
def current_trace_fields():
span = trace.get_current_span()
ctx = span.get_span_context()
if not ctx.is_valid:
return {}, None, None
carrier = {}
inject_trace(carrier)
return carrier, format(ctx.trace_id, "032x"), format(ctx.span_id, "016x")
def structured_log(logger, event, level=logging.INFO, **fields):
_carrier, trace_id, span_id = current_trace_fields()
payload = {
"event": event,
"service.name": os.environ.get("OTEL_SERVICE_NAME", "messenger"),
}
if trace_id:
payload["trace_id"] = trace_id
if span_id:
payload["span_id"] = span_id
for key, value in fields.items():
if value is None:
continue
if key in ("password", "token", "authorization", "body", "text", "bytes"):
continue
payload[key] = value
logger.log(level, json.dumps(payload, ensure_ascii=False, sort_keys=True))
@contextmanager
def start_span(name, kind=SpanKind.INTERNAL, attributes=None, links=None, context=None):
attrs = dict(attributes or {})
span = tracer().start_span(name, context=context, kind=kind, attributes=attrs, links=links or [])
token = trace.use_span(span, end_on_exit=True)
token.__enter__()
try:
yield span
except Exception as exc:
span.record_exception(exc)
span.set_status(Status(StatusCode.ERROR, type(exc).__name__))
raise
finally:
token.__exit__(None, None, None)
def link_from_carrier(carrier):
ctx = extract_context(carrier)
span_ctx = trace.get_current_span(ctx).get_span_context()
if span_ctx.is_valid:
return [Link(span_ctx)]
return []
def observe_process():
try:
import resource
usage = resource.getrusage(resource.RUSAGE_SELF)
_STATE["process_rss"] = float(usage.ru_maxrss) * 1024.0
_STATE["process_cpu"] = float(usage.ru_utime + usage.ru_stime)
except Exception:
pass
def set_pool_stats(used, waiting):
_STATE["db_pool_used"] = float(used)
_STATE["db_pool_waiting"] = float(waiting)
def set_worker_stats(busy, capacity):
_STATE["worker_busy"] = float(busy)
_STATE["worker_capacity"] = float(capacity)
def set_queue_stats(name, depth, oldest_age_s):
_STATE["queue_depth"][name] = int(depth)
_STATE["oldest_job_age"][name] = float(oldest_age_s)
def record_job(outcome, duration_s, job_type="attachment.process.v1"):
if jobs_processed is None:
return
attrs = {"job.type": job_type, "job.outcome": outcome}
jobs_processed.add(1, attrs)
job_duration.record(duration_s, attrs)
def record_time_to_ready(seconds):
if e2e_ready is None:
return
e2e_ready.record(float(seconds), {"job.type": "attachment.process.v1"})
def now_monotonic():
return time.perf_counter()
+241
View File
@@ -0,0 +1,241 @@
"""Отдельный процесс. API не уменьшает картинку, даже если worker остановлен."""
import logging
import os
import socket
import threading
import time
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timezone
import pika
import psycopg
from psycopg.rows import dict_row
from psycopg_pool import ConnectionPool
from blobs import bucket_ready, read_secret
from broker import PROCESS_QUEUE, RETRY_QUEUE, _parameters, broker_channel, ensure_topology, publish_pending, queue_depth
from jobs import cleanup_staging, lease_seconds, process_delivery, release_expired
from telemetry import observe_process, set_queue_stats, set_worker_stats, setup as setup_telemetry, structured_log
LOGGER = logging.getLogger("worker")
SCHEMA_VERSION = "004_jobs"
BUSY = 0
BUSY_LOCK = threading.Lock()
def database_url():
return read_secret(os.environ["DATABASE_URL_FILE"])
def concurrency():
value = int(os.environ.get("WORKER_CONCURRENCY", "2"))
if not 1 <= value <= 8:
raise RuntimeError("WORKER_CONCURRENCY")
return value
def wait_schema(conninfo):
last = "error"
for _ in range(90):
try:
with psycopg.connect(conninfo, connect_timeout=3, row_factory=dict_row) as conn:
row = conn.execute(
"SELECT 1 FROM schema_migrations WHERE version = %s",
(SCHEMA_VERSION,),
).fetchone()
if row is not None:
return
last = "migration missing"
except psycopg.Error as exc:
last = type(exc).__name__
time.sleep(1)
LOGGER.error("schema not ready: %s", last)
raise SystemExit(1)
def wait_bucket():
for _ in range(60):
if bucket_ready():
return
time.sleep(1)
LOGGER.error("object storage not ready")
raise SystemExit(1)
def wait_broker():
last = "error"
for _ in range(60):
try:
with broker_channel():
return
except Exception as exc:
last = type(exc).__name__
time.sleep(1)
LOGGER.error("broker not ready: %s", last)
raise SystemExit(1)
def make_pool(conninfo, slots):
return ConnectionPool(
conninfo,
min_size=1,
max_size=slots * 2 + 2,
timeout=3,
kwargs={
"connect_timeout": 3,
"row_factory": dict_row,
"application_name": "mtusi-lab6-worker",
"options": "-c statement_timeout=5000 -c lock_timeout=3000 -c idle_in_transaction_session_timeout=30000",
},
open=True,
)
def oldest_job_age_seconds(pool):
try:
with pool.connection() as conn:
row = conn.execute(
"""
SELECT EXTRACT(EPOCH FROM (now() - MIN(created_at))) AS age
FROM attachment_jobs
WHERE status IN ('queued', 'processing')
"""
).fetchone()
if row is None or row["age"] is None:
return 0.0
return float(row["age"])
except Exception:
return 0.0
def refresh_runtime_stats(pool, slots):
global BUSY
try:
depth = queue_depth(PROCESS_QUEUE)
except Exception:
depth = 0
try:
retry_depth = queue_depth(RETRY_QUEUE)
except Exception:
retry_depth = 0
age = oldest_job_age_seconds(pool)
set_queue_stats(PROCESS_QUEUE, depth, age)
set_queue_stats(RETRY_QUEUE, retry_depth, 0.0)
with BUSY_LOCK:
busy = BUSY
set_worker_stats(busy, slots)
observe_process()
try:
stats = pool.get_stats()
from telemetry import set_pool_stats
used = int(stats.get("pool_size", 0)) - int(stats.get("pool_available", 0))
waiting = int(stats.get("requests_waiting", 0))
set_pool_stats(max(0, used), waiting)
except Exception:
pass
def consume(pool, owner, slots):
executor = ThreadPoolExecutor(max_workers=slots, thread_name_prefix="job")
while True:
connection = None
try:
connection = pika.BlockingConnection(_parameters())
channel = connection.channel()
ensure_topology(channel)
channel.basic_qos(prefetch_count=slots)
def on_message(ch, method, _props, body):
executor.submit(run_one, pool, owner, ch, method.delivery_tag, body)
channel.basic_consume(PROCESS_QUEUE, on_message, auto_ack=False)
channel.start_consuming()
except Exception as exc:
LOGGER.warning("consumer %s", type(exc).__name__)
time.sleep(1)
finally:
if connection is not None:
try:
connection.close()
except Exception:
pass
def run_one(pool, owner, channel, tag, body):
global BUSY
with BUSY_LOCK:
BUSY += 1
try:
process_delivery(pool, body, owner)
action = "ack"
except Exception as exc:
LOGGER.warning("delivery %s", type(exc).__name__)
action = "nack"
finally:
with BUSY_LOCK:
BUSY = max(0, BUSY - 1)
def finish():
try:
if action == "ack":
channel.basic_ack(tag)
else:
channel.basic_nack(tag, requeue=True)
except Exception:
pass
try:
channel.connection.add_callback_threadsafe(finish)
except Exception:
pass
def main():
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
setup_telemetry(os.environ.get("OTEL_SERVICE_NAME", "messenger-worker"))
conninfo = database_url()
wait_schema(conninfo)
wait_bucket()
wait_broker()
slots = concurrency()
pool = make_pool(conninfo, slots)
owner = socket.gethostname()
stop = threading.Event()
set_worker_stats(0, slots)
def drain():
while not stop.wait(1):
try:
with pool.connection() as conn:
publish_pending(conn)
except Exception as exc:
LOGGER.warning("drain %s", type(exc).__name__)
def sweep():
ticks = 0
while not stop.wait(5):
ticks += 1
try:
with pool.connection() as conn:
release_expired(conn)
if ticks % 12 == 0:
cleanup_staging(conn)
refresh_runtime_stats(pool, slots)
except Exception as exc:
LOGGER.warning("sweep %s", type(exc).__name__)
threading.Thread(target=drain, name="drain", daemon=True).start()
threading.Thread(target=sweep, name="sweep", daemon=True).start()
try:
with pool.connection() as conn:
publish_pending(conn)
except Exception as exc:
LOGGER.warning("startup drain %s", type(exc).__name__)
structured_log(LOGGER, "worker_ready", owner=owner, concurrency=slots, lease=lease_seconds())
LOGGER.info("worker ready owner=%s concurrency=%s lease=%s", owner, slots, lease_seconds())
consume(pool, owner, slots)
if __name__ == "__main__":
main()