ЛР 5 — БПИ2303 — Лазарев — на 4
Асинхронная обработка вложений: RabbitMQ 4.1 (quorum-очереди, publisher confirms, manual ack, DLQ), transactional outbox, отдельный worker. - upload: оригинал в staging S3, затем одной транзакцией queued + jobs + outbox -> 202; API к брокеру не подключается - relay: публикация outbox с confirm, reaper истёкших аренд, redrive - worker: claim по строке jobs, аренда с heartbeat и fencing по lease_token, transform в подпроцессе с RLIMIT_AS/RLIMIT_CPU/таймаутом, thumbnail 256, crop 128, WebP 1280 по детерминированным ключам - retry с backoff и jitter, постоянные/временные ошибки, реестр failed, ops replay (ready не повторяется), DLQ для невалидных сообщений - janitor: очистка staging и сирот; миграция 004 с backfill вложений lab4 - тесты отказов: окна COMMIT/publish, крахи worker до/после S3 и ack, заморозка worker, всплеск загрузок, права брокера; evidence/ и REPORT.md
This commit is contained in:
@@ -0,0 +1,98 @@
|
||||
"""Общее для фоновых процессов lab5 (relay, worker, ops): конфигурация, БД, брокер.
|
||||
|
||||
API (server.py) брокер не использует вовсе: он только пишет outbox в PostgreSQL.
|
||||
Поэтому недоступность RabbitMQ не влияет на приём файлов — задания копятся в outbox.
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
import socket
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
|
||||
import pika
|
||||
from psycopg.conninfo import make_conninfo
|
||||
|
||||
logging.basicConfig(stream=sys.stdout, level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
|
||||
logging.getLogger("pika").setLevel(logging.WARNING)
|
||||
|
||||
# Топология брокера (объявляется декларативно в secrets/rabbitmq_definitions.json,
|
||||
# приложения её не создают — у их пользователей нет права configure).
|
||||
EXCHANGE = "attachments"
|
||||
ROUTING_KEY = "attachment.process.v1"
|
||||
QUEUE = "attachments.process.v1"
|
||||
DLQ = "attachments.dlq"
|
||||
|
||||
HOSTNAME = socket.gethostname()
|
||||
# Идентификатор процесса для lease_owner: hostname контейнера + случайный boot id.
|
||||
BOOT_ID = uuid.uuid4().hex[:8]
|
||||
OWNER = "%s:%s" % (HOSTNAME, BOOT_ID)
|
||||
|
||||
|
||||
def env_int(name, default):
|
||||
return int(os.environ.get(name, str(default)))
|
||||
|
||||
|
||||
def env_float(name, default):
|
||||
return float(os.environ.get(name, str(default)))
|
||||
|
||||
|
||||
def secret(name):
|
||||
"""Значение из NAME_FILE (Docker secret) либо из NAME."""
|
||||
path = os.environ.get(name + "_FILE")
|
||||
if path:
|
||||
with open(path, encoding="utf-8") as f:
|
||||
return f.read().strip()
|
||||
return os.environ.get(name, "")
|
||||
|
||||
|
||||
def database_conninfo():
|
||||
options = "-c statement_timeout=%d" % env_int("DB_STATEMENT_TIMEOUT_MS", 5000)
|
||||
url = secret("DATABASE_URL")
|
||||
if url:
|
||||
return make_conninfo(url, connect_timeout=3, options=options)
|
||||
return make_conninfo(
|
||||
host=os.environ.get("POSTGRES_HOST", "localhost"),
|
||||
port=os.environ.get("POSTGRES_PORT", "5432"),
|
||||
dbname=os.environ.get("POSTGRES_DB", "messenger"),
|
||||
user=os.environ.get("POSTGRES_USER", "messenger"),
|
||||
password=secret("POSTGRES_PASSWORD"),
|
||||
connect_timeout=3,
|
||||
options=options,
|
||||
)
|
||||
|
||||
|
||||
def broker_parameters():
|
||||
"""amqp URL из BROKER_URL_FILE: у relay, worker и ops — разные пользователи RabbitMQ."""
|
||||
params = pika.URLParameters(secret("BROKER_URL"))
|
||||
# heartbeat: брокер закроет соединение мёртвого/замороженного клиента и вернёт его unacked
|
||||
# сообщения в очередь (в т.ч. выданные заранее по prefetch). 10 с: эксперимент
|
||||
# lease_takeover показал, что при 20 с такое сообщение висело ~35 с. Worker обрабатывает
|
||||
# задание в отдельном потоке и продолжает обслуживать heartbeat (process_data_events),
|
||||
# поэтому долгая обработка соединение не рвёт.
|
||||
params.heartbeat = env_int("BROKER_HEARTBEAT_SECONDS", 10)
|
||||
params.blocked_connection_timeout = 30
|
||||
params.socket_timeout = 5
|
||||
params.connection_attempts = 1
|
||||
params.client_properties = {"connection_name": "%s-%s" % (os.environ.get("SERVICE_NAME", "app"), HOSTNAME)}
|
||||
return params
|
||||
|
||||
|
||||
def connect_broker(log, stop=None):
|
||||
"""Подключение с повторами и паузой до 5 с; stop — threading.Event для выхода."""
|
||||
delay = 0.5
|
||||
while True:
|
||||
try:
|
||||
return pika.BlockingConnection(broker_parameters())
|
||||
except Exception as exc:
|
||||
log.warning("broker unavailable (%s), retry in %.1fs", type(exc).__name__, delay)
|
||||
if stop is not None and stop.wait(delay):
|
||||
return None
|
||||
if stop is None:
|
||||
time.sleep(delay)
|
||||
delay = min(5.0, delay * 2)
|
||||
|
||||
|
||||
def touch(path):
|
||||
with open(path, "w") as f:
|
||||
f.write(str(time.time()))
|
||||
+216
@@ -0,0 +1,216 @@
|
||||
"""Проверка загружаемых изображений по СОДЕРЖИМОМУ, с ограниченной памятью.
|
||||
|
||||
Заголовок Content-Type клиента — только заявление: настоящий формат определяется
|
||||
по сигнатуре и структуре файла. Лимит пикселей проверяется по заголовку (PNG IHDR,
|
||||
JPEG SOF) ДО распаковки, поэтому «бомба» 100 000×100 000 не декодируется вовсе.
|
||||
|
||||
PNG проверяется собственным потоковым валидатором (стандартная библиотека):
|
||||
структура и CRC каждого chunk, допустимые IHDR, IDAT распаковывается zlib кусками
|
||||
по 1 MiB без сохранения результата; объём распакованных данных должен ТОЧНО совпасть
|
||||
с размером, который следует из IHDR (больше — бомба/мусор, меньше — обрезанный файл).
|
||||
|
||||
JPEG: разбор маркеров до SOF (размеры), затем пробное декодирование Pillow в режиме
|
||||
draft (масштаб 1/8): проверяются энтропийные данные, а памяти нужно ~1/64 от полного
|
||||
кадра (40 Мпикс -> ~2 MiB вместо ~120 MiB).
|
||||
"""
|
||||
import struct
|
||||
import zlib
|
||||
|
||||
PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
|
||||
JPEG_SOI = b"\xff\xd8\xff"
|
||||
READ_CHUNK = 64 * 1024
|
||||
INFLATE_STEP = 1024 * 1024
|
||||
|
||||
# Допустимые глубины цвета по типу цвета PNG и число каналов.
|
||||
_PNG_DEPTHS = {0: {1, 2, 4, 8, 16}, 2: {8, 16}, 3: {1, 2, 4, 8}, 4: {8, 16}, 6: {8, 16}}
|
||||
_PNG_CHANNELS = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}
|
||||
# Adam7: (x0, y0, dx, dy)
|
||||
_ADAM7 = ((0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4, 4), (0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2))
|
||||
_JPEG_SOF = {0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF}
|
||||
|
||||
|
||||
class InvalidImage(Exception):
|
||||
"""Файл не является корректным PNG/JPEG заявленного типа -> 415."""
|
||||
|
||||
|
||||
class TooManyPixels(Exception):
|
||||
"""Декодированный размер превышает лимит -> 413."""
|
||||
|
||||
|
||||
def sniff(head):
|
||||
"""Тип по сигнатуре первых байтов: 'image/png', 'image/jpeg' или None."""
|
||||
if head.startswith(PNG_SIGNATURE):
|
||||
return "image/png"
|
||||
if head.startswith(JPEG_SOI):
|
||||
return "image/jpeg"
|
||||
return None
|
||||
|
||||
|
||||
def png_header_pixels(head):
|
||||
"""Ранняя проверка по первым 33 байтам (сигнатура + IHDR): (w, h) или None."""
|
||||
if len(head) < 33 or not head.startswith(PNG_SIGNATURE) or head[12:16] != b"IHDR":
|
||||
return None
|
||||
return struct.unpack(">II", head[16:24])
|
||||
|
||||
|
||||
def _read_exact(f, n):
|
||||
data = f.read(n)
|
||||
if len(data) != n:
|
||||
raise InvalidImage("truncated")
|
||||
return data
|
||||
|
||||
|
||||
def _png_expected_bytes(w, h, bits_per_pixel, interlace):
|
||||
def raw(pw, ph):
|
||||
return ph * (1 + (pw * bits_per_pixel + 7) // 8) if pw and ph else 0
|
||||
if interlace == 0:
|
||||
return raw(w, h)
|
||||
total = 0
|
||||
for x0, y0, dx, dy in _ADAM7:
|
||||
pw = (w - x0 + dx - 1) // dx if w > x0 else 0
|
||||
ph = (h - y0 + dy - 1) // dy if h > y0 else 0
|
||||
total += raw(pw, ph)
|
||||
return total
|
||||
|
||||
|
||||
def validate_png(f, size, max_pixels):
|
||||
if _read_exact(f, 8) != PNG_SIGNATURE:
|
||||
raise InvalidImage("signature")
|
||||
pos = 8
|
||||
width = height = None
|
||||
expected = produced = 0
|
||||
inflater = None
|
||||
seen_plte = idat_done = False
|
||||
color_type = None
|
||||
last_type = None
|
||||
while True:
|
||||
if pos + 12 > size:
|
||||
raise InvalidImage("truncated")
|
||||
length, ctype = struct.unpack(">I4s", _read_exact(f, 8))
|
||||
pos += 8
|
||||
if length > 0x7FFFFFFF or pos + length + 4 > size:
|
||||
raise InvalidImage("chunk length")
|
||||
if not ctype.isalpha():
|
||||
raise InvalidImage("chunk type")
|
||||
if width is None and ctype != b"IHDR":
|
||||
raise InvalidImage("IHDR must be first")
|
||||
crc = zlib.crc32(ctype)
|
||||
if ctype == b"IDAT":
|
||||
if idat_done or (color_type == 3 and not seen_plte):
|
||||
raise InvalidImage("IDAT order")
|
||||
remaining = length
|
||||
while remaining:
|
||||
piece = _read_exact(f, min(READ_CHUNK, remaining))
|
||||
remaining -= len(piece)
|
||||
crc = zlib.crc32(piece, crc)
|
||||
buf = piece
|
||||
while buf:
|
||||
if inflater.eof:
|
||||
raise InvalidImage("data after zlib stream")
|
||||
try:
|
||||
out = inflater.decompress(buf, INFLATE_STEP)
|
||||
except zlib.error:
|
||||
raise InvalidImage("zlib")
|
||||
produced += len(out)
|
||||
if produced > expected:
|
||||
raise InvalidImage("too much pixel data") # бомба/мусор
|
||||
buf = inflater.unconsumed_tail
|
||||
else:
|
||||
if last_type == b"IDAT":
|
||||
idat_done = True
|
||||
data = _read_exact(f, length)
|
||||
crc = zlib.crc32(data, crc)
|
||||
if ctype == b"IHDR":
|
||||
if width is not None or length != 13:
|
||||
raise InvalidImage("IHDR")
|
||||
width, height, depth, color_type, comp, filt, interlace = struct.unpack(">IIBBBBB", data)
|
||||
if not (1 <= width <= 0x7FFFFFFF and 1 <= height <= 0x7FFFFFFF):
|
||||
raise InvalidImage("dimensions")
|
||||
if width * height > max_pixels:
|
||||
raise TooManyPixels()
|
||||
if depth not in _PNG_DEPTHS.get(color_type, ()) or comp != 0 or filt != 0 or interlace not in (0, 1):
|
||||
raise InvalidImage("IHDR values")
|
||||
expected = _png_expected_bytes(width, height, _PNG_CHANNELS[color_type] * depth, interlace)
|
||||
inflater = zlib.decompressobj()
|
||||
elif ctype == b"PLTE":
|
||||
seen_plte = True
|
||||
elif ctype == b"IEND":
|
||||
pass
|
||||
elif ctype[0:1].isupper():
|
||||
raise InvalidImage("unknown critical chunk") # декодер обязан его понимать
|
||||
if struct.unpack(">I", _read_exact(f, 4))[0] != crc & 0xFFFFFFFF:
|
||||
raise InvalidImage("crc")
|
||||
pos += length + 4
|
||||
last_type = ctype
|
||||
if ctype == b"IEND":
|
||||
break
|
||||
if inflater is None or not inflater.eof or produced != expected:
|
||||
raise InvalidImage("incomplete pixel data")
|
||||
if pos != size:
|
||||
raise InvalidImage("trailing data") # полиглоты PNG+что-то ещё не принимаем
|
||||
return width, height
|
||||
|
||||
|
||||
def jpeg_dimensions(f, size):
|
||||
"""Размеры из первого SOF без декодирования. Ограничено размером файла."""
|
||||
if _read_exact(f, 2) != b"\xff\xd8":
|
||||
raise InvalidImage("signature")
|
||||
pos = 2
|
||||
while pos < size:
|
||||
b = _read_exact(f, 1)
|
||||
pos += 1
|
||||
if b != b"\xff":
|
||||
raise InvalidImage("marker")
|
||||
marker = 0xFF
|
||||
while marker == 0xFF:
|
||||
marker = _read_exact(f, 1)[0]
|
||||
pos += 1
|
||||
if marker == 0x01 or 0xD0 <= marker <= 0xD7:
|
||||
continue
|
||||
if marker in (0xD8, 0xD9, 0xDA):
|
||||
raise InvalidImage("no SOF before scan")
|
||||
seg_len = struct.unpack(">H", _read_exact(f, 2))[0]
|
||||
if seg_len < 2 or pos + seg_len > size:
|
||||
raise InvalidImage("segment length")
|
||||
if marker in _JPEG_SOF:
|
||||
if seg_len < 8:
|
||||
raise InvalidImage("SOF")
|
||||
_precision, height, width = struct.unpack(">BHH", _read_exact(f, 5))
|
||||
if width == 0 or height == 0:
|
||||
raise InvalidImage("dimensions") # DNL-высота не поддерживается
|
||||
return width, height
|
||||
f.seek(seg_len - 2, 1)
|
||||
pos += seg_len
|
||||
raise InvalidImage("no SOF")
|
||||
|
||||
|
||||
def validate_jpeg(f, size, max_pixels):
|
||||
width, height = jpeg_dimensions(f, size)
|
||||
if width * height > max_pixels:
|
||||
raise TooManyPixels()
|
||||
from PIL import Image # импорт по требованию: Pillow нужен только для JPEG
|
||||
Image.MAX_IMAGE_PIXELS = max_pixels
|
||||
f.seek(0)
|
||||
try:
|
||||
with Image.open(f, formats=("JPEG",)) as im:
|
||||
if im.size != (width, height):
|
||||
raise InvalidImage("size mismatch")
|
||||
im.draft("RGB", (max(1, width // 8), max(1, height // 8)))
|
||||
im.load() # обрезанные/битые энтропийные данные -> OSError
|
||||
except InvalidImage:
|
||||
raise
|
||||
except Exception:
|
||||
# Pillow бросает разные исключения (OSError, SyntaxError, ValueError,
|
||||
# DecompressionBombError...) — для клиента это одинаково «не JPEG».
|
||||
raise InvalidImage("decode")
|
||||
return width, height
|
||||
|
||||
|
||||
def validate(f, size, content_type, max_pixels):
|
||||
"""(width, height) или InvalidImage/TooManyPixels. f — seekable файл, позиция 0."""
|
||||
f.seek(0)
|
||||
if content_type == "image/png":
|
||||
return validate_png(f, size, max_pixels)
|
||||
if content_type == "image/jpeg":
|
||||
return validate_jpeg(f, size, max_pixels)
|
||||
raise InvalidImage("type")
|
||||
+209
@@ -0,0 +1,209 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Сверка PostgreSQL <-> S3 и очистка (compose-сервис `janitor`). Lab5.
|
||||
|
||||
Prefix-ы bucket:
|
||||
staging/<uuid> принятые оригиналы до публикации результата (attachments.staging_key);
|
||||
attachments/<id>/v<ver>/<name> конечные объекты: original и варианты;
|
||||
originals/<uuid> оригиналы lab4 (после миграции 004 — staging-объекты backfill-заданий);
|
||||
health/, bootstrap/ служебные, не трогаются.
|
||||
|
||||
За один проход (под pg_try_advisory_lock):
|
||||
1. abandoned: pending-строки старше grace (API упал до постановки в очередь, 202 не было)
|
||||
-> удалить staging-объект, затем строку;
|
||||
2. staging ready: у ready-вложения остался staging (worker не смог удалить после COMMIT)
|
||||
-> удалить объект, staging_key = NULL;
|
||||
3. staging failed: failed дольше STAGING_RETENTION_SECONDS -> удалить staging (replay после
|
||||
этого невозможен: ops replay ответит refused_staging_expired);
|
||||
4. orphan: объекты staging/, originals/, attachments/ старше grace, на которые не ссылается
|
||||
ни одна строка (staging_key, object_key ready-вложения, attachment_variants), и вложение
|
||||
не queued/processing -> удалить;
|
||||
5. missing: ready без объекта оригинала или варианта -> ТОЛЬКО отчёт.
|
||||
Текущую работу (queued/processing) janitor не удаляет никогда: её staging нужен worker.
|
||||
Grace (ATTACHMENT_GRACE_SECONDS, 3600 с) многократно больше UPLOAD_TIMEOUT_SECONDS и
|
||||
JOB_TIMEOUT_SECONDS, поэтому идущая загрузка/обработка не считается брошенной.
|
||||
|
||||
python src/janitor.py --once --dry-run | --once | --interval 300
|
||||
"""
|
||||
import argparse
|
||||
import datetime as dt
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
|
||||
import jobs
|
||||
from server import OBJ, STORE
|
||||
|
||||
log = logging.getLogger("messenger.janitor")
|
||||
JANITOR_LOCK_ID = 727002
|
||||
PREFIXES = ("staging/", "originals/", "attachments/")
|
||||
HEARTBEAT = "/tmp/janitor.heartbeat"
|
||||
STAGING_RETENTION = int(os.environ.get("STAGING_RETENTION_SECONDS", "86400"))
|
||||
_FINAL_RE = re.compile(r"^attachments/([0-9a-f-]{36})/")
|
||||
|
||||
|
||||
def heartbeat():
|
||||
with open(HEARTBEAT, "w") as f:
|
||||
f.write(str(time.time()))
|
||||
|
||||
|
||||
def _delete(report, key, dry_run):
|
||||
if dry_run:
|
||||
return True
|
||||
try:
|
||||
OBJ.delete(key)
|
||||
report["deleted_objects"] += 1
|
||||
return True
|
||||
except Exception as exc:
|
||||
report["errors"] += 1
|
||||
log.warning("object not deleted (%s)", type(exc).__name__)
|
||||
return False
|
||||
|
||||
|
||||
def run_once(grace_seconds, dry_run, staging_retention=STAGING_RETENTION):
|
||||
started = time.monotonic()
|
||||
report = {"dry_run": dry_run, "grace_seconds": grace_seconds, "staging_retention_seconds": staging_retention,
|
||||
"abandoned_pending": 0, "staging_ready_cleaned": 0, "staging_failed_expired": 0,
|
||||
"orphan_objects": 0, "missing_objects": 0, "deleted_objects": 0, "deleted_rows": 0, "errors": 0}
|
||||
with STORE.pool.connection() as conn:
|
||||
conn.autocommit = True
|
||||
if not conn.execute("SELECT pg_try_advisory_lock(%s) AS ok", (JANITOR_LOCK_ID,)).fetchone()["ok"]:
|
||||
report["skipped"] = "another janitor is running"
|
||||
return report
|
||||
try:
|
||||
now_db = conn.execute("SELECT now() AS t").fetchone()["t"]
|
||||
cutoff = now_db - dt.timedelta(seconds=grace_seconds)
|
||||
report["rows_by_status"] = {r["status"]: r["n"] for r in conn.execute(
|
||||
"SELECT status, count(*) AS n FROM attachments GROUP BY status")}
|
||||
report["jobs_by_status"] = {r["status"]: r["n"] for r in conn.execute(
|
||||
"SELECT status, count(*) AS n FROM jobs GROUP BY status")}
|
||||
report["outbox_unpublished"] = conn.execute(
|
||||
"SELECT count(*) AS n FROM outbox WHERE published_at IS NULL").fetchone()["n"]
|
||||
|
||||
# 1. брошенные pending
|
||||
abandoned = conn.execute(
|
||||
"""SELECT id, staging_key FROM attachments
|
||||
WHERE status = 'pending' AND created_at < %s ORDER BY created_at""", (cutoff,)).fetchall()
|
||||
report["abandoned_pending"] = len(abandoned)
|
||||
report["abandoned_ids"] = [str(r["id"]) for r in abandoned[:20]]
|
||||
for row in abandoned:
|
||||
if dry_run:
|
||||
continue
|
||||
if row["staging_key"] and not _delete(report, row["staging_key"], dry_run):
|
||||
continue
|
||||
report["deleted_rows"] += conn.execute(
|
||||
"DELETE FROM attachments WHERE id = %s AND status = 'pending'", (row["id"],)).rowcount
|
||||
|
||||
# 2/3. staging, который больше не нужен
|
||||
stale = conn.execute(
|
||||
"""SELECT a.id, a.staging_key, a.status, j.id AS job_id FROM attachments a
|
||||
LEFT JOIN jobs j ON j.attachment_id = a.id AND j.pipeline_version = a.pipeline_version
|
||||
WHERE a.staging_key IS NOT NULL AND (a.status = 'ready'
|
||||
OR (a.status = 'failed' AND a.updated_at < now() - make_interval(secs => %s)))""",
|
||||
(staging_retention,)).fetchall()
|
||||
for row in stale:
|
||||
key = "staging_ready_cleaned" if row["status"] == "ready" else "staging_failed_expired"
|
||||
report[key] += 1
|
||||
if dry_run or not _delete(report, row["staging_key"], dry_run):
|
||||
continue
|
||||
with conn.transaction():
|
||||
n = conn.execute(
|
||||
"""UPDATE attachments SET staging_key = NULL
|
||||
WHERE id = %s AND staging_key = %s AND status = %s""",
|
||||
(row["id"], row["staging_key"], row["status"])).rowcount
|
||||
if n and row["job_id"]:
|
||||
jobs.add_event(conn, row["job_id"], "staging_deleted", None, "janitor", {"status": row["status"]})
|
||||
|
||||
# 4/5. обход bucket. Момент начала — по часам БД: ready раньше этого момента обязан
|
||||
# иметь все объекты в листинге (объекты пишутся ДО COMMIT ready).
|
||||
list_started = conn.execute("SELECT now() AS t").fetchone()["t"]
|
||||
listed = {}
|
||||
for prefix in PREFIXES:
|
||||
for obj in OBJ.client.list_objects(OBJ.bucket, prefix=prefix, recursive=True):
|
||||
listed[obj.object_name] = obj.last_modified
|
||||
report["objects_total"] = len(listed)
|
||||
report["objects_by_prefix"] = {p: sum(1 for k in listed if k.startswith(p)) for p in PREFIXES}
|
||||
known = set()
|
||||
busy = set() # вложения с текущей работой: их объекты не трогаем
|
||||
keys = list(listed)
|
||||
for i in range(0, len(keys), 1000):
|
||||
batch = keys[i:i + 1000]
|
||||
for r in conn.execute(
|
||||
"""SELECT staging_key AS k FROM attachments WHERE staging_key = ANY(%(b)s)
|
||||
UNION SELECT object_key FROM attachments WHERE status = 'ready' AND object_key = ANY(%(b)s)
|
||||
UNION SELECT object_key FROM attachment_variants WHERE object_key = ANY(%(b)s)""",
|
||||
{"b": batch}):
|
||||
known.add(r["k"])
|
||||
ids = {m.group(1) for k in keys for m in [_FINAL_RE.match(k)] if m}
|
||||
if ids:
|
||||
for r in conn.execute(
|
||||
"SELECT id FROM attachments WHERE id = ANY(%s::uuid[]) AND status IN ('pending','queued','processing')",
|
||||
(list(ids),)):
|
||||
busy.add(str(r["id"]))
|
||||
orphans = []
|
||||
for k, mtime in listed.items():
|
||||
if k in known or mtime is None or mtime >= cutoff:
|
||||
continue
|
||||
m = _FINAL_RE.match(k)
|
||||
if m and m.group(1) in busy:
|
||||
continue
|
||||
orphans.append(k)
|
||||
report["orphan_objects"] = len(orphans)
|
||||
report["orphan_keys_sample"] = sorted(orphans)[:5]
|
||||
for key in orphans:
|
||||
_delete(report, key, dry_run)
|
||||
|
||||
missing = []
|
||||
for r in conn.execute(
|
||||
"""SELECT a.id, a.object_key AS k FROM attachments a WHERE a.status = 'ready' AND a.updated_at < %s
|
||||
UNION ALL
|
||||
SELECT v.attachment_id, v.object_key FROM attachment_variants v
|
||||
JOIN attachments a ON a.id = v.attachment_id
|
||||
WHERE a.status = 'ready' AND a.updated_at < %s""", (list_started, list_started)):
|
||||
if r["k"] not in listed:
|
||||
missing.append(str(r["id"]))
|
||||
report["missing_objects"] = len(missing)
|
||||
report["missing_ids_sample"] = sorted(set(missing))[:5]
|
||||
if missing:
|
||||
log.error("ready attachments without object: %d (manual investigation needed)", len(missing))
|
||||
finally:
|
||||
conn.execute("SELECT pg_advisory_unlock(%s)", (JANITOR_LOCK_ID,))
|
||||
report["duration_ms"] = round((time.monotonic() - started) * 1000, 1)
|
||||
return report
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--once", action="store_true")
|
||||
parser.add_argument("--dry-run", action="store_true")
|
||||
parser.add_argument("--grace-seconds", type=int,
|
||||
default=int(os.environ.get("ATTACHMENT_GRACE_SECONDS", "3600")))
|
||||
parser.add_argument("--staging-retention-seconds", type=int, default=STAGING_RETENTION)
|
||||
parser.add_argument("--interval", type=int, default=int(os.environ.get("JANITOR_INTERVAL_SECONDS", "300")))
|
||||
args = parser.parse_args()
|
||||
if args.grace_seconds < 1:
|
||||
parser.error("grace period must be positive")
|
||||
STORE.open()
|
||||
try:
|
||||
while True:
|
||||
try:
|
||||
print(json.dumps(run_once(args.grace_seconds, args.dry_run, args.staging_retention_seconds),
|
||||
ensure_ascii=False), flush=True)
|
||||
except Exception as exc:
|
||||
log.warning("janitor pass failed (%s)", type(exc).__name__)
|
||||
if args.once:
|
||||
return 1
|
||||
if args.once:
|
||||
return 0
|
||||
wake = time.monotonic() + args.interval
|
||||
while time.monotonic() < wake:
|
||||
heartbeat()
|
||||
time.sleep(min(30, max(0.1, wake - time.monotonic())))
|
||||
finally:
|
||||
STORE.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
+364
@@ -0,0 +1,364 @@
|
||||
"""Задания обработки вложений: схема сообщения, переходы состояний, retry, lease, replay.
|
||||
|
||||
Используется API (постановка в очередь), worker, relay (reaper) и ops-CLI. Все переходы —
|
||||
SQL-транзакции над строкой jobs под FOR UPDATE, поэтому решение «что делать с сообщением»
|
||||
принимается по устойчивому состоянию в PostgreSQL, а не по факту доставки.
|
||||
|
||||
Сообщение брокера (contracts/jobs.schema.json) — только ссылка: job_id, attachment_id,
|
||||
pipeline_version, attempt. Bytes, credentials, URL и ключи S3 в сообщение не попадают:
|
||||
worker берёт доверенные storage metadata из БД.
|
||||
|
||||
Переходы (contracts/attachment-states.md):
|
||||
enqueue нет -> queued API, одна транзакция с outbox
|
||||
claim queued -> processing worker: attempt+1, lease_owner/token/until
|
||||
heartbeat processing (продление) worker, только со своим lease_token
|
||||
complete processing -> ready worker, только со своим lease_token (fencing)
|
||||
retry processing -> queued временная ошибка, backoff + jitter, outbox с available_at
|
||||
fail processing -> failed постоянная ошибка или исчерпаны попытки
|
||||
lease expired processing -> queued reaper (relay), если аренду никто не продлил
|
||||
replay failed -> queued оператор (ops.py), audit, ready не трогается
|
||||
"""
|
||||
import datetime as dt
|
||||
import json
|
||||
import random
|
||||
import uuid
|
||||
|
||||
SCHEMA_VERSION = 1
|
||||
JOB_TYPE = "attachment.process.v1"
|
||||
VARIANT_NAMES = ("thumbnail", "crop", "optimized")
|
||||
# Постоянные ошибки: повтор не поможет (тот же вход даст тот же результат).
|
||||
PERMANENT_ERRORS = {"invalid_image", "image_too_large", "staging_corrupted", "staging_missing",
|
||||
"resource_limit"}
|
||||
_UUID_FIELDS = ("job_id", "attachment_id")
|
||||
_ALLOWED = {"schema_version", "job_id", "type", "attachment_id", "pipeline_version", "attempt",
|
||||
"created_at", "traceparent", "tracestate"}
|
||||
|
||||
|
||||
class InvalidMessage(Exception):
|
||||
"""Сообщение не соответствует jobs.schema.json -> reject в DLQ."""
|
||||
|
||||
|
||||
def utc_now_text():
|
||||
return dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
|
||||
|
||||
def make_payload(job_id, attachment_id, pipeline_version, attempt, created_at=None):
|
||||
return {
|
||||
"schema_version": SCHEMA_VERSION,
|
||||
"job_id": str(job_id),
|
||||
"type": JOB_TYPE,
|
||||
"attachment_id": str(attachment_id),
|
||||
"pipeline_version": int(pipeline_version),
|
||||
"attempt": int(attempt),
|
||||
"created_at": created_at or utc_now_text(),
|
||||
}
|
||||
|
||||
|
||||
def parse_message(body):
|
||||
"""bytes -> dict по jobs.schema.json (без внешних библиотек). Иначе InvalidMessage."""
|
||||
try:
|
||||
msg = json.loads(body.decode("utf-8"))
|
||||
except (UnicodeDecodeError, ValueError):
|
||||
raise InvalidMessage("not json")
|
||||
if not isinstance(msg, dict):
|
||||
raise InvalidMessage("not object")
|
||||
if set(msg) - _ALLOWED:
|
||||
raise InvalidMessage("extra fields")
|
||||
for field in ("schema_version", "job_id", "type", "attachment_id", "pipeline_version", "attempt", "created_at"):
|
||||
if field not in msg:
|
||||
raise InvalidMessage("missing " + field)
|
||||
if msg["schema_version"] != SCHEMA_VERSION or msg["type"] != JOB_TYPE:
|
||||
raise InvalidMessage("unsupported type/version")
|
||||
for field in _UUID_FIELDS:
|
||||
try:
|
||||
if not isinstance(msg[field], str):
|
||||
raise ValueError
|
||||
uuid.UUID(msg[field])
|
||||
except ValueError:
|
||||
raise InvalidMessage("bad " + field)
|
||||
for field in ("pipeline_version", "attempt"):
|
||||
v = msg[field]
|
||||
if not isinstance(v, int) or isinstance(v, bool) or v < 1:
|
||||
raise InvalidMessage("bad " + field)
|
||||
if not isinstance(msg["created_at"], str):
|
||||
raise InvalidMessage("bad created_at")
|
||||
try:
|
||||
dt.datetime.fromisoformat(msg["created_at"].replace("Z", "+00:00"))
|
||||
except ValueError:
|
||||
raise InvalidMessage("bad created_at")
|
||||
return msg
|
||||
|
||||
|
||||
def backoff_seconds(attempt, base, cap, rng=random):
|
||||
"""Экспоненциальный backoff с «equal jitter»: d = min(cap, base*2^(attempt-1)),
|
||||
задержка равномерно в [d/2, d]. Половина гарантирует паузу (не долбим упавший S3),
|
||||
случайная половина разносит повторы многих заданий во времени (нет «стада»)."""
|
||||
d = min(float(cap), float(base) * (2 ** max(0, attempt - 1)))
|
||||
return d / 2 + rng.uniform(0, d / 2)
|
||||
|
||||
|
||||
def add_event(conn, job_id, event, attempt=None, actor=None, detail=None):
|
||||
conn.execute(
|
||||
"INSERT INTO job_events (job_id, event, attempt, actor, detail) VALUES (%s, %s, %s, %s, %s)",
|
||||
(job_id, event, attempt, actor, json.dumps(detail, ensure_ascii=False) if detail is not None else None))
|
||||
|
||||
|
||||
def add_outbox(conn, job_id, attachment_id, pipeline_version, attempt, delay_seconds=0.0):
|
||||
payload = make_payload(job_id, attachment_id, pipeline_version, attempt)
|
||||
conn.execute(
|
||||
"""INSERT INTO outbox (job_id, payload, available_at)
|
||||
VALUES (%s, %s, now() + make_interval(secs => %s))""",
|
||||
(job_id, json.dumps(payload), delay_seconds))
|
||||
return payload
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# API: постановка в очередь
|
||||
# ---------------------------------------------------------------------------
|
||||
def enqueue(conn, attachment_id, pipeline_version, max_attempts):
|
||||
"""В ТЕКУЩЕЙ транзакции: pending -> queued, jobs, outbox, событие. job_id или None."""
|
||||
row = conn.execute(
|
||||
"""UPDATE attachments SET status = 'queued', updated_at = now()
|
||||
WHERE id = %s AND status = 'pending' RETURNING id""", (attachment_id,)).fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
job_id = uuid.uuid4()
|
||||
conn.execute(
|
||||
"""INSERT INTO jobs (id, attachment_id, pipeline_version, status, attempt, max_attempts,
|
||||
next_attempt_at, created_at, updated_at)
|
||||
VALUES (%s, %s, %s, 'queued', 0, %s, now(), now(), now())""",
|
||||
(job_id, attachment_id, pipeline_version, max_attempts))
|
||||
add_event(conn, job_id, "enqueued", 1, "api")
|
||||
add_outbox(conn, job_id, attachment_id, pipeline_version, 1)
|
||||
return job_id
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Worker
|
||||
# ---------------------------------------------------------------------------
|
||||
JOB_COLUMNS = """j.id AS job_id, j.attachment_id, j.pipeline_version, j.status AS job_status, j.attempt,
|
||||
j.max_attempts, j.next_attempt_at, j.error_code, j.lease_owner, j.lease_token, j.lease_until, j.replay_count,
|
||||
j.lease_until > now() AS lease_alive, j.next_attempt_at > now() + interval '1 second' AS too_early,
|
||||
a.status AS attachment_status, a.content_type, a.size_bytes, a.sha256, a.width, a.height,
|
||||
a.object_key, a.staging_key, a.filename, a.pipeline_version AS current_pipeline_version"""
|
||||
|
||||
|
||||
def load_job(conn, job_id, lock=False):
|
||||
return conn.execute(
|
||||
"SELECT " + JOB_COLUMNS + " FROM jobs j JOIN attachments a ON a.id = j.attachment_id WHERE j.id = %s"
|
||||
+ (" FOR UPDATE OF j" if lock else ""), (job_id,)).fetchone()
|
||||
|
||||
|
||||
def _owner_host(owner):
|
||||
return (owner or "").split(":", 1)[0]
|
||||
|
||||
|
||||
def claim(conn, msg, owner, lease_seconds):
|
||||
"""Решение по сообщению. Возвращает (action, job):
|
||||
'process' — аренда взята (job со свежим lease_token), можно работать;
|
||||
'ack' — ничего делать не нужно (уже ready/failed, занято живой арендой, ранний дубль);
|
||||
'reject' — сообщение не соответствует заданию (в DLQ, разбирает оператор).
|
||||
Вызывается в транзакции; при 'process' коммит фиксирует processing ДО начала работы."""
|
||||
job = load_job(conn, msg["job_id"], lock=True)
|
||||
if job is None:
|
||||
return "reject", "unknown_job"
|
||||
if str(job["attachment_id"]) != msg["attachment_id"] or job["pipeline_version"] != msg["pipeline_version"]:
|
||||
return "reject", "job_mismatch"
|
||||
status = job["job_status"]
|
||||
if status == "ready":
|
||||
add_event(conn, job["job_id"], "duplicate_ignored", msg["attempt"], owner, {"status": "ready"})
|
||||
return "ack", job
|
||||
if status == "failed":
|
||||
add_event(conn, job["job_id"], "duplicate_ignored", msg["attempt"], owner, {"status": "failed"})
|
||||
return "ack", job
|
||||
if job["current_pipeline_version"] > job["pipeline_version"]:
|
||||
# Устаревшая job после новой версии pipeline: результат не публикуем.
|
||||
conn.execute("""UPDATE jobs SET status = 'failed', error_code = 'superseded', lease_owner = NULL,
|
||||
lease_token = NULL, lease_until = NULL, updated_at = now(), finished_at = now()
|
||||
WHERE id = %s""", (job["job_id"],))
|
||||
add_event(conn, job["job_id"], "superseded", msg["attempt"], owner)
|
||||
return "ack", job
|
||||
if status == "processing" and job["lease_alive"]:
|
||||
prev = job["lease_owner"] or ""
|
||||
# Тот же контейнер (hostname), но другой процесс (boot id): прежняя инкарнация этого
|
||||
# worker умерла (crash/restart) — два процесса одного контейнера одновременно не живут.
|
||||
if not (_owner_host(prev) == _owner_host(owner) and prev != owner):
|
||||
add_event(conn, job["job_id"], "busy_ignored", msg["attempt"], owner, {"lease_owner": prev})
|
||||
return "ack", job
|
||||
add_event(conn, job["job_id"], "lease_taken_over", job["attempt"], owner,
|
||||
{"previous_owner": prev, "reason": "previous process of this container died"})
|
||||
elif status == "processing":
|
||||
add_event(conn, job["job_id"], "lease_taken_over", job["attempt"], owner,
|
||||
{"previous_owner": job["lease_owner"], "reason": "lease expired"})
|
||||
elif job["too_early"]:
|
||||
# queued, но время следующей попытки ещё не пришло: это старый дубль, а запланированное
|
||||
# сообщение relay опубликует само (outbox.available_at).
|
||||
add_event(conn, job["job_id"], "early_duplicate_ignored", msg["attempt"], owner)
|
||||
return "ack", job
|
||||
if job["attempt"] >= job["max_attempts"]:
|
||||
_finish_failed(conn, job, "retry_exhausted", owner, "attempts exhausted before claim")
|
||||
return "ack", job
|
||||
token = uuid.uuid4()
|
||||
conn.execute(
|
||||
"""UPDATE jobs SET status = 'processing', attempt = attempt + 1, lease_owner = %s, lease_token = %s,
|
||||
lease_until = now() + make_interval(secs => %s), updated_at = now()
|
||||
WHERE id = %s""", (owner, token, lease_seconds, job["job_id"]))
|
||||
conn.execute("UPDATE attachments SET status = 'processing', updated_at = now() WHERE id = %s",
|
||||
(job["attachment_id"],))
|
||||
job = dict(job, attempt=job["attempt"] + 1, lease_token=token, job_status="processing")
|
||||
add_event(conn, job["job_id"], "claimed", job["attempt"], owner,
|
||||
{"redelivered_message_attempt": msg["attempt"]})
|
||||
return "process", job
|
||||
|
||||
|
||||
def heartbeat(conn, job_id, token, lease_seconds):
|
||||
"""Продлить аренду. False — аренда потеряна (reaper/другой worker), работу надо бросить."""
|
||||
cur = conn.execute(
|
||||
"""UPDATE jobs SET lease_until = now() + make_interval(secs => %s)
|
||||
WHERE id = %s AND lease_token = %s AND status = 'processing'""", (lease_seconds, job_id, token))
|
||||
return cur.rowcount == 1
|
||||
|
||||
|
||||
def complete(conn, job, variants, owner):
|
||||
"""processing -> ready атомарно с метаданными вариантов. Только владелец аренды (fencing по
|
||||
lease_token): опоздавший процесс, у которого аренду забрали, ничего не перезапишет.
|
||||
Возвращает 'ready' | 'already_ready' | 'lease_lost'."""
|
||||
cur = conn.execute(
|
||||
"""UPDATE jobs SET status = 'ready', lease_owner = NULL, lease_token = NULL, lease_until = NULL,
|
||||
error_code = NULL, last_error = NULL, updated_at = now(), finished_at = now()
|
||||
WHERE id = %s AND status = 'processing' AND lease_token = %s""", (job["job_id"], job["lease_token"]))
|
||||
if cur.rowcount != 1:
|
||||
now = load_job(conn, job["job_id"])
|
||||
add_event(conn, job["job_id"], "commit_rejected_lease_lost", job["attempt"], owner,
|
||||
{"current_status": now["job_status"]})
|
||||
return "already_ready" if now["job_status"] == "ready" else "lease_lost"
|
||||
with conn.cursor() as cur:
|
||||
# Ключ эффекта — PK (attachment_id, pipeline_version, name): второго набора не будет.
|
||||
cur.executemany(
|
||||
"""INSERT INTO attachment_variants (attachment_id, pipeline_version, name, object_key, content_type,
|
||||
size_bytes, width, height, sha256, created_at)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, now())
|
||||
ON CONFLICT (attachment_id, pipeline_version, name) DO UPDATE SET
|
||||
object_key = EXCLUDED.object_key, content_type = EXCLUDED.content_type,
|
||||
size_bytes = EXCLUDED.size_bytes, width = EXCLUDED.width, height = EXCLUDED.height,
|
||||
sha256 = EXCLUDED.sha256""",
|
||||
[(job["attachment_id"], job["pipeline_version"], v["name"], v["key"], v["content_type"],
|
||||
v["size_bytes"], v["width"], v["height"], v["sha256"]) for v in variants])
|
||||
# Не откатываем более новую версию pipeline (на случай нескольких версий, трек 5).
|
||||
conn.execute(
|
||||
"""UPDATE attachments SET status = 'ready', error_code = NULL, updated_at = now()
|
||||
WHERE id = %s AND pipeline_version <= %s""", (job["attachment_id"], job["pipeline_version"]))
|
||||
add_event(conn, job["job_id"], "ready", job["attempt"], owner,
|
||||
{"variants": {v["name"]: [v["width"], v["height"]] for v in variants}})
|
||||
return "ready"
|
||||
|
||||
|
||||
def _finish_failed(conn, job, code, actor, detail):
|
||||
conn.execute(
|
||||
"""UPDATE jobs SET status = 'failed', error_code = %s, last_error = %s, lease_owner = NULL,
|
||||
lease_token = NULL, lease_until = NULL, updated_at = now(), finished_at = now()
|
||||
WHERE id = %s""", (code, (detail or "")[:500], job["job_id"]))
|
||||
conn.execute("UPDATE attachments SET status = 'failed', error_code = %s, updated_at = now() WHERE id = %s",
|
||||
(code, job["attachment_id"]))
|
||||
add_event(conn, job["job_id"], "failed", job["attempt"], actor, {"error_code": code, "detail": detail})
|
||||
|
||||
|
||||
def fail_or_retry(conn, job, code, detail, owner, base, cap, rng=random):
|
||||
"""Ошибка попытки. Постоянная -> failed(code); временная -> queued с backoff, пока есть
|
||||
попытки, иначе failed(retry_exhausted). Только владелец аренды.
|
||||
Возвращает 'failed' | 'retry' | 'lease_lost' и задержку."""
|
||||
cur = load_job(conn, job["job_id"], lock=True)
|
||||
if cur["job_status"] != "processing" or cur["lease_token"] != job["lease_token"]:
|
||||
add_event(conn, job["job_id"], "error_ignored_lease_lost", job["attempt"], owner, {"error_code": code})
|
||||
return "lease_lost", None
|
||||
if code in PERMANENT_ERRORS:
|
||||
_finish_failed(conn, job, code, owner, detail)
|
||||
return "failed", None
|
||||
if cur["attempt"] >= cur["max_attempts"]:
|
||||
_finish_failed(conn, job, "retry_exhausted", owner, "last error: %s %s" % (code, detail or ""))
|
||||
return "failed", None
|
||||
delay = backoff_seconds(cur["attempt"], base, cap, rng)
|
||||
_schedule_retry(conn, cur, delay, code, detail, owner, "retry_scheduled")
|
||||
return "retry", delay
|
||||
|
||||
|
||||
def _schedule_retry(conn, job, delay, code, detail, actor, event):
|
||||
conn.execute(
|
||||
"""UPDATE jobs SET status = 'queued', lease_owner = NULL, lease_token = NULL, lease_until = NULL,
|
||||
error_code = NULL, last_error = %s, next_attempt_at = now() + make_interval(secs => %s),
|
||||
updated_at = now()
|
||||
WHERE id = %s""", (("%s: %s" % (code, detail or ""))[:500], delay, job["job_id"]))
|
||||
conn.execute("UPDATE attachments SET status = 'queued', updated_at = now() WHERE id = %s",
|
||||
(job["attachment_id"],))
|
||||
add_outbox(conn, job["job_id"], job["attachment_id"], job["pipeline_version"], job["attempt"] + 1, delay)
|
||||
add_event(conn, job["job_id"], event, job["attempt"], actor,
|
||||
{"error_code": code, "delay_seconds": round(delay, 3), "next_attempt": job["attempt"] + 1})
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Reaper (в relay): зависшие processing и потерянные сообщения
|
||||
# ---------------------------------------------------------------------------
|
||||
def reap_expired_leases(conn, base, cap, actor="reaper", limit=100):
|
||||
"""processing с истёкшей арендой (worker умер/завис и не продлевал lease) -> queued
|
||||
с backoff или failed(retry_exhausted). Возвращает число обработанных."""
|
||||
rows = conn.execute(
|
||||
"SELECT " + JOB_COLUMNS + """ FROM jobs j JOIN attachments a ON a.id = j.attachment_id
|
||||
WHERE j.status = 'processing' AND j.lease_until < now()
|
||||
ORDER BY j.lease_until LIMIT %s FOR UPDATE OF j SKIP LOCKED""", (limit,)).fetchall()
|
||||
for job in rows:
|
||||
add_event(conn, job["job_id"], "lease_expired", job["attempt"], actor, {"lease_owner": job["lease_owner"]})
|
||||
if job["attempt"] >= job["max_attempts"]:
|
||||
_finish_failed(conn, job, "retry_exhausted", actor, "lease expired on last attempt")
|
||||
else:
|
||||
_schedule_retry(conn, job, backoff_seconds(job["attempt"], base, cap), "lease_expired",
|
||||
"worker did not renew lease", actor, "requeued_after_lease")
|
||||
return len(rows)
|
||||
|
||||
|
||||
def redrive_stale_queued(conn, after_seconds, actor="reaper", limit=100):
|
||||
"""queued-задание, по которому давно нет ни неопубликованного outbox, ни движения:
|
||||
сообщение могло потеряться в брокере (например, после потери его volume). Публикуем
|
||||
ещё раз — дубль безопасен, решение примет worker по строке jobs."""
|
||||
rows = conn.execute(
|
||||
"""SELECT j.id, j.attachment_id, j.pipeline_version, j.attempt FROM jobs j
|
||||
WHERE j.status = 'queued' AND j.updated_at < now() - make_interval(secs => %s)
|
||||
AND j.next_attempt_at < now() - make_interval(secs => %s)
|
||||
AND NOT EXISTS (SELECT 1 FROM outbox o WHERE o.job_id = j.id AND o.published_at IS NULL)
|
||||
ORDER BY j.updated_at LIMIT %s FOR UPDATE OF j SKIP LOCKED""",
|
||||
(after_seconds, after_seconds, limit)).fetchall()
|
||||
for r in rows:
|
||||
conn.execute("UPDATE jobs SET updated_at = now() WHERE id = %s", (r["id"],))
|
||||
add_outbox(conn, r["id"], r["attachment_id"], r["pipeline_version"], r["attempt"] + 1)
|
||||
add_event(conn, r["id"], "redriven", r["attempt"] + 1, actor, {"stale_after_seconds": after_seconds})
|
||||
return len(rows)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Оператор: replay
|
||||
# ---------------------------------------------------------------------------
|
||||
def replay(conn, attachment_id, actor, extra_attempts, reason, dry_run=False):
|
||||
"""failed -> queued. Новая попытка того же job_id (прежний ключ эффекта), max_attempts
|
||||
увеличивается на extra_attempts. ready/queued/processing НЕ трогаются: «повторить» не
|
||||
означает выполнить дубль успешной работы. Возвращает (result, job)."""
|
||||
job = conn.execute(
|
||||
"SELECT " + JOB_COLUMNS + """ FROM jobs j JOIN attachments a ON a.id = j.attachment_id
|
||||
WHERE j.attachment_id = %s AND j.pipeline_version = a.pipeline_version FOR UPDATE OF j""",
|
||||
(attachment_id,)).fetchone()
|
||||
if job is None:
|
||||
return "not_found", None
|
||||
if job["job_status"] != "failed":
|
||||
return "refused_status_" + job["job_status"], job
|
||||
if job["staging_key"] is None:
|
||||
return "refused_staging_expired", job
|
||||
if dry_run:
|
||||
return "would_replay", job
|
||||
conn.execute(
|
||||
"""UPDATE jobs SET status = 'queued', max_attempts = attempt + %s, error_code = NULL,
|
||||
next_attempt_at = now(), replay_count = replay_count + 1, updated_at = now(), finished_at = NULL
|
||||
WHERE id = %s""", (extra_attempts, job["job_id"]))
|
||||
conn.execute("UPDATE attachments SET status = 'queued', error_code = NULL, updated_at = now() WHERE id = %s",
|
||||
(job["attachment_id"],))
|
||||
add_outbox(conn, job["job_id"], job["attachment_id"], job["pipeline_version"], job["attempt"] + 1)
|
||||
add_event(conn, job["job_id"], "replayed", job["attempt"] + 1, actor,
|
||||
{"reason": reason, "previous_error": job.get("error_code"), "replay_count": job["replay_count"] + 1})
|
||||
return "replayed", job
|
||||
@@ -0,0 +1,28 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Однократное применение миграций (compose-сервис `migrate`).
|
||||
|
||||
Запускается ОДИН раз до старта/замены API-реплик, а не каждой репликой.
|
||||
Дополнительно миграции выполняются под pg_advisory_xact_lock: даже если
|
||||
оператор случайно запустит job дважды параллельно, гонки не будет.
|
||||
Каждый файл применяется в своей транзакции и фиксируется в schema_migrations.
|
||||
"""
|
||||
import logging
|
||||
import sys
|
||||
|
||||
from server import MIGRATIONS_DIR, STORE
|
||||
|
||||
log = logging.getLogger("messenger.migrate")
|
||||
|
||||
|
||||
def main():
|
||||
STORE.open()
|
||||
try:
|
||||
before = STORE.pending_migrations(MIGRATIONS_DIR)
|
||||
STORE.migrate(MIGRATIONS_DIR)
|
||||
log.info("migrations done; applied now: %s", ", ".join(before) or "nothing")
|
||||
finally:
|
||||
STORE.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
+182
@@ -0,0 +1,182 @@
|
||||
"""Доступ к S3-совместимому хранилищу (SeaweedFS) через клиент minio-py.
|
||||
|
||||
API работает с bucket под ОТДЕЛЬНЫМИ credentials с правами только Read+Write на этот
|
||||
bucket (без List, без создания/удаления bucket, без политик и IAM) — см.
|
||||
scripts/init-secrets.sh и REPORT.md. Публичных URL/redirect нет: байты всегда идут
|
||||
через авторизованный API.
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
import urllib3
|
||||
from minio import Minio
|
||||
from minio.error import S3Error
|
||||
|
||||
log = logging.getLogger("messenger.s3")
|
||||
|
||||
# minio-py для объектов больше part_size делает multipart и держит в памяти
|
||||
# один part. 5 MiB — минимум S3: файл 10 MiB -> 2 части по 5 MiB.
|
||||
PART_SIZE = 5 * 1024 * 1024
|
||||
STREAM_CHUNK = 64 * 1024
|
||||
# Служебные объекты S3Health: health/<реплика> (вне prefix originals/, janitor их не трогает).
|
||||
HEALTH_PREFIX = "health/"
|
||||
|
||||
|
||||
class StorageUnavailable(Exception):
|
||||
"""S3 недоступен/таймаут/ошибка сервера -> 503."""
|
||||
|
||||
|
||||
class ObjectMissing(Exception):
|
||||
"""Метаданные есть, объекта нет (рассогласование) -> 503 + лог."""
|
||||
|
||||
|
||||
def _secret(name):
|
||||
path = os.environ.get(name + "_FILE")
|
||||
if path:
|
||||
with open(path, encoding="utf-8") as f:
|
||||
return f.read().strip()
|
||||
return os.environ.get(name, "")
|
||||
|
||||
|
||||
def make_client(access_env="S3_ACCESS_KEY_ID", secret_env="S3_SECRET_ACCESS_KEY",
|
||||
connect_timeout=None, read_timeout=None):
|
||||
endpoint = urlsplit(os.environ.get("S3_ENDPOINT", "http://s3:8333"))
|
||||
connect_timeout = connect_timeout or float(os.environ.get("S3_CONNECT_TIMEOUT_SECONDS", "2"))
|
||||
read_timeout = read_timeout or float(os.environ.get("S3_READ_TIMEOUT_SECONDS", "5"))
|
||||
# Короткие таймауты и без собственных повторов: зависший S3 не держит поток
|
||||
# дольше таймаута LB, повтор решает клиент (для upload — новым запросом).
|
||||
http = urllib3.PoolManager(
|
||||
timeout=urllib3.Timeout(connect=connect_timeout, read=read_timeout),
|
||||
retries=urllib3.Retry(total=0, connect=0, read=0, redirect=0, status=0),
|
||||
maxsize=int(os.environ.get("S3_POOL_SIZE", "16")),
|
||||
block=False)
|
||||
return Minio(endpoint.netloc, access_key=_secret(access_env), secret_key=_secret(secret_env),
|
||||
secure=endpoint.scheme == "https", region=os.environ.get("S3_REGION", "us-east-1"),
|
||||
http_client=http)
|
||||
|
||||
|
||||
def _is_transport_error(exc):
|
||||
return isinstance(exc, (urllib3.exceptions.HTTPError, OSError))
|
||||
|
||||
|
||||
class ObjectStore:
|
||||
def __init__(self, client, bucket):
|
||||
self.client = client
|
||||
self.bucket = bucket
|
||||
|
||||
def put(self, key, fileobj, length, content_type):
|
||||
try:
|
||||
self.client.put_object(self.bucket, key, fileobj, length, content_type=content_type,
|
||||
part_size=PART_SIZE)
|
||||
except S3Error as exc:
|
||||
log.warning("s3 put failed: %s", exc.code)
|
||||
raise StorageUnavailable()
|
||||
except Exception as exc:
|
||||
if _is_transport_error(exc):
|
||||
log.warning("s3 put failed: %s", type(exc).__name__)
|
||||
raise StorageUnavailable()
|
||||
raise
|
||||
|
||||
def open(self, key):
|
||||
"""Поток объекта (urllib3 response). Закрывать: resp.close(); resp.release_conn()."""
|
||||
try:
|
||||
return self.client.get_object(self.bucket, key)
|
||||
except S3Error as exc:
|
||||
if exc.code in ("NoSuchKey", "NoSuchObject"):
|
||||
raise ObjectMissing()
|
||||
log.warning("s3 get failed: %s", exc.code)
|
||||
raise StorageUnavailable()
|
||||
except Exception as exc:
|
||||
if _is_transport_error(exc):
|
||||
log.warning("s3 get failed: %s", type(exc).__name__)
|
||||
raise StorageUnavailable()
|
||||
raise
|
||||
|
||||
def delete(self, key):
|
||||
"""Идемпотентно: отсутствие объекта — не ошибка (S3 DELETE так и работает)."""
|
||||
try:
|
||||
self.client.remove_object(self.bucket, key)
|
||||
except S3Error as exc:
|
||||
if exc.code in ("NoSuchKey", "NoSuchObject"):
|
||||
return
|
||||
raise StorageUnavailable()
|
||||
except Exception as exc:
|
||||
if _is_transport_error(exc):
|
||||
raise StorageUnavailable()
|
||||
raise
|
||||
|
||||
def ping(self, probe_key):
|
||||
"""PUT + GET маленького служебного объекта health/<реплика>: проверяет S3,
|
||||
credentials и РЕАЛЬНЫЕ пути записи и чтения. HEAD bucket/healthz для этого мало:
|
||||
у SeaweedFS после рестарта они успешны, а первая запись ещё ~5 с висит
|
||||
(выбор raft-лидера master, выдача volume под запись)."""
|
||||
import io
|
||||
self.client.put_object(self.bucket, probe_key, io.BytesIO(b"ok"), 2, content_type="text/plain")
|
||||
resp = self.client.get_object(self.bucket, probe_key)
|
||||
try:
|
||||
if resp.read() != b"ok":
|
||||
raise RuntimeError("probe mismatch")
|
||||
finally:
|
||||
resp.close()
|
||||
resp.release_conn()
|
||||
return True
|
||||
|
||||
|
||||
class S3Health:
|
||||
"""Фоновая проверка S3, как DbHealth для PostgreSQL.
|
||||
|
||||
S3 НЕ входит в /health/ready: он общий для всех реплик, и его отказ не лечится
|
||||
исключением реплики из LB, а текстовые сообщения без него работают. Флаг нужен,
|
||||
чтобы upload при известном отказе S3 сразу получал 503, не принимая 10 MiB."""
|
||||
|
||||
def __init__(self, store, interval, stale_after, instance_id):
|
||||
self.store = store
|
||||
self.probe_key = HEALTH_PREFIX + instance_id
|
||||
self.interval = interval
|
||||
self.stale_after = stale_after
|
||||
self.last_ok = None
|
||||
self._stop = threading.Event()
|
||||
self._ok_event = threading.Event() # выставлен, пока последняя проверка успешна
|
||||
|
||||
def start(self):
|
||||
threading.Thread(target=self._loop, name="s3-health", daemon=True).start()
|
||||
|
||||
def stop(self):
|
||||
self._stop.set()
|
||||
|
||||
def ok(self):
|
||||
last = self.last_ok
|
||||
return last is not None and time.monotonic() - last <= self.stale_after
|
||||
|
||||
def wait_startup(self, timeout):
|
||||
"""Только на старте реплики (успешной проверки ещё не было): подождать до timeout,
|
||||
пока S3 станет доступен для записи. При подтверждённом отказе — не ждать."""
|
||||
if self.last_ok is None:
|
||||
self._ok_event.wait(timeout)
|
||||
return self.ok()
|
||||
|
||||
def known_down(self):
|
||||
"""S3 был доступен и перестал отвечать. На старте реплики (успешной проверки ещё
|
||||
не было) — False: чтение может работать раньше, чем прогреется запись."""
|
||||
last = self.last_ok
|
||||
return last is not None and time.monotonic() - last > self.stale_after
|
||||
|
||||
def _loop(self):
|
||||
healthy = None
|
||||
while not self._stop.is_set():
|
||||
try:
|
||||
self.store.ping(self.probe_key)
|
||||
self.last_ok = time.monotonic()
|
||||
self._ok_event.set()
|
||||
if healthy is not True:
|
||||
log.info("s3 health: ok")
|
||||
healthy = True
|
||||
except Exception as exc:
|
||||
self._ok_event.clear()
|
||||
if healthy is not False:
|
||||
log.warning("s3 health: failing (%s)", type(exc).__name__)
|
||||
healthy = False
|
||||
self._stop.wait(self.interval)
|
||||
+217
@@ -0,0 +1,217 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Операторский CLI (compose-сервис `ops`, profile tools). Вывод — JSON без секретов.
|
||||
|
||||
ops inspect <attachment_id> состояние: attachment, job, события, варианты, outbox, объекты S3
|
||||
ops failed [--limit N] реестр failed-заданий (DLQ на стороне БД)
|
||||
ops replay <attachment_id>... [--all-failed] [--error-code C] [--dry-run] [--reason TEXT]
|
||||
явный replay failed -> queued (ready/queued/processing не трогаются)
|
||||
ops dlq [--replay] [--purge-invalid]
|
||||
сообщения в RabbitMQ DLQ: показать; --replay — разобрать каждое
|
||||
по состоянию jobs (failed -> replay, остальное -> отбросить с audit)
|
||||
ops publish-raw <json> учебное: опубликовать произвольное тело (проверка DLQ)
|
||||
|
||||
Replay всегда проходит через строку jobs под FOR UPDATE: повтор ready-задания отклоняется,
|
||||
поэтому «повторить» не означает исполнить дубль уже успешной работы.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
import pika
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
import common
|
||||
import jobs
|
||||
import objstore
|
||||
|
||||
EXTRA_ATTEMPTS = common.env_int("JOB_MAX_ATTEMPTS", 5)
|
||||
|
||||
|
||||
def db():
|
||||
return psycopg.connect(common.database_conninfo(), row_factory=dict_row)
|
||||
|
||||
|
||||
def jsonable(value):
|
||||
if isinstance(value, dict):
|
||||
return {k: jsonable(v) for k, v in value.items()}
|
||||
if isinstance(value, (list, tuple)):
|
||||
return [jsonable(v) for v in value]
|
||||
if isinstance(value, (str, int, float, bool)) or value is None:
|
||||
return value
|
||||
if hasattr(value, "isoformat"):
|
||||
return value.isoformat().replace("+00:00", "Z")
|
||||
return str(value)
|
||||
|
||||
|
||||
def out(data):
|
||||
print(json.dumps(jsonable(data), ensure_ascii=False, indent=1))
|
||||
|
||||
|
||||
def s3_objects(prefix):
|
||||
"""Только имена/размеры (ключ janitor: List, без чтения содержимого)."""
|
||||
store = objstore.ObjectStore(objstore.make_client(), os.environ.get("S3_BUCKET", "messenger-attachments"))
|
||||
try:
|
||||
return sorted((o.object_name, o.size) for o in store.client.list_objects(store.bucket, prefix=prefix, recursive=True))
|
||||
except Exception as exc:
|
||||
return [("error", type(exc).__name__)]
|
||||
|
||||
|
||||
def cmd_inspect(args):
|
||||
with db() as conn:
|
||||
att = conn.execute(
|
||||
"""SELECT id, chat_id, status, error_code, content_type, size_bytes, sha256, width, height,
|
||||
object_key, staging_key, pipeline_version, created_at, updated_at
|
||||
FROM attachments WHERE id = %s""", (args.attachment_id,)).fetchone()
|
||||
if att is None:
|
||||
out({"error": "not_found"})
|
||||
return 1
|
||||
job = conn.execute(
|
||||
"""SELECT id, pipeline_version, status, attempt, max_attempts, next_attempt_at, lease_owner,
|
||||
lease_until, error_code, last_error, replay_count, created_at, updated_at, finished_at
|
||||
FROM jobs WHERE attachment_id = %s ORDER BY pipeline_version""", (args.attachment_id,)).fetchall()
|
||||
job_ids = [j["id"] for j in job]
|
||||
events = conn.execute(
|
||||
"SELECT job_id, at, event, attempt, actor, detail FROM job_events WHERE job_id = ANY(%s) ORDER BY id",
|
||||
(job_ids,)).fetchall()
|
||||
outbox = conn.execute(
|
||||
"""SELECT id, payload->>'attempt' AS attempt, available_at, created_at, published_at, publish_count
|
||||
FROM outbox WHERE job_id = ANY(%s) ORDER BY id""", (job_ids,)).fetchall()
|
||||
variants = conn.execute(
|
||||
"""SELECT pipeline_version, name, object_key, content_type, size_bytes, width, height, sha256
|
||||
FROM attachment_variants WHERE attachment_id = %s ORDER BY pipeline_version, name""",
|
||||
(args.attachment_id,)).fetchall()
|
||||
objects = s3_objects("attachments/%s/" % args.attachment_id)
|
||||
staging = s3_objects(att["staging_key"]) if att["staging_key"] else []
|
||||
out({"attachment": att, "jobs": job, "events": events, "outbox": outbox, "variants": variants,
|
||||
"s3_final_objects": objects, "s3_staging_objects": staging})
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_failed(args):
|
||||
with db() as conn:
|
||||
rows = conn.execute(
|
||||
"""SELECT j.attachment_id, j.id AS job_id, j.error_code, j.attempt, j.max_attempts, j.replay_count,
|
||||
j.last_error, j.updated_at, a.staging_key IS NOT NULL AS replayable
|
||||
FROM jobs j JOIN attachments a ON a.id = j.attachment_id
|
||||
WHERE j.status = 'failed' ORDER BY j.updated_at DESC LIMIT %s""", (args.limit,)).fetchall()
|
||||
out({"failed": rows, "count": len(rows)})
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_replay(args):
|
||||
results = []
|
||||
with db() as conn:
|
||||
ids = list(args.attachment_ids)
|
||||
if args.all_failed:
|
||||
q = "SELECT attachment_id FROM jobs WHERE status = 'failed'"
|
||||
params = []
|
||||
if args.error_code:
|
||||
q += " AND error_code = %s"
|
||||
params.append(args.error_code)
|
||||
ids += [str(r["attachment_id"]) for r in conn.execute(q, params)]
|
||||
for att_id in ids:
|
||||
with conn.transaction():
|
||||
result, job = jobs.replay(conn, att_id, "ops:" + common.HOSTNAME, EXTRA_ATTEMPTS,
|
||||
args.reason, dry_run=args.dry_run)
|
||||
results.append({"attachment_id": att_id, "result": result,
|
||||
"job_id": str(job["job_id"]) if job else None})
|
||||
out({"replay": results})
|
||||
return 0 if all(r["result"] in ("replayed", "would_replay") for r in results) else 3
|
||||
|
||||
|
||||
def broker_channel():
|
||||
conn = pika.BlockingConnection(common.broker_parameters())
|
||||
return conn, conn.channel()
|
||||
|
||||
|
||||
def cmd_dlq(args):
|
||||
conn, ch = broker_channel()
|
||||
seen = []
|
||||
tags = []
|
||||
try:
|
||||
with db() as dbc:
|
||||
while True:
|
||||
method, props, body = ch.basic_get(common.DLQ, auto_ack=False)
|
||||
if method is None:
|
||||
break
|
||||
deaths = (props.headers or {}).get("x-death") or []
|
||||
reason = deaths[0].get("reason") if deaths else None
|
||||
item = {"reason": reason.decode() if isinstance(reason, bytes) else reason,
|
||||
"delivery_count": (props.headers or {}).get("x-delivery-count"), "action": "kept"}
|
||||
try:
|
||||
msg = jobs.parse_message(body)
|
||||
item["job_id"] = msg["job_id"]
|
||||
if args.replay:
|
||||
with dbc.transaction():
|
||||
job = jobs.load_job(dbc, msg["job_id"], lock=True)
|
||||
if job is None:
|
||||
item["action"] = "kept_unknown_job"
|
||||
elif job["job_status"] == "failed":
|
||||
result, _ = jobs.replay(dbc, str(job["attachment_id"]), "ops-dlq", EXTRA_ATTEMPTS,
|
||||
"dlq replay")
|
||||
item["action"] = result
|
||||
else:
|
||||
# queued/processing/ready: состояние уже ведёт БД, дубль не нужен.
|
||||
jobs.add_event(dbc, job["job_id"], "dlq_message_dropped", msg["attempt"], "ops-dlq",
|
||||
{"job_status": job["job_status"], "reason": item["reason"]})
|
||||
item["action"] = "dropped_job_" + job["job_status"]
|
||||
except jobs.InvalidMessage as exc:
|
||||
item["invalid"] = str(exc)
|
||||
if args.purge_invalid:
|
||||
item["action"] = "purged_invalid"
|
||||
seen.append(item)
|
||||
if item["action"].startswith("kept"):
|
||||
tags.append(method.delivery_tag) # вернём в DLQ после обхода
|
||||
else:
|
||||
ch.basic_ack(method.delivery_tag)
|
||||
for tag in tags:
|
||||
ch.basic_nack(tag, requeue=True)
|
||||
finally:
|
||||
conn.close()
|
||||
out({"dlq_messages": seen, "count": len(seen)})
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_publish_raw(args):
|
||||
conn, ch = broker_channel()
|
||||
try:
|
||||
ch.confirm_delivery()
|
||||
ch.basic_publish(common.EXCHANGE, common.ROUTING_KEY, args.body.encode(),
|
||||
pika.BasicProperties(delivery_mode=2, content_type="application/json"), mandatory=True)
|
||||
finally:
|
||||
conn.close()
|
||||
out({"published": True})
|
||||
return 0
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(prog="ops")
|
||||
sub = p.add_subparsers(dest="cmd", required=True)
|
||||
s = sub.add_parser("inspect")
|
||||
s.add_argument("attachment_id")
|
||||
s.set_defaults(func=cmd_inspect)
|
||||
s = sub.add_parser("failed")
|
||||
s.add_argument("--limit", type=int, default=50)
|
||||
s.set_defaults(func=cmd_failed)
|
||||
s = sub.add_parser("replay")
|
||||
s.add_argument("attachment_ids", nargs="*")
|
||||
s.add_argument("--all-failed", action="store_true")
|
||||
s.add_argument("--error-code")
|
||||
s.add_argument("--dry-run", action="store_true")
|
||||
s.add_argument("--reason", default="operator replay")
|
||||
s.set_defaults(func=cmd_replay)
|
||||
s = sub.add_parser("dlq")
|
||||
s.add_argument("--replay", action="store_true")
|
||||
s.add_argument("--purge-invalid", action="store_true")
|
||||
s.set_defaults(func=cmd_dlq)
|
||||
s = sub.add_parser("publish-raw")
|
||||
s.add_argument("body")
|
||||
s.set_defaults(func=cmd_publish_raw)
|
||||
args = p.parse_args()
|
||||
return args.func(args)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
+201
@@ -0,0 +1,201 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Outbox relay + reaper (compose-сервис `relay`).
|
||||
|
||||
Закрывает разрыв PostgreSQL <-> broker (transactional outbox):
|
||||
API в ОДНОЙ транзакции пишет queued-вложение, jobs и outbox. Relay берёт неопубликованные
|
||||
строки (FOR UPDATE SKIP LOCKED — несколько relay не мешают друг другу), публикует каждую
|
||||
в RabbitMQ с publisher confirm (persistent, mandatory) и только ПОСЛЕ подтверждения
|
||||
брокера ставит published_at в той же транзакции. Крах между COMMIT API и publish, между
|
||||
publish и confirm или между confirm и UPDATE outbox -> строка остаётся неопубликованной и
|
||||
будет опубликована снова: возможен дубль сообщения (at-least-once), его гасит worker по
|
||||
состоянию jobs.
|
||||
|
||||
Будит relay NOTIFY из триггера outbox; без уведомления — опрос раз в RELAY_POLL_SECONDS.
|
||||
Строки с available_at в будущем (retry с backoff) публикуются, когда наступит срок.
|
||||
|
||||
Reaper (раз в REAPER_INTERVAL_SECONDS, под advisory-блокировкой — один на всех):
|
||||
* processing с истёкшей арендой -> queued (backoff) или failed(retry_exhausted);
|
||||
* queued без движения дольше JOB_REDRIVE_AFTER_SECONDS и без неопубликованного outbox
|
||||
-> ещё одна публикация (сообщение могло потеряться вместе с volume брокера);
|
||||
* опубликованные строки outbox старше OUTBOX_RETENTION_SECONDS удаляются.
|
||||
|
||||
Учебная инъекция отказа: RELAY_FAULT=crash-before-publish | crash-after-publish —
|
||||
один раз за жизнь контейнера (маркер в /tmp) процесс делает os._exit посреди батча.
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
import pika
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
import common
|
||||
import jobs
|
||||
|
||||
log = logging.getLogger("relay")
|
||||
POLL_SECONDS = common.env_float("RELAY_POLL_SECONDS", 1)
|
||||
BATCH = common.env_int("RELAY_BATCH", 100)
|
||||
REAPER_INTERVAL = common.env_float("REAPER_INTERVAL_SECONDS", 5)
|
||||
REDRIVE_AFTER = common.env_int("JOB_REDRIVE_AFTER_SECONDS", 900)
|
||||
OUTBOX_RETENTION = common.env_int("OUTBOX_RETENTION_SECONDS", 86400)
|
||||
RETRY_BASE = common.env_float("JOB_RETRY_BASE_SECONDS", 2)
|
||||
RETRY_MAX = common.env_float("JOB_RETRY_MAX_SECONDS", 60)
|
||||
FAULT = os.environ.get("RELAY_FAULT", "")
|
||||
FAULT_MARKER = "/tmp/relay-fault.done"
|
||||
HEARTBEAT = "/tmp/relay.heartbeat"
|
||||
REAPER_LOCK_ID = 727003
|
||||
|
||||
|
||||
def fault(point):
|
||||
if FAULT != point or os.path.exists(FAULT_MARKER):
|
||||
return
|
||||
with open(FAULT_MARKER, "w") as f:
|
||||
f.write(point)
|
||||
log.warning("FAULT INJECTION %s: exiting without finishing the batch", point)
|
||||
os._exit(86)
|
||||
|
||||
|
||||
class Relay:
|
||||
def __init__(self):
|
||||
self.conninfo = common.database_conninfo()
|
||||
self.db = None
|
||||
self.listen = None
|
||||
self.broker = None
|
||||
self.channel = None
|
||||
self.next_reap = 0.0
|
||||
self.stop = threading.Event()
|
||||
|
||||
# --- соединения ---
|
||||
def ensure_db(self):
|
||||
if self.db is None or self.db.closed:
|
||||
self.db = psycopg.connect(self.conninfo, row_factory=dict_row)
|
||||
if self.listen is None or self.listen.closed:
|
||||
self.listen = psycopg.connect(self.conninfo, autocommit=True)
|
||||
self.listen.execute("LISTEN outbox")
|
||||
|
||||
def ensure_broker(self):
|
||||
if self.broker is None or self.broker.is_closed or self.channel is None or self.channel.is_closed:
|
||||
self.close_broker()
|
||||
self.broker = common.connect_broker(log, self.stop)
|
||||
if self.broker is None:
|
||||
return
|
||||
self.channel = self.broker.channel()
|
||||
# Publisher confirms: basic_publish ждёт ack брокера (сообщение записано в
|
||||
# quorum-очередь) и бросает NackError/UnroutableError при отказе.
|
||||
self.channel.confirm_delivery()
|
||||
log.info("connected to broker")
|
||||
|
||||
def close_broker(self):
|
||||
try:
|
||||
if self.broker is not None and not self.broker.is_closed:
|
||||
self.broker.close()
|
||||
except Exception:
|
||||
pass
|
||||
self.broker = self.channel = None
|
||||
|
||||
def close_db(self):
|
||||
for conn in (self.db, self.listen):
|
||||
try:
|
||||
if conn is not None:
|
||||
conn.close()
|
||||
except Exception:
|
||||
pass
|
||||
self.db = self.listen = None
|
||||
|
||||
# --- публикация ---
|
||||
def publish_batch(self):
|
||||
"""Один батч в одной транзакции. Возвращает число опубликованных строк."""
|
||||
with self.db.transaction():
|
||||
rows = self.db.execute(
|
||||
"""SELECT id, job_id, payload FROM outbox
|
||||
WHERE published_at IS NULL AND available_at <= now()
|
||||
ORDER BY available_at, id LIMIT %s FOR UPDATE SKIP LOCKED""", (BATCH,)).fetchall()
|
||||
if not rows:
|
||||
return 0
|
||||
fault("crash-before-publish") # COMMIT задания есть, publish ещё нет
|
||||
for row in rows:
|
||||
payload = row["payload"]
|
||||
self.channel.basic_publish(
|
||||
exchange=common.EXCHANGE, routing_key=common.ROUTING_KEY,
|
||||
body=json.dumps(payload, separators=(",", ":")).encode(),
|
||||
properties=pika.BasicProperties(
|
||||
content_type="application/json", delivery_mode=pika.DeliveryMode.Persistent,
|
||||
message_id="%s:%s" % (payload["job_id"], payload["attempt"]), type=jobs.JOB_TYPE,
|
||||
headers={"x-outbox-id": row["id"]}),
|
||||
mandatory=True)
|
||||
fault("crash-after-publish") # confirm получен, published_at не записан -> дубль
|
||||
self.db.execute(
|
||||
"UPDATE outbox SET published_at = now(), publish_count = publish_count + 1 WHERE id = ANY(%s)",
|
||||
([r["id"] for r in rows],))
|
||||
log.info("published %d job message(s)", len(rows))
|
||||
return len(rows)
|
||||
|
||||
def reap(self):
|
||||
with self.db.transaction():
|
||||
if not self.db.execute("SELECT pg_try_advisory_xact_lock(%s) AS ok", (REAPER_LOCK_ID,)).fetchone()["ok"]:
|
||||
return
|
||||
expired = jobs.reap_expired_leases(self.db, RETRY_BASE, RETRY_MAX, actor="reaper:" + common.OWNER)
|
||||
redriven = jobs.redrive_stale_queued(self.db, REDRIVE_AFTER, actor="reaper:" + common.OWNER)
|
||||
purged = self.db.execute(
|
||||
"DELETE FROM outbox WHERE published_at < now() - make_interval(secs => %s)",
|
||||
(OUTBOX_RETENTION,)).rowcount
|
||||
if expired or redriven or purged:
|
||||
log.info("reaper: expired_leases=%d redriven=%d outbox_purged=%d", expired, redriven, purged)
|
||||
|
||||
def wait_notify(self, timeout):
|
||||
"""Ждём NOTIFY outbox не дольше timeout; параллельно обслуживаем heartbeat брокера."""
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
if self.broker is not None:
|
||||
self.broker.process_data_events(time_limit=0)
|
||||
for _ in self.listen.notifies(timeout=min(0.25, max(0.01, deadline - time.monotonic())), stop_after=1):
|
||||
return
|
||||
|
||||
def run(self):
|
||||
log.info("relay started owner=%s fault=%s", common.OWNER, FAULT or "-")
|
||||
delay = 0.5
|
||||
while not self.stop.is_set():
|
||||
common.touch(HEARTBEAT)
|
||||
try:
|
||||
self.ensure_db()
|
||||
self.ensure_broker()
|
||||
if self.broker is None:
|
||||
continue
|
||||
while self.publish_batch() == BATCH:
|
||||
pass
|
||||
if time.monotonic() >= self.next_reap:
|
||||
self.reap()
|
||||
self.next_reap = time.monotonic() + REAPER_INTERVAL
|
||||
self.wait_notify(POLL_SECONDS)
|
||||
delay = 0.5
|
||||
except (pika.exceptions.AMQPError, pika.exceptions.UnroutableError, pika.exceptions.NackError) as exc:
|
||||
# Транзакция батча откатилась: строки остались неопубликованными.
|
||||
log.warning("broker publish failed (%s), retry in %.1fs", type(exc).__name__, delay)
|
||||
self.close_broker()
|
||||
self.stop.wait(delay)
|
||||
delay = min(5.0, delay * 2)
|
||||
except psycopg.Error as exc:
|
||||
log.warning("database error (%s), retry in %.1fs", type(exc).__name__, delay)
|
||||
self.close_db()
|
||||
self.stop.wait(delay)
|
||||
delay = min(5.0, delay * 2)
|
||||
self.close_broker()
|
||||
self.close_db()
|
||||
|
||||
|
||||
def main():
|
||||
import signal
|
||||
relay = Relay()
|
||||
signal.signal(signal.SIGTERM, lambda *_: relay.stop.set())
|
||||
signal.signal(signal.SIGINT, lambda *_: relay.stop.set())
|
||||
relay.run()
|
||||
log.info("relay stopped")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,84 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Идемпотентный bootstrap S3 (однократный compose-job `s3-init`).
|
||||
|
||||
Работает под admin-credentials, которые есть ТОЛЬКО у этого job (API и janitor их не
|
||||
получают). Повторный запуск ничего не ломает:
|
||||
1. ждёт доступности S3 (до 60 с);
|
||||
2. создаёт bucket, если его нет (уже существующий — не ошибка);
|
||||
3. проверяет приватность: анонимные GET объекта и ListBucket должны получить 403.
|
||||
Если bucket вдруг публичен — exit 1, и API не стартует (depends_on).
|
||||
Права пользователей (api: Read+Write, janitor: List+Write) задаются декларативно в
|
||||
secrets/s3_identities.json (генерирует scripts/init-secrets.sh).
|
||||
"""
|
||||
import io
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
from minio.error import S3Error
|
||||
|
||||
import objstore
|
||||
|
||||
logging.basicConfig(stream=sys.stdout, level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||
log = logging.getLogger("messenger.s3-init")
|
||||
|
||||
|
||||
def anonymous_status(url):
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=3) as resp:
|
||||
return resp.status
|
||||
except urllib.error.HTTPError as exc:
|
||||
return exc.code
|
||||
|
||||
|
||||
def main():
|
||||
bucket = os.environ.get("S3_BUCKET", "messenger-attachments")
|
||||
endpoint = os.environ.get("S3_ENDPOINT", "http://s3:8333").rstrip("/")
|
||||
# Первый PUT в новый bucket ждёт, пока SeaweedFS выделит volume-ы коллекции: таймаут больше.
|
||||
client = objstore.make_client(read_timeout=30)
|
||||
deadline = time.monotonic() + 60
|
||||
while True:
|
||||
try:
|
||||
exists = client.bucket_exists(bucket)
|
||||
break
|
||||
except Exception as exc:
|
||||
if time.monotonic() > deadline:
|
||||
raise
|
||||
log.info("s3 not ready (%s), retrying", type(exc).__name__)
|
||||
time.sleep(1)
|
||||
created = False
|
||||
if not exists:
|
||||
try:
|
||||
client.make_bucket(bucket)
|
||||
created = True
|
||||
except S3Error as exc:
|
||||
if exc.code not in ("BucketAlreadyOwnedByYou", "BucketAlreadyExists"):
|
||||
raise
|
||||
# Контрольный объект: на нём проверяем, что анонимный GET не проходит.
|
||||
probe = "bootstrap/probe"
|
||||
for attempt in range(1, 6):
|
||||
try:
|
||||
client.put_object(bucket, probe, io.BytesIO(b"private"), 7, content_type="text/plain")
|
||||
break
|
||||
except Exception as exc:
|
||||
if attempt == 5:
|
||||
raise
|
||||
log.info("probe put failed (%s), retry %d", type(exc).__name__, attempt)
|
||||
time.sleep(2)
|
||||
checks = {
|
||||
"anonymous_get_object": anonymous_status("%s/%s/%s" % (endpoint, bucket, probe)),
|
||||
"anonymous_list_bucket": anonymous_status("%s/%s?list-type=2" % (endpoint, bucket)),
|
||||
}
|
||||
client.remove_object(bucket, probe)
|
||||
private = all(code in (401, 403) for code in checks.values())
|
||||
print(json.dumps({"bucket": bucket, "created": created, "already_existed": exists,
|
||||
"anonymous_http_status": checks, "private": private}), flush=True)
|
||||
return 0 if private else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,53 @@
|
||||
"""Пароли (scrypt из стандартной библиотеки) и сессионные токены."""
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import os
|
||||
import secrets
|
||||
|
||||
# Параметры scrypt: N=2^15, r=8, p=1 (~32 МБ памяти и ~0.1 с на проверку).
|
||||
SCRYPT_LOG_N = 15
|
||||
SCRYPT_R = 8
|
||||
SCRYPT_P = 1
|
||||
_MAXMEM = 128 * 1024 * 1024
|
||||
|
||||
|
||||
def _scrypt(password, salt, log_n, r, p):
|
||||
return hashlib.scrypt(password.encode("utf-8"), salt=salt, n=2 ** log_n, r=r, p=p,
|
||||
maxmem=_MAXMEM, dklen=32)
|
||||
|
||||
|
||||
def hash_password(password):
|
||||
"""Возвращает строку scrypt$logN$r$p$salt$hash; plaintext нигде не хранится."""
|
||||
salt = os.urandom(16)
|
||||
digest = _scrypt(password, salt, SCRYPT_LOG_N, SCRYPT_R, SCRYPT_P)
|
||||
return "scrypt$%d$%d$%d$%s$%s" % (
|
||||
SCRYPT_LOG_N, SCRYPT_R, SCRYPT_P,
|
||||
base64.b64encode(salt).decode(), base64.b64encode(digest).decode())
|
||||
|
||||
|
||||
def verify_password(password, stored):
|
||||
try:
|
||||
scheme, log_n, r, p, salt, digest = stored.split("$")
|
||||
if scheme != "scrypt":
|
||||
return False
|
||||
expected = base64.b64decode(digest)
|
||||
actual = _scrypt(password, base64.b64decode(salt), int(log_n), int(r), int(p))
|
||||
except (ValueError, TypeError):
|
||||
return False
|
||||
return hmac.compare_digest(actual, expected) # сравнение за постоянное время
|
||||
|
||||
|
||||
# Хеш несуществующего пользователя: неверный логин тратит столько же времени,
|
||||
# сколько неверный пароль, и не выдаёт, существует ли username.
|
||||
DUMMY_HASH = hash_password(secrets.token_urlsafe(16))
|
||||
|
||||
|
||||
def new_token():
|
||||
"""Непрозрачный случайный токен: 32 байта = 256 бит энтропии."""
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
|
||||
def token_hash(token):
|
||||
"""В БД лежит только SHA-256 токена: утечка таблицы не даёт готовых сессий."""
|
||||
return hashlib.sha256(token.encode("utf-8")).digest()
|
||||
+1079
File diff suppressed because it is too large
Load Diff
+413
@@ -0,0 +1,413 @@
|
||||
"""Работа с PostgreSQL: пользователи, чаты, сообщения, сессии, метаданные вложений.
|
||||
|
||||
Lab5: вложение создаётся как pending (скрыто), после записи оригинала в staging одной
|
||||
транзакцией становится queued вместе с заданием и записью outbox (src/jobs.py).
|
||||
|
||||
Источник истины — база данных. В памяти процесса состояния нет, поэтому
|
||||
перезапуск API (и самой БД с сохранённым volume) не теряет данные.
|
||||
"""
|
||||
import datetime as dt
|
||||
import logging
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
import jobs
|
||||
from psycopg_pool import ConnectionPool
|
||||
|
||||
log = logging.getLogger("messenger.store")
|
||||
|
||||
EPOCH = dt.datetime(1970, 1, 1, tzinfo=dt.timezone.utc)
|
||||
MIGRATIONS_LOCK_ID = 727001 # произвольный номер advisory-блокировки для миграций
|
||||
|
||||
|
||||
class Conflict(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class UnknownMember(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class AttachmentNotFound(Exception):
|
||||
"""Вложение неизвестно, не принято (pending) или принадлежит другому чату -> 404."""
|
||||
|
||||
|
||||
class AttachmentFailed(Exception):
|
||||
"""Вложение в состоянии failed: прикреплять нельзя -> 409."""
|
||||
|
||||
|
||||
def format_ts(value):
|
||||
"""datetime -> RFC 3339 UTC с микросекундами и суффиксом Z."""
|
||||
return value.astimezone(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
|
||||
|
||||
|
||||
def to_micros(value):
|
||||
delta = value - EPOCH
|
||||
return (delta.days * 86400 + delta.seconds) * 1_000_000 + delta.microseconds
|
||||
|
||||
|
||||
def from_micros(micros):
|
||||
return EPOCH + dt.timedelta(microseconds=micros)
|
||||
|
||||
|
||||
def _user(row):
|
||||
# Пароль/hash и сессионные данные никогда не входят в User.
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"username": row["username"],
|
||||
"display_name": row["display_name"],
|
||||
"created_at": format_ts(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
def _chat(row):
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"title": row["title"],
|
||||
"member_ids": [str(m) for m in row["member_ids"]],
|
||||
"created_at": format_ts(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
def _message(row):
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"chat_id": str(row["chat_id"]),
|
||||
"sender_id": str(row["sender_id"]),
|
||||
"text": row["text"],
|
||||
"created_at": format_ts(row["created_at"]),
|
||||
"attachment_ids": [str(a) for a in (row["attachment_ids"] or [])],
|
||||
}
|
||||
|
||||
|
||||
def _attachment(row):
|
||||
# Наружу не отдаются object_key, bucket и внутренние адреса.
|
||||
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": row["size_bytes"],
|
||||
"sha256": row["sha256"],
|
||||
"status": row["status"],
|
||||
# Варианты показываются только у ready (их наличие = готовность уровня).
|
||||
"variants": list(row["variants"] or []) if row["status"] == "ready" else [],
|
||||
"error_code": row["error_code"] if row["status"] == "failed" else None,
|
||||
"created_at": format_ts(row["created_at"]),
|
||||
"updated_at": format_ts(row["updated_at"]),
|
||||
}
|
||||
|
||||
|
||||
ATTACHMENT_COLUMNS = """a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, a.sha256,
|
||||
a.status, a.error_code, a.object_key, a.created_at, a.updated_at,
|
||||
(SELECT json_agg(json_build_object('name', v.name, 'content_type', v.content_type,
|
||||
'size_bytes', v.size_bytes, 'width', v.width, 'height', v.height, 'sha256', v.sha256)
|
||||
ORDER BY array_position(ARRAY['thumbnail','crop','optimized'], v.name))
|
||||
FROM attachment_variants v
|
||||
WHERE v.attachment_id = a.id AND v.pipeline_version = a.pipeline_version) AS variants"""
|
||||
|
||||
|
||||
MESSAGE_COLUMNS = """m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
||||
(SELECT array_agg(ma.attachment_id ORDER BY ma.position) FROM message_attachments ma
|
||||
WHERE ma.message_id = m.id) AS attachment_ids"""
|
||||
|
||||
CHAT_COLUMNS = """c.id, c.title, c.created_at,
|
||||
(SELECT array_agg(m.user_id ORDER BY m.position) FROM chat_members m WHERE m.chat_id = c.id) AS member_ids"""
|
||||
|
||||
|
||||
class Store:
|
||||
def __init__(self, conninfo, pool_size=10, pool_timeout=3):
|
||||
# check: перед выдачей соединение проверяется. После перезапуска PostgreSQL
|
||||
# «мёртвые» соединения отбрасываются, и запрос не получает ложный 503.
|
||||
self.pool = ConnectionPool(
|
||||
conninfo, min_size=1, max_size=pool_size, timeout=pool_timeout,
|
||||
kwargs={"row_factory": dict_row}, open=False,
|
||||
check=ConnectionPool.check_connection)
|
||||
|
||||
# --- запуск ---
|
||||
def open(self, wait_seconds=60):
|
||||
"""Ждём готовности БД (она может стартовать дольше API) и открываем пул."""
|
||||
self.pool.open()
|
||||
deadline = time.monotonic() + wait_seconds
|
||||
while True:
|
||||
try:
|
||||
with self.pool.connection() as conn:
|
||||
conn.execute("SELECT 1")
|
||||
return
|
||||
except Exception as exc:
|
||||
if time.monotonic() > deadline:
|
||||
raise
|
||||
log.info("database is not ready yet (%s), retrying", type(exc).__name__)
|
||||
time.sleep(1)
|
||||
|
||||
def close(self):
|
||||
self.pool.close()
|
||||
|
||||
def migrate(self, directory):
|
||||
"""Применяет *.sql по порядку имён; каждая миграция — одна транзакция, один раз."""
|
||||
files = sorted(Path(directory).glob("*.sql"))
|
||||
with self.pool.connection() as conn:
|
||||
# Advisory-блокировка (сессионная): параллельный повторный запуск job не устроит гонку.
|
||||
conn.autocommit = True
|
||||
conn.execute("SELECT pg_advisory_lock(%s)", (MIGRATIONS_LOCK_ID,))
|
||||
try:
|
||||
conn.execute("""CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())""")
|
||||
done = {r["version"] for r in conn.execute("SELECT version FROM schema_migrations")}
|
||||
for path in files:
|
||||
if path.name in done:
|
||||
continue
|
||||
# Миграция и её отметка — одна транзакция: либо целиком, либо никак.
|
||||
with conn.transaction():
|
||||
conn.execute(path.read_text(encoding="utf-8"))
|
||||
conn.execute("INSERT INTO schema_migrations (version) VALUES (%s)", (path.name,))
|
||||
log.info("migration applied: %s", path.name)
|
||||
finally:
|
||||
conn.execute("SELECT pg_advisory_unlock(%s)", (MIGRATIONS_LOCK_ID,))
|
||||
conn.autocommit = False
|
||||
|
||||
def pending_migrations(self, directory):
|
||||
"""Миграции из каталога образа, ещё не применённые к БД (API их НЕ применяет)."""
|
||||
files = sorted(p.name for p in Path(directory).glob("*.sql"))
|
||||
with self.pool.connection() as conn:
|
||||
exists = conn.execute("SELECT to_regclass('schema_migrations') IS NOT NULL AS ok").fetchone()["ok"]
|
||||
done = {r["version"] for r in conn.execute("SELECT version FROM schema_migrations")} if exists else set()
|
||||
return [f for f in files if f not in done]
|
||||
|
||||
def ping(self):
|
||||
with self.pool.connection() as conn:
|
||||
conn.execute("SELECT 1")
|
||||
|
||||
# --- пользователи ---
|
||||
def create_user(self, username, display_name, password_hash):
|
||||
try:
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"""INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES (%s, %s, %s, %s, clock_timestamp())
|
||||
RETURNING id, username, display_name, created_at""",
|
||||
(uuid.uuid4(), username, display_name, password_hash)).fetchone()
|
||||
except psycopg.errors.UniqueViolation:
|
||||
# Уникальность гарантирует сама БД — гонка двух регистраций безопасна.
|
||||
raise Conflict()
|
||||
return _user(row)
|
||||
|
||||
def get_credentials(self, username):
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT id, username, display_name, created_at, password_hash FROM users WHERE username = %s",
|
||||
(username,)).fetchone()
|
||||
if row is None:
|
||||
return None, None
|
||||
return _user(row), row["password_hash"]
|
||||
|
||||
# --- сессии ---
|
||||
def create_session(self, user_id, token_hash, ttl_seconds):
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"""INSERT INTO sessions (token_hash, user_id, created_at, expires_at)
|
||||
VALUES (%s, %s, now(), now() + make_interval(secs => %s))
|
||||
RETURNING expires_at""",
|
||||
(token_hash, user_id, ttl_seconds)).fetchone()
|
||||
return format_ts(row["expires_at"])
|
||||
|
||||
def get_session_user(self, token_hash):
|
||||
"""Пользователь действующей сессии или None (неизвестна/истекла/отозвана)."""
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"""SELECT u.id, u.username, u.display_name, u.created_at
|
||||
FROM sessions s JOIN users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = %s AND s.revoked_at IS NULL AND s.expires_at > now()""",
|
||||
(token_hash,)).fetchone()
|
||||
return _user(row) if row else None
|
||||
|
||||
def revoke_session(self, token_hash):
|
||||
with self.pool.connection() as conn:
|
||||
conn.execute(
|
||||
"UPDATE sessions SET revoked_at = now() WHERE token_hash = %s AND revoked_at IS NULL",
|
||||
(token_hash,))
|
||||
|
||||
# --- чаты ---
|
||||
def create_chat(self, title, member_ids):
|
||||
"""Чат и его участники создаются в одной транзакции (атомарно)."""
|
||||
chat_id = uuid.uuid4()
|
||||
with self.pool.connection() as conn:
|
||||
found = conn.execute(
|
||||
"SELECT count(*) AS n FROM users WHERE id = ANY(%s::uuid[])", (member_ids,)).fetchone()["n"]
|
||||
if found != len(member_ids):
|
||||
raise UnknownMember()
|
||||
conn.execute(
|
||||
"INSERT INTO chats (id, title, created_at) VALUES (%s, %s, clock_timestamp())",
|
||||
(chat_id, title))
|
||||
with conn.cursor() as cur:
|
||||
cur.executemany(
|
||||
"INSERT INTO chat_members (chat_id, user_id, position) VALUES (%s, %s, %s)",
|
||||
[(chat_id, m, i) for i, m in enumerate(member_ids)])
|
||||
row = conn.execute("SELECT " + CHAT_COLUMNS + " FROM chats c WHERE c.id = %s", (chat_id,)).fetchone()
|
||||
return _chat(row)
|
||||
|
||||
def get_chat_for(self, user_id, chat_id):
|
||||
"""Чат, если пользователь — участник; иначе None (чужой и несуществующий неразличимы)."""
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT " + CHAT_COLUMNS + """ FROM chats c
|
||||
WHERE c.id = %s AND EXISTS (
|
||||
SELECT 1 FROM chat_members m WHERE m.chat_id = c.id AND m.user_id = %s)""",
|
||||
(chat_id, user_id)).fetchone()
|
||||
return _chat(row) if row else None
|
||||
|
||||
def list_chats(self, user_id, after, limit):
|
||||
params = [user_id]
|
||||
where = ""
|
||||
if after:
|
||||
where = "AND (c.created_at, c.id) > (%s, %s::uuid)"
|
||||
params += [from_micros(after[0]), after[1]]
|
||||
params.append(limit + 1) # +1 запись: узнаём, есть ли следующая страница
|
||||
with self.pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT " + CHAT_COLUMNS + """ FROM chats c
|
||||
JOIN chat_members me ON me.chat_id = c.id AND me.user_id = %s
|
||||
WHERE true """ + where + " ORDER BY c.created_at, c.id LIMIT %s", params).fetchall()
|
||||
return self._page(rows, limit, _chat)
|
||||
|
||||
# --- сообщения ---
|
||||
def add_message(self, user_id, chat_id, text, attachment_ids, idem_key, request_hash, idem_ttl_seconds):
|
||||
"""Идемпотентная отправка. Возвращает (message, replayed) или None, если чата нет/он чужой.
|
||||
|
||||
Всё в ОДНОЙ транзакции: проверка доступа, поиск ключа, вставка сообщения и запись
|
||||
ключа. Либо фиксируется и сообщение, и ключ, либо ничего (транзиентная ошибка
|
||||
не запоминается как результат — клиент повторит с тем же ключом).
|
||||
Конкурентные запросы с одним ключом через разные реплики сериализуются
|
||||
блокировкой строки чата (FOR UPDATE), второй после COMMIT первого видит ключ.
|
||||
PK таблицы ключей — страховка: даже без блокировки дубль не зафиксируется.
|
||||
Lab4: в той же транзакции проверяется, что все attachment_ids — ready-вложения
|
||||
ЭТОГО чата (FOR SHARE: строка не исчезнет до COMMIT), и пишутся ссылки.
|
||||
"""
|
||||
with self.pool.connection() as conn:
|
||||
# FOR UPDATE по строке чата: вставки в один чат идут по очереди, поэтому
|
||||
# created_at растёт в порядке фиксации и keyset-курсор не пропускает записи.
|
||||
allowed = conn.execute(
|
||||
"""SELECT 1 FROM chats c WHERE c.id = %s AND EXISTS (
|
||||
SELECT 1 FROM chat_members m WHERE m.chat_id = c.id AND m.user_id = %s)
|
||||
FOR UPDATE OF c""", (chat_id, user_id)).fetchone()
|
||||
if allowed is None:
|
||||
return None
|
||||
existing = conn.execute(
|
||||
"""SELECT k.request_hash, k.expires_at > now() AS alive, """ + MESSAGE_COLUMNS + """
|
||||
FROM idempotency_keys k JOIN messages m ON m.id = k.message_id
|
||||
WHERE k.user_id = %s AND k.chat_id = %s AND k.idem_key = %s""",
|
||||
(user_id, chat_id, idem_key)).fetchone()
|
||||
if existing is not None:
|
||||
if existing["alive"]:
|
||||
if bytes(existing["request_hash"]) != request_hash:
|
||||
raise Conflict()
|
||||
return _message(existing), True
|
||||
# Ключ старше TTL (24 ч) — освобождаем его и обрабатываем как новый.
|
||||
conn.execute(
|
||||
"DELETE FROM idempotency_keys WHERE user_id = %s AND chat_id = %s AND idem_key = %s",
|
||||
(user_id, chat_id, idem_key))
|
||||
if attachment_ids:
|
||||
# Lab5: queued/processing/ready можно прикреплять; failed — 409;
|
||||
# pending (upload ещё не принят) — как неизвестное.
|
||||
found = conn.execute(
|
||||
"""SELECT id, status FROM attachments
|
||||
WHERE id = ANY(%s::uuid[]) AND chat_id = %s AND status <> 'pending'
|
||||
FOR SHARE""", (attachment_ids, chat_id)).fetchall()
|
||||
if len(found) != len(attachment_ids):
|
||||
# Чужой чат, неизвестный или непринятый id — одинаково 404.
|
||||
raise AttachmentNotFound()
|
||||
if any(r["status"] == "failed" for r in found):
|
||||
raise AttachmentFailed()
|
||||
row = conn.execute(
|
||||
"""INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES (%s, %s, %s, %s, clock_timestamp())
|
||||
RETURNING id, chat_id, sender_id, text, created_at""",
|
||||
(uuid.uuid4(), chat_id, user_id, text)).fetchone()
|
||||
if attachment_ids:
|
||||
with conn.cursor() as cur:
|
||||
cur.executemany(
|
||||
"""INSERT INTO message_attachments (message_id, attachment_id, position)
|
||||
VALUES (%s, %s, %s)""",
|
||||
[(row["id"], a, i) for i, a in enumerate(attachment_ids)])
|
||||
row = dict(row, attachment_ids=list(attachment_ids))
|
||||
conn.execute(
|
||||
"""INSERT INTO idempotency_keys (user_id, chat_id, idem_key, request_hash, message_id, expires_at)
|
||||
VALUES (%s, %s, %s, %s, %s, now() + make_interval(secs => %s))""",
|
||||
(user_id, chat_id, idem_key, request_hash, row["id"], idem_ttl_seconds))
|
||||
return _message(row), False
|
||||
|
||||
def list_messages(self, chat_id, after, limit):
|
||||
params = [chat_id]
|
||||
where = ""
|
||||
if after:
|
||||
where = "AND (m.created_at, m.id) > (%s, %s::uuid)"
|
||||
params += [from_micros(after[0]), after[1]]
|
||||
params.append(limit + 1)
|
||||
with self.pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT " + MESSAGE_COLUMNS + " FROM messages m WHERE m.chat_id = %s "
|
||||
+ where + " ORDER BY m.created_at, m.id LIMIT %s", params).fetchall()
|
||||
return self._page(rows, limit, _message)
|
||||
|
||||
# --- вложения ---
|
||||
def create_pending_attachment(self, att_id, chat_id, owner_id, filename, content_type,
|
||||
size_bytes, sha256, width, height, object_key, staging_key):
|
||||
"""Шаг 1: намерение фиксируется ДО PUT в staging (как в lab4). Строка pending
|
||||
API не показывает; брошенную (крах до постановки в очередь) убирает janitor."""
|
||||
with self.pool.connection() as conn:
|
||||
conn.execute(
|
||||
"""INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes,
|
||||
sha256, width, height, object_key, staging_key, status, created_at, updated_at)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, 'pending', now(), now())""",
|
||||
(att_id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||||
width, height, object_key, staging_key))
|
||||
|
||||
def enqueue_attachment(self, att_id, pipeline_version, max_attempts, before_commit=None):
|
||||
"""Шаг 3 (после PUT в staging): ОДНА транзакция pending -> queued + jobs + outbox.
|
||||
После COMMIT работа принята: даже если API сразу упадёт, relay опубликует задание.
|
||||
None — строку уже убрал janitor (ответ 503)."""
|
||||
with self.pool.connection() as conn:
|
||||
job_id = jobs.enqueue(conn, att_id, pipeline_version, max_attempts)
|
||||
if job_id is None:
|
||||
return None
|
||||
if before_commit:
|
||||
before_commit()
|
||||
row = conn.execute("SELECT " + ATTACHMENT_COLUMNS + " FROM attachments a WHERE a.id = %s",
|
||||
(att_id,)).fetchone()
|
||||
return _attachment(row)
|
||||
|
||||
def delete_pending_attachment(self, att_id):
|
||||
"""Компенсация: убрать непринятое намерение (staging-объект удалён/не создан)."""
|
||||
with self.pool.connection() as conn:
|
||||
conn.execute("DELETE FROM attachments WHERE id = %s AND status = 'pending'", (att_id,))
|
||||
|
||||
def get_attachment_for(self, user_id, att_id):
|
||||
"""(attachment, object_key) для участника чата; иначе None. Pending не виден."""
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT " + ATTACHMENT_COLUMNS + """ FROM attachments a
|
||||
WHERE a.id = %s AND a.status <> 'pending' AND EXISTS (
|
||||
SELECT 1 FROM chat_members m WHERE m.chat_id = a.chat_id AND m.user_id = %s)""",
|
||||
(att_id, user_id)).fetchone()
|
||||
return (_attachment(row), row["object_key"]) if row else None
|
||||
|
||||
def get_variant_key(self, att_id, name):
|
||||
"""object_key варианта текущей версии pipeline (или None)."""
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"""SELECT v.object_key FROM attachment_variants v JOIN attachments a ON a.id = v.attachment_id
|
||||
WHERE v.attachment_id = %s AND v.name = %s AND v.pipeline_version = a.pipeline_version""",
|
||||
(att_id, name)).fetchone()
|
||||
return row["object_key"] if row else None
|
||||
|
||||
@staticmethod
|
||||
def _page(rows, limit, convert):
|
||||
has_more = len(rows) > limit
|
||||
rows = rows[:limit]
|
||||
last = (to_micros(rows[-1]["created_at"]), str(rows[-1]["id"])) if rows and has_more else None
|
||||
return [convert(r) for r in rows], last
|
||||
@@ -0,0 +1,120 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Преобразование одного изображения в отдельном ПРОЦЕССЕ с жёсткими лимитами.
|
||||
|
||||
python transform.py <input> <output_dir> <content_type> <max_pixels>
|
||||
-> stdout: JSON {"variants": [...]} ; код выхода — класс ошибки.
|
||||
|
||||
Worker запускает его через subprocess с таймаутом JOB_TIMEOUT_SECONDS (wall clock), а сам
|
||||
процесс до импорта Pillow ограничивает себе адресное пространство (RLIMIT_AS) и CPU-время
|
||||
(RLIMIT_CPU). «Бомба», которую не поймали проверки заголовка, убивает только этот процесс,
|
||||
а не worker с его соединениями и арендами.
|
||||
|
||||
Коды выхода: 0 — успех; 3 — invalid_image; 4 — image_too_large; 5 — resource_limit
|
||||
(MemoryError). Убит сигналом (SIGXCPU/SIGKILL) -> resource_limit; таймаут — решает worker.
|
||||
|
||||
Варианты (contracts/README.md, «Фоновая обработка»):
|
||||
thumbnail — JPEG q=85, вписан в 256x256 с сохранением пропорций, без увеличения;
|
||||
размеры считаются целочисленно с округлением вниз, минимум 1 px
|
||||
(320x200 -> 256x160); EXIF orientation применяется; alpha -> на белый фон;
|
||||
crop — JPEG q=85, центрированный квадрат 128x128 (маленькие исходники увеличиваются);
|
||||
optimized — WebP q=80 method=4, вписан в 1280x1280 без увеличения; alpha сохраняется.
|
||||
Во все варианты НЕ переносятся EXIF/XMP/ICC/комментарии: Pillow пишет метаданные только
|
||||
если их явно передать (exif=, icc_profile=), мы их не передаём. Цвет считается sRGB.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import resource
|
||||
import sys
|
||||
|
||||
MEMORY_LIMIT_MB = int(os.environ.get("TRANSFORM_MEMORY_LIMIT_MB", "768"))
|
||||
CPU_LIMIT_SECONDS = int(os.environ.get("TRANSFORM_CPU_SECONDS", "30"))
|
||||
THUMB = 256
|
||||
CROP = 128
|
||||
OPTIMIZED = 1280
|
||||
JPEG_QUALITY = 85
|
||||
WEBP_QUALITY = 80
|
||||
EXIT_INVALID, EXIT_TOO_LARGE, EXIT_RESOURCE = 3, 4, 5
|
||||
|
||||
|
||||
def fit_within(w, h, box):
|
||||
"""Вписать (w, h) в box x box без увеличения; целочисленно, вниз, минимум 1."""
|
||||
if w <= box and h <= box:
|
||||
return w, h
|
||||
if w >= h:
|
||||
return box, max(1, h * box // w)
|
||||
return max(1, w * box // h), box
|
||||
|
||||
|
||||
def fail(code, error, detail=""):
|
||||
print(json.dumps({"error": error, "detail": detail[:200]}))
|
||||
sys.stdout.flush()
|
||||
os._exit(code)
|
||||
|
||||
|
||||
def main():
|
||||
src, out_dir, content_type, max_pixels = sys.argv[1], sys.argv[2], sys.argv[3], int(sys.argv[4])
|
||||
limit = MEMORY_LIMIT_MB * 1024 * 1024
|
||||
resource.setrlimit(resource.RLIMIT_AS, (limit, limit))
|
||||
resource.setrlimit(resource.RLIMIT_CPU, (CPU_LIMIT_SECONDS, CPU_LIMIT_SECONDS + 1))
|
||||
|
||||
import warnings
|
||||
from PIL import Image, ImageOps
|
||||
# Больше max_pixels — ошибка, а не предупреждение (по умолчанию Pillow только warn до 2x).
|
||||
Image.MAX_IMAGE_PIXELS = max_pixels
|
||||
warnings.simplefilter("error", Image.DecompressionBombWarning)
|
||||
fmt = {"image/png": "PNG", "image/jpeg": "JPEG"}.get(content_type)
|
||||
if fmt is None:
|
||||
fail(EXIT_INVALID, "invalid_image", "unsupported content type")
|
||||
try:
|
||||
im = Image.open(src, formats=(fmt,))
|
||||
w0, h0 = im.size
|
||||
if w0 * h0 > max_pixels:
|
||||
fail(EXIT_TOO_LARGE, "image_too_large", "%dx%d" % (w0, h0))
|
||||
orientation = im.getexif().get(0x0112, 1)
|
||||
swap = orientation in (5, 6, 7, 8)
|
||||
ow, oh = (h0, w0) if swap else (w0, h0) # размеры ПОСЛЕ применения EXIF orientation
|
||||
if fmt == "JPEG":
|
||||
# draft: декодер JPEG сразу уменьшает в 2/4/8 раз, но не меньше 1280 по обеим
|
||||
# сторонам — памяти нужно в 4–64 раза меньше, качество вариантов не страдает.
|
||||
im.draft("RGB", (OPTIMIZED, OPTIMIZED))
|
||||
im.load()
|
||||
if orientation in range(2, 9):
|
||||
im = ImageOps.exif_transpose(im)
|
||||
has_alpha = im.mode in ("RGBA", "LA", "PA") or (im.mode == "P" and "transparency" in im.info)
|
||||
work = im.convert("RGBA") if has_alpha else im.convert("RGB")
|
||||
del im
|
||||
# Промежуточная копия <= 1280: из неё делаются все варианты (экономия памяти и CPU).
|
||||
mw, mh = fit_within(ow, oh, OPTIMIZED)
|
||||
if work.size != (mw, mh):
|
||||
work = work.resize((mw, mh), Image.LANCZOS, reducing_gap=3.0)
|
||||
if has_alpha:
|
||||
flat = Image.new("RGB", work.size, (255, 255, 255))
|
||||
flat.paste(work, mask=work.getchannel("A"))
|
||||
else:
|
||||
flat = work
|
||||
variants = []
|
||||
tw, th = fit_within(ow, oh, THUMB)
|
||||
thumb = flat if flat.size == (tw, th) else flat.resize((tw, th), Image.LANCZOS)
|
||||
path = os.path.join(out_dir, "thumbnail.jpg")
|
||||
thumb.save(path, "JPEG", quality=JPEG_QUALITY, optimize=True)
|
||||
variants.append({"name": "thumbnail", "path": path, "content_type": "image/jpeg", "width": tw, "height": th})
|
||||
crop = ImageOps.fit(flat, (CROP, CROP), method=Image.LANCZOS, centering=(0.5, 0.5))
|
||||
path = os.path.join(out_dir, "crop.jpg")
|
||||
crop.save(path, "JPEG", quality=JPEG_QUALITY, optimize=True)
|
||||
variants.append({"name": "crop", "path": path, "content_type": "image/jpeg", "width": CROP, "height": CROP})
|
||||
path = os.path.join(out_dir, "optimized.webp")
|
||||
work.save(path, "WEBP", quality=WEBP_QUALITY, method=4)
|
||||
variants.append({"name": "optimized", "path": path, "content_type": "image/webp", "width": mw, "height": mh})
|
||||
except MemoryError:
|
||||
fail(EXIT_RESOURCE, "resource_limit", "memory limit %d MiB" % MEMORY_LIMIT_MB)
|
||||
except (Image.DecompressionBombError, Image.DecompressionBombWarning) as exc:
|
||||
fail(EXIT_TOO_LARGE, "image_too_large", type(exc).__name__)
|
||||
except Exception as exc:
|
||||
# Битые/усечённые данные: OSError, SyntaxError, ValueError, struct.error...
|
||||
fail(EXIT_INVALID, "invalid_image", type(exc).__name__)
|
||||
print(json.dumps({"variants": variants, "source": [ow, oh]}))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
+431
@@ -0,0 +1,431 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Worker обработки вложений (compose-сервис `worker`, отдельный процесс от API).
|
||||
|
||||
WORKER_CONCURRENCY потоков-потребителей; у каждого своё соединение AMQP, prefetch=1
|
||||
(не больше одного неподтверждённого сообщения на поток) и своё соединение PostgreSQL.
|
||||
Итого одновременно в работе не больше WORKER_CONCURRENCY заданий на контейнер.
|
||||
|
||||
Обработка одного сообщения (at-least-once, ack только после устойчивого эффекта):
|
||||
1. разбор по jobs.schema.json; мусор -> basic.reject(requeue=False) -> DLQ;
|
||||
2. claim в транзакции (src/jobs.py): по строке jobs решаем, нужна ли работа. ready/failed,
|
||||
чужая живая аренда, ранний дубль -> ack без работы. Иначе processing, attempt+1,
|
||||
lease_token (fencing) и lease_until, COMMIT;
|
||||
3. пока идёт работа, отдельный поток продлевает аренду (heartbeat) не дольше
|
||||
JOB_TIMEOUT_SECONDS: зависший процесс аренду теряет, долгий, но живой — нет;
|
||||
4. staging -> временный файл (лимит байт = size_bytes из БД, проверка SHA-256);
|
||||
5. transform.py в подпроцессе (RLIMIT_AS, RLIMIT_CPU, таймаут) -> thumbnail/crop/optimized;
|
||||
6. PUT оригинала и вариантов по ДЕТЕРМИНИРОВАННЫМ ключам attachments/<id>/v<ver>/<name>:
|
||||
повтор перезаписывает те же объекты, второго набора не появляется;
|
||||
7. complete: processing -> ready + attachment_variants одной транзакцией и только со своим
|
||||
lease_token; иначе (аренду забрали) — ничего не пишем;
|
||||
8. удаление staging (после COMMIT), затем ack. Крах до ack -> redelivery -> claim видит
|
||||
ready -> no-op ack.
|
||||
Ошибки: постоянные -> failed(error_code); временные -> queued с backoff+jitter через outbox
|
||||
(relay опубликует в срок) или failed(retry_exhausted). Нет доступа к БД -> сообщение
|
||||
возвращается в очередь (nack) после паузы; если так и не записалось — reaper/redrive.
|
||||
|
||||
Учебные отказы (WORKER_FAULT_INJECTION=1): filename вида fault-<point>.png задаёт точку:
|
||||
crash-after-claim, crash-after-s3-put, crash-after-commit (os._exit один раз на job),
|
||||
transient-<N> (временная ошибка в первых N попытках), transient-always (до replay),
|
||||
slow (пауза FAULT_SLOW_SECONDS после claim, аренда продлевается).
|
||||
"""
|
||||
import concurrent.futures
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
import common
|
||||
import jobs
|
||||
import objstore
|
||||
from objstore import ObjectMissing, StorageUnavailable
|
||||
|
||||
log = logging.getLogger("worker")
|
||||
CONCURRENCY = common.env_int("WORKER_CONCURRENCY", 2)
|
||||
PREFETCH = common.env_int("WORKER_PREFETCH", 1)
|
||||
LEASE_SECONDS = common.env_int("JOB_LEASE_SECONDS", 30)
|
||||
JOB_TIMEOUT = common.env_float("JOB_TIMEOUT_SECONDS", 60)
|
||||
RETRY_BASE = common.env_float("JOB_RETRY_BASE_SECONDS", 2)
|
||||
RETRY_MAX = common.env_float("JOB_RETRY_MAX_SECONDS", 60)
|
||||
MAX_UPLOAD_BYTES = common.env_int("MAX_UPLOAD_BYTES", 10485760)
|
||||
MAX_IMAGE_PIXELS = common.env_int("MAX_IMAGE_PIXELS", 40000000)
|
||||
REQUEUE_PAUSE = common.env_float("WORKER_REQUEUE_PAUSE_SECONDS", 2)
|
||||
WORK_DIR = os.environ.get("WORKER_TMP_DIR") or None
|
||||
FAULT_INJECTION = os.environ.get("WORKER_FAULT_INJECTION", "0") == "1"
|
||||
FAULT_SLOW_SECONDS = common.env_float("FAULT_SLOW_SECONDS", 20)
|
||||
TRANSFORM = os.path.join(os.path.dirname(os.path.abspath(__file__)), "transform.py")
|
||||
HEARTBEAT = "/tmp/worker.heartbeat"
|
||||
EXT = {"image/jpeg": "jpg", "image/webp": "webp", "image/png": "png"}
|
||||
TRANSFORM_ERRORS = {3: "invalid_image", 4: "image_too_large", 5: "resource_limit"}
|
||||
|
||||
OBJ = objstore.ObjectStore(objstore.make_client(), os.environ.get("S3_BUCKET", "messenger-attachments"))
|
||||
STOP = threading.Event()
|
||||
|
||||
|
||||
class JobError(Exception):
|
||||
def __init__(self, code, detail=""):
|
||||
super().__init__(code)
|
||||
self.code = code
|
||||
self.detail = detail
|
||||
|
||||
|
||||
class LeaseLost(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class Lease:
|
||||
"""Продление аренды отдельным соединением раз в LEASE_SECONDS/3, но не дольше
|
||||
JOB_TIMEOUT_SECONDS (+запас на загрузку в S3) от начала: после этого аренда истекает
|
||||
и reaper вернёт задание в очередь, даже если процесс жив, но завис."""
|
||||
|
||||
def __init__(self, conninfo, job):
|
||||
self.conninfo = conninfo
|
||||
self.job = job
|
||||
self.lost = False
|
||||
self.deadline = time.monotonic() + JOB_TIMEOUT + 30
|
||||
self._stop = threading.Event()
|
||||
self._thread = threading.Thread(target=self._loop, daemon=True)
|
||||
|
||||
def __enter__(self):
|
||||
self._thread.start()
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
self._stop.set()
|
||||
self._thread.join(timeout=5)
|
||||
|
||||
def check(self, conn=None):
|
||||
"""Перед каждым побочным эффектом: флаг фонового heartbeat И синхронная проверка
|
||||
(продление) аренды в БД. Иначе замороженный процесс после разморозки успел бы
|
||||
сделать шаг до того, как фоновый поток заметит потерю аренды."""
|
||||
if self.lost:
|
||||
raise LeaseLost()
|
||||
if conn is not None:
|
||||
with conn.transaction():
|
||||
ok = jobs.heartbeat(conn, self.job["job_id"], self.job["lease_token"], LEASE_SECONDS)
|
||||
if not ok:
|
||||
self.lost = True
|
||||
raise LeaseLost()
|
||||
|
||||
def _loop(self):
|
||||
conn = None
|
||||
while not self._stop.wait(max(1.0, LEASE_SECONDS / 3)):
|
||||
if time.monotonic() > self.deadline:
|
||||
log.warning("job %s exceeded hard deadline, lease is no longer renewed", self.job["job_id"])
|
||||
return
|
||||
try:
|
||||
if conn is None or conn.closed:
|
||||
conn = psycopg.connect(self.conninfo, autocommit=True)
|
||||
if not jobs.heartbeat(conn, self.job["job_id"], self.job["lease_token"], LEASE_SECONDS):
|
||||
self.lost = True
|
||||
log.warning("lease lost for job %s", self.job["job_id"])
|
||||
return
|
||||
except psycopg.Error as exc:
|
||||
log.warning("lease heartbeat failed (%s)", type(exc).__name__)
|
||||
conn = None
|
||||
if conn is not None:
|
||||
conn.close()
|
||||
|
||||
|
||||
def sha256_file(path):
|
||||
h = hashlib.sha256()
|
||||
with open(path, "rb") as f:
|
||||
for chunk in iter(lambda: f.read(1024 * 1024), b""):
|
||||
h.update(chunk)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
class Consumer(threading.Thread):
|
||||
def __init__(self, index):
|
||||
super().__init__(name="consumer-%d" % index, daemon=True)
|
||||
self.conninfo = common.database_conninfo()
|
||||
self.db = None
|
||||
self.last_beat = time.monotonic()
|
||||
self.pool = concurrent.futures.ThreadPoolExecutor(max_workers=1)
|
||||
|
||||
# ------------------------------------------------------------------ AMQP
|
||||
def run(self):
|
||||
while not STOP.is_set():
|
||||
conn = common.connect_broker(log, STOP)
|
||||
if conn is None:
|
||||
return
|
||||
try:
|
||||
ch = conn.channel()
|
||||
ch.basic_qos(prefetch_count=PREFETCH)
|
||||
log.info("%s consuming %s owner=%s", self.name, common.QUEUE, common.OWNER)
|
||||
for method, _props, body in ch.consume(common.QUEUE, inactivity_timeout=1):
|
||||
self.last_beat = time.monotonic()
|
||||
if STOP.is_set():
|
||||
break
|
||||
if method is None:
|
||||
continue
|
||||
outcome = self.run_job(conn, body)
|
||||
if outcome == "ack":
|
||||
ch.basic_ack(method.delivery_tag)
|
||||
elif outcome == "reject":
|
||||
ch.basic_reject(method.delivery_tag, requeue=False) # -> DLX -> DLQ
|
||||
else:
|
||||
self.pause(conn, REQUEUE_PAUSE)
|
||||
ch.basic_nack(method.delivery_tag, requeue=True)
|
||||
ch.cancel()
|
||||
conn.close()
|
||||
except Exception as exc:
|
||||
log.warning("%s broker loop error (%s), reconnecting", self.name, type(exc).__name__)
|
||||
try:
|
||||
conn.close()
|
||||
except Exception:
|
||||
pass
|
||||
STOP.wait(1)
|
||||
|
||||
def pause(self, conn, seconds):
|
||||
end = time.monotonic() + seconds
|
||||
while time.monotonic() < end:
|
||||
conn.process_data_events(time_limit=min(0.5, end - time.monotonic()))
|
||||
self.last_beat = time.monotonic()
|
||||
|
||||
def run_job(self, conn, body):
|
||||
"""Работа в отдельном потоке; этот поток обслуживает heartbeat AMQP-соединения."""
|
||||
future = self.pool.submit(self.process_message, body)
|
||||
while not future.done():
|
||||
conn.process_data_events(time_limit=0.5)
|
||||
self.last_beat = time.monotonic()
|
||||
try:
|
||||
return future.result()
|
||||
except Exception:
|
||||
log.exception("unexpected worker error")
|
||||
return "requeue"
|
||||
|
||||
# ------------------------------------------------------------------ DB
|
||||
def database(self):
|
||||
if self.db is None or self.db.closed:
|
||||
self.db = psycopg.connect(self.conninfo, row_factory=dict_row)
|
||||
return self.db
|
||||
|
||||
def drop_db(self):
|
||||
try:
|
||||
if self.db is not None:
|
||||
self.db.close()
|
||||
except Exception:
|
||||
pass
|
||||
self.db = None
|
||||
|
||||
# ------------------------------------------------------------------ job
|
||||
def process_message(self, body):
|
||||
try:
|
||||
msg = jobs.parse_message(body)
|
||||
except jobs.InvalidMessage as exc:
|
||||
log.warning("invalid message rejected to DLQ (%s)", exc)
|
||||
return "reject"
|
||||
try:
|
||||
db = self.database()
|
||||
with db.transaction():
|
||||
action, job = jobs.claim(db, msg, common.OWNER, LEASE_SECONDS)
|
||||
except psycopg.Error as exc:
|
||||
log.warning("claim failed, message requeued (%s)", type(exc).__name__)
|
||||
self.drop_db()
|
||||
return "requeue"
|
||||
if action == "reject":
|
||||
log.warning("message for job %s rejected to DLQ (%s)", msg["job_id"], job)
|
||||
return "reject"
|
||||
if action == "ack":
|
||||
return "ack"
|
||||
log.info("job %s attempt %d claimed (attachment %s)", job["job_id"], job["attempt"], job["attachment_id"])
|
||||
try:
|
||||
return self.execute(db, job)
|
||||
except psycopg.Error as exc:
|
||||
# Результат не записан; аренда истечёт, reaper вернёт задание. Сообщение — назад.
|
||||
log.warning("database error during job %s (%s)", job["job_id"], type(exc).__name__)
|
||||
self.drop_db()
|
||||
return "requeue"
|
||||
|
||||
def fault_point(self, job):
|
||||
if not FAULT_INJECTION:
|
||||
return None
|
||||
name = job["filename"] or ""
|
||||
if not name.startswith("fault-"):
|
||||
return None
|
||||
return name[len("fault-"):].rsplit(".", 1)[0]
|
||||
|
||||
def crash_once(self, db, job, point, wanted):
|
||||
if point != wanted:
|
||||
return
|
||||
with db.transaction():
|
||||
seen = db.execute(
|
||||
"""SELECT 1 FROM job_events WHERE job_id = %s AND event = 'fault_injected'
|
||||
AND detail->>'point' = %s""", (job["job_id"], point)).fetchone()
|
||||
if seen:
|
||||
return
|
||||
jobs.add_event(db, job["job_id"], "fault_injected", job["attempt"], common.OWNER, {"point": point})
|
||||
log.warning("FAULT INJECTION %s job=%s: process exits now", point, job["job_id"])
|
||||
os._exit(86)
|
||||
|
||||
def execute(self, db, job):
|
||||
point = self.fault_point(job)
|
||||
started = time.monotonic()
|
||||
with Lease(self.conninfo, job) as lease:
|
||||
try:
|
||||
self.crash_once(db, job, point, "crash-after-claim")
|
||||
if point == "slow" and job["attempt"] == 1:
|
||||
log.warning("FAULT INJECTION slow job=%s sleeping %.0fs", job["job_id"], FAULT_SLOW_SECONDS)
|
||||
time.sleep(FAULT_SLOW_SECONDS)
|
||||
if point and point.startswith("transient-"):
|
||||
n = point.split("-", 1)[1]
|
||||
if (n == "always" and job["replay_count"] == 0) or (n.isdigit() and job["attempt"] <= int(n)):
|
||||
raise JobError("storage_unavailable", "injected transient error")
|
||||
lease.check(db)
|
||||
variants = self.do_work(db, job, lease, started)
|
||||
self.crash_once(db, job, point, "crash-after-s3-put")
|
||||
lease.check(db)
|
||||
except LeaseLost:
|
||||
with db.transaction():
|
||||
jobs.add_event(db, job["job_id"], "aborted_lease_lost", job["attempt"], common.OWNER)
|
||||
return "ack"
|
||||
except JobError as err:
|
||||
with db.transaction():
|
||||
result, delay = jobs.fail_or_retry(db, job, err.code, err.detail, common.OWNER,
|
||||
RETRY_BASE, RETRY_MAX)
|
||||
log.warning("job %s attempt %d: %s (%s) -> %s%s", job["job_id"], job["attempt"], err.code,
|
||||
err.detail, result, " in %.1fs" % delay if delay else "")
|
||||
return "ack"
|
||||
with db.transaction():
|
||||
result = jobs.complete(db, job, variants, common.OWNER)
|
||||
self.crash_once(db, job, point, "crash-after-commit")
|
||||
log.info("job %s attempt %d -> %s in %.0fms", job["job_id"], job["attempt"], result,
|
||||
(time.monotonic() - started) * 1000)
|
||||
if result == "ready":
|
||||
self.cleanup_staging(db, job)
|
||||
return "ack"
|
||||
|
||||
def cleanup_staging(self, db, job):
|
||||
"""Staging удаляется только после COMMIT ready. Не вышло — доберёт janitor."""
|
||||
key = job["staging_key"]
|
||||
if not key:
|
||||
return
|
||||
try:
|
||||
OBJ.delete(key)
|
||||
except StorageUnavailable:
|
||||
log.warning("staging cleanup postponed for %s", job["attachment_id"])
|
||||
return
|
||||
with db.transaction():
|
||||
db.execute("UPDATE attachments SET staging_key = NULL WHERE id = %s AND status = 'ready'",
|
||||
(job["attachment_id"],))
|
||||
jobs.add_event(db, job["job_id"], "staging_deleted", job["attempt"], common.OWNER)
|
||||
|
||||
def do_work(self, db, job, lease, started):
|
||||
tmpdir = tempfile.mkdtemp(prefix="job-", dir=WORK_DIR)
|
||||
try:
|
||||
src = os.path.join(tmpdir, "source")
|
||||
self.fetch_staging(job, src)
|
||||
lease.check(db)
|
||||
produced = self.transform(job, src, tmpdir, started)
|
||||
lease.check(db) # последняя проверка перед записью в конечный prefix
|
||||
ver = job["pipeline_version"]
|
||||
base = "attachments/%s/v%d/" % (job["attachment_id"], ver)
|
||||
if job["object_key"] != base + "original":
|
||||
raise JobError("staging_corrupted", "unexpected object key")
|
||||
variants = []
|
||||
for v in produced:
|
||||
path = v["path"]
|
||||
variants.append({"name": v["name"], "key": base + "%s.%s" % (v["name"], EXT[v["content_type"]]),
|
||||
"content_type": v["content_type"], "width": v["width"], "height": v["height"],
|
||||
"size_bytes": os.path.getsize(path), "sha256": sha256_file(path), "path": path})
|
||||
try:
|
||||
# Сначала все объекты, потом COMMIT в БД: ready никогда не ссылается на
|
||||
# отсутствующий объект. Ключи детерминированы — повтор перезаписывает их же.
|
||||
with open(src, "rb") as f:
|
||||
OBJ.put(job["object_key"], f, job["size_bytes"], job["content_type"])
|
||||
for v in variants:
|
||||
with open(v["path"], "rb") as f:
|
||||
OBJ.put(v["key"], f, v["size_bytes"], v["content_type"])
|
||||
except StorageUnavailable:
|
||||
raise JobError("storage_unavailable", "put result")
|
||||
return variants
|
||||
finally:
|
||||
shutil.rmtree(tmpdir, ignore_errors=True)
|
||||
|
||||
def fetch_staging(self, job, path):
|
||||
key = job["staging_key"]
|
||||
if not key:
|
||||
raise JobError("staging_missing", "staging already removed")
|
||||
limit = min(job["size_bytes"], MAX_UPLOAD_BYTES)
|
||||
try:
|
||||
resp = OBJ.open(key)
|
||||
except ObjectMissing:
|
||||
raise JobError("staging_missing", "no staging object")
|
||||
except StorageUnavailable:
|
||||
raise JobError("storage_unavailable", "get staging")
|
||||
h = hashlib.sha256()
|
||||
size = 0
|
||||
try:
|
||||
with open(path, "wb") as f:
|
||||
for chunk in resp.stream(objstore.STREAM_CHUNK):
|
||||
size += len(chunk)
|
||||
if size > limit:
|
||||
raise JobError("staging_corrupted", "staging larger than metadata")
|
||||
h.update(chunk)
|
||||
f.write(chunk)
|
||||
except JobError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise JobError("storage_unavailable", "read staging: %s" % type(exc).__name__)
|
||||
finally:
|
||||
resp.close()
|
||||
resp.release_conn()
|
||||
if size != job["size_bytes"] or h.hexdigest() != job["sha256"]:
|
||||
raise JobError("staging_corrupted", "size/sha256 differ from accepted upload")
|
||||
|
||||
def transform(self, job, src, tmpdir, started):
|
||||
out = os.path.join(tmpdir, "out")
|
||||
os.mkdir(out)
|
||||
left = max(1.0, JOB_TIMEOUT - (time.monotonic() - started))
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
[sys.executable, TRANSFORM, src, out, job["content_type"], str(MAX_IMAGE_PIXELS)],
|
||||
capture_output=True, timeout=left, check=False)
|
||||
except subprocess.TimeoutExpired:
|
||||
raise JobError("processing_timeout", "transform exceeded %.0fs" % left)
|
||||
if proc.returncode < 0:
|
||||
raise JobError("resource_limit", "transform killed by signal %d" % -proc.returncode)
|
||||
if proc.returncode in TRANSFORM_ERRORS:
|
||||
raise JobError(TRANSFORM_ERRORS[proc.returncode], proc.stdout.decode(errors="replace")[:200])
|
||||
if proc.returncode != 0:
|
||||
raise JobError("processing_failed", "transform exit %d" % proc.returncode)
|
||||
result = json.loads(proc.stdout)
|
||||
names = sorted(v["name"] for v in result["variants"])
|
||||
if names != sorted(jobs.VARIANT_NAMES):
|
||||
raise JobError("processing_failed", "unexpected variants")
|
||||
return result["variants"]
|
||||
|
||||
|
||||
def main():
|
||||
signal.signal(signal.SIGTERM, lambda *_: STOP.set())
|
||||
signal.signal(signal.SIGINT, lambda *_: STOP.set())
|
||||
log.info("worker starting owner=%s concurrency=%d prefetch=%d lease=%ds timeout=%.0fs fault_injection=%s",
|
||||
common.OWNER, CONCURRENCY, PREFETCH, LEASE_SECONDS, JOB_TIMEOUT, FAULT_INJECTION)
|
||||
consumers = [Consumer(i) for i in range(CONCURRENCY)]
|
||||
for c in consumers:
|
||||
c.start()
|
||||
while not STOP.is_set():
|
||||
# healthcheck: файл обновляется, только пока все потребители живы и не зависли.
|
||||
if all(c.is_alive() and time.monotonic() - c.last_beat < 30 for c in consumers):
|
||||
common.touch(HEARTBEAT)
|
||||
STOP.wait(2)
|
||||
log.info("SIGTERM: finishing in-flight jobs")
|
||||
for c in consumers:
|
||||
c.join(timeout=JOB_TIMEOUT + 30)
|
||||
log.info("worker stopped")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user