Files
mtusi2026lab6/student-tests/queue_contract_check.py
T
zemiles c199f6632a ЛР 6 — БПИ2303 — Лазарев — на 4
Перенесена реализация lab5 (API x2 за HAProxy, PostgreSQL, SeaweedFS S3,
RabbitMQ, relay outbox, worker x2, janitor) без изменения бизнес-API.

Наблюдаемость:
- OpenTelemetry SDK в API, relay, worker, janitor: traces, metrics, logs
  по OTLP/HTTP; структурные JSON-логи с trace_id/span_id
- OTel Collector (memory_limiter, batch, ограниченные очереди и retry),
  Prometheus (метрики, alert rules), Loki (логи), Tempo (трассы),
  Grafana с provisioning datasources и dashboard
- W3C trace context API -> outbox -> RabbitMQ -> worker (parent-child,
  включая retry); метрики очереди, пула БД, загрузки worker, CPU/RAM
- SLI/SLO, 10 alert rules с unit-тестами promtool и runbooks
- инциденты: остановка worker, блокировка БД, отказ telemetry backend;
  по наблюдениям исправлен простой worker в цикле AMQP (разбор x2.4)
2026-11-17 10:59:41 +03:00

99 lines
4.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/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())