forked from mtusi2026/mtusi2026lab5
- 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
99 lines
4.5 KiB
Python
99 lines
4.5 KiB
Python
#!/usr/bin/env python3
|
||
"""Аудит F12 и F11: разбор сообщения брокера = contracts/jobs.schema.json; версия pipeline.
|
||
|
||
python3 -m venv .venv && .venv/bin/pip install -r requirements-dev.txt rfc3339-validator
|
||
.venv/bin/python student-tests/queue_contract_check.py --output evidence/queue-contract-check.json
|
||
|
||
F12: набор сообщений (валидные и контрпримеры из аудита) проверяется src/jobs.parse_message
|
||
и jsonschema Draft 2020-12 с FormatChecker (date-time, uuid). Вердикты должны совпасть.
|
||
F11: API с PIPELINE_VERSION=2 не стартует (понятная ошибка), а не работает «молча» неверно.
|
||
"""
|
||
import argparse
|
||
import copy
|
||
import json
|
||
import subprocess
|
||
import sys
|
||
from pathlib import Path
|
||
|
||
ROOT = Path(__file__).resolve().parents[1]
|
||
sys.path.insert(0, str(ROOT / "src"))
|
||
import jobs # noqa: E402
|
||
from jsonschema import Draft202012Validator, FormatChecker # noqa: E402
|
||
|
||
BASE = {"schema_version": 1, "job_id": "11111111-1111-4111-8111-111111111111", "type": "attachment.process.v1",
|
||
"attachment_id": "22222222-2222-4222-8222-222222222222", "pipeline_version": 1, "attempt": 1,
|
||
"created_at": "2026-09-01T12:00:00Z"}
|
||
|
||
|
||
def variant(**kw):
|
||
m = copy.deepcopy(BASE)
|
||
for k, v in kw.items():
|
||
if v is None:
|
||
m.pop(k, None)
|
||
else:
|
||
m[k] = v
|
||
return m
|
||
|
||
|
||
CASES = {
|
||
"valid minimal": variant(),
|
||
"valid with trace context": variant(traceparent="00-" + "a" * 32 + "-" + "b" * 16 + "-01", tracestate="k=v"),
|
||
"valid created_at with offset and fraction": variant(created_at="2026-09-01T15:00:00.123+03:00"),
|
||
"schema_version true (audit)": variant(schema_version=True),
|
||
"created_at date only (audit)": variant(created_at="2026-01-01"),
|
||
"traceparent number (audit)": variant(traceparent=123),
|
||
"tracestate 513 chars (audit)": variant(tracestate="x" * 513),
|
||
"attempt true": variant(attempt=True),
|
||
"attempt 0": variant(attempt=0),
|
||
"pipeline_version 1.0": variant(pipeline_version=1.0),
|
||
"job_id not uuid": variant(job_id="not-a-uuid"),
|
||
"job_id uuid without hyphens": variant(job_id="11111111111141118111111111111111"),
|
||
"extra field": variant(url="http://evil/"),
|
||
"missing created_at": variant(created_at=None),
|
||
"wrong type": variant(type="attachment.delete.v1"),
|
||
"traceparent bad version": variant(traceparent="01-" + "a" * 32 + "-" + "b" * 16 + "-01"),
|
||
"created_at no timezone": variant(created_at="2026-09-01T12:00:00"),
|
||
}
|
||
|
||
|
||
def main():
|
||
p = argparse.ArgumentParser()
|
||
p.add_argument("--output")
|
||
args = p.parse_args()
|
||
schema = json.loads((ROOT / "contracts/jobs.schema.json").read_text())
|
||
try:
|
||
import rfc3339_validator # noqa: F401 (без него FormatChecker не проверяет date-time)
|
||
formats = True
|
||
except ImportError:
|
||
formats = False
|
||
validator = Draft202012Validator(schema, format_checker=FormatChecker())
|
||
results, mismatches = [], 0
|
||
for name, msg in CASES.items():
|
||
schema_ok = validator.is_valid(msg)
|
||
try:
|
||
jobs.parse_message(json.dumps(msg).encode())
|
||
parser_ok = True
|
||
except jobs.InvalidMessage:
|
||
parser_ok = False
|
||
same = schema_ok == parser_ok
|
||
mismatches += not same
|
||
results.append({"case": name, "jsonschema_valid": schema_ok, "parser_valid": parser_ok, "match": same})
|
||
print("%s %-45s schema=%-5s parser=%s" % ("PASS" if same else "FAIL", name, schema_ok, parser_ok))
|
||
# F11
|
||
proc = subprocess.run(["docker", "compose", "run", "--rm", "--no-deps", "-T", "-e", "PIPELINE_VERSION=2", "api"],
|
||
cwd=ROOT, capture_output=True, text=True, timeout=180)
|
||
f11 = {"exit_code": proc.returncode,
|
||
"message": [l for l in (proc.stdout + proc.stderr).splitlines() if "PIPELINE_VERSION" in l][-1:]}
|
||
f11_ok = proc.returncode != 0 and bool(f11["message"])
|
||
print("%s F11 api with PIPELINE_VERSION=2 refuses to start: %s" % ("PASS" if f11_ok else "FAIL", f11))
|
||
if args.output:
|
||
Path(args.output).write_text(json.dumps({"date_time_format_checked": formats, "cases": results,
|
||
"F11": f11}, ensure_ascii=False, indent=1) + "\n")
|
||
ok = mismatches == 0 and f11_ok and formats
|
||
print("PASS" if ok else "FAIL", "(%d cases, %d mismatches, date-time format checked: %s)" % (len(CASES), mismatches, formats))
|
||
return 0 if ok else 1
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|