Аудит F01, F11, F12, F13: гонка janitor/replay, версия pipeline, схема сообщения, срок задания
- F01: janitor под блокировкой jobs+attachments перепроверяет условие, снимает staging_key и только после COMMIT удаляет объект; replay перечитывает staging_key отдельным запросом под блокировкой вложения (в READ COMMITTED соединённые колонки могли остаться из старого снимка); тест трёх порядков, включая чередование из аудита (учебная пауза JANITOR_PAUSE_AFTER_SELECT_SECONDS) - F11: pipeline_version пишется при создании вложения; API не стартует с неподдерживаемой версией - F12: строгий разбор по jobs.schema.json (bool, RFC 3339, traceparent, tracestate); 17 случаев совпадают с jsonschema Draft 2020-12 - F13: единый срок задания на чтение staging, transform и запись; после срока аренда не продлевается, работа прерывается как processing_timeout
This commit is contained in:
+40
-13
@@ -21,9 +21,12 @@ worker берёт доверенные storage metadata из БД.
|
||||
import datetime as dt
|
||||
import json
|
||||
import random
|
||||
import re
|
||||
import uuid
|
||||
|
||||
SCHEMA_VERSION = 1
|
||||
# Аудит F11: публикация результата и выборка вариантов согласованы только для v1.
|
||||
SUPPORTED_PIPELINE_VERSIONS = (1,)
|
||||
JOB_TYPE = "attachment.process.v1"
|
||||
VARIANT_NAMES = ("thumbnail", "crop", "optimized")
|
||||
# Постоянные ошибки: повтор не поможет (тот же вход даст тот же результат).
|
||||
@@ -54,8 +57,22 @@ def make_payload(job_id, attachment_id, pipeline_version, attempt, created_at=No
|
||||
}
|
||||
|
||||
|
||||
_UUID_RE = re.compile(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")
|
||||
# RFC 3339 date-time: обязательно время и зона (Z или ±hh:mm).
|
||||
_DATETIME_RE = re.compile(r"^\d{4}-\d{2}-\d{2}[Tt]\d{2}:\d{2}:\d{2}(\.\d+)?([Zz]|[+-]\d{2}:\d{2})$")
|
||||
_TRACEPARENT_RE = re.compile(r"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$")
|
||||
|
||||
|
||||
def _strict_int(v):
|
||||
# В Python True == 1 и isinstance(True, int): bool исключается явно (аудит F12).
|
||||
# По JSON Schema 2020-12 integer — число с нулевой дробной частью: 1.0 тоже допустимо.
|
||||
return type(v) is int or (type(v) is float and v.is_integer())
|
||||
|
||||
|
||||
def parse_message(body):
|
||||
"""bytes -> dict по jobs.schema.json (без внешних библиотек). Иначе InvalidMessage."""
|
||||
"""bytes -> dict строго по jobs.schema.json (без внешних библиотек). Иначе InvalidMessage.
|
||||
Аудит F12: раньше проходили schema_version=true, created_at без времени, traceparent-число
|
||||
и tracestate длиннее 512. Соответствие сверяется с jsonschema тестом job_schema_check.py."""
|
||||
try:
|
||||
msg = json.loads(body.decode("utf-8"))
|
||||
except (UnicodeDecodeError, ValueError):
|
||||
@@ -67,25 +84,29 @@ def parse_message(body):
|
||||
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")
|
||||
if not _strict_int(msg["schema_version"]) or msg["schema_version"] != SCHEMA_VERSION:
|
||||
raise InvalidMessage("unsupported schema_version")
|
||||
if msg["type"] != JOB_TYPE:
|
||||
raise InvalidMessage("unsupported type")
|
||||
for field in _UUID_FIELDS:
|
||||
try:
|
||||
if not isinstance(msg[field], str):
|
||||
raise ValueError
|
||||
uuid.UUID(msg[field])
|
||||
except ValueError:
|
||||
if not isinstance(msg[field], str) or not _UUID_RE.match(msg[field]):
|
||||
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:
|
||||
if not _strict_int(msg[field]) or msg[field] < 1:
|
||||
raise InvalidMessage("bad " + field)
|
||||
if not isinstance(msg["created_at"], str):
|
||||
created = msg["created_at"]
|
||||
if not isinstance(created, str) or not _DATETIME_RE.match(created):
|
||||
raise InvalidMessage("bad created_at")
|
||||
try:
|
||||
dt.datetime.fromisoformat(msg["created_at"].replace("Z", "+00:00"))
|
||||
dt.datetime.fromisoformat(created.upper().replace("Z", "+00:00"))
|
||||
except ValueError:
|
||||
raise InvalidMessage("bad created_at")
|
||||
if "traceparent" in msg and (not isinstance(msg["traceparent"], str) or not _TRACEPARENT_RE.match(msg["traceparent"])):
|
||||
raise InvalidMessage("bad traceparent")
|
||||
if "tracestate" in msg and (not isinstance(msg["tracestate"], str) or len(msg["tracestate"]) > 512):
|
||||
raise InvalidMessage("bad tracestate")
|
||||
for field in ("schema_version", "pipeline_version", "attempt"):
|
||||
msg[field] = int(msg[field]) # 1.0 -> 1
|
||||
return msg
|
||||
|
||||
|
||||
@@ -348,7 +369,13 @@ def replay(conn, attachment_id, actor, extra_attempts, reason, dry_run=False):
|
||||
return "not_found", None
|
||||
if job["job_status"] != "failed":
|
||||
return "refused_status_" + job["job_status"], job
|
||||
if job["staging_key"] is None:
|
||||
# Аудит F01: staging_key перечитывается ОТДЕЛЬНЫМ запросом под блокировкой строки вложения.
|
||||
# В READ COMMITTED «SELECT ... FOR UPDATE OF j» после ожидания блокировки перечитывает только
|
||||
# строку jobs, а колонки attachments из соединения могли остаться из старого снимка — и replay
|
||||
# принял бы работу, исходник которой janitor уже освободил.
|
||||
att = conn.execute("SELECT staging_key FROM attachments WHERE id = %s FOR UPDATE",
|
||||
(job["attachment_id"],)).fetchone()
|
||||
if att["staging_key"] is None:
|
||||
return "refused_staging_expired", job
|
||||
if dry_run:
|
||||
return "would_replay", job
|
||||
|
||||
Reference in New Issue
Block a user