forked from mtusi2026/mtusi2026lab7
Перенос решения ЛР 6 без изменений (src, migrations, student-tests, bench, infra, scripts, compose, Dockerfile, docs)
This commit is contained in:
@@ -0,0 +1,184 @@
|
||||
"""Lab 6, against the running stand: what the stored observations really contain.
|
||||
|
||||
* one upload with a client-chosen traceparent = ONE trace: API SERVER (continues it) -> relay
|
||||
PRODUCER -> worker CONSUMER -> s3/db spans; with WORKER_FAULT_POINTS=transient_error=1 the
|
||||
failed attempt AND the retry are in the same trace (two publishes, two consumer spans);
|
||||
* log records of api and worker carry the trace_id and the X-Request-Id;
|
||||
* metrics: exact counters (jobs processed by outcome, time to ready) moved for our work, and
|
||||
no metric series has an id/raw path as a label value;
|
||||
* nothing secret in Loki/Tempo: no password, token, message text of our requests.
|
||||
Stores are read through Grafana's datasource proxy (scripts/obs.py).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import secrets
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
import obs
|
||||
from conftest import ROOT, service_with_env
|
||||
|
||||
pytestmark = pytest.mark.stack
|
||||
|
||||
SAMPLE = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
|
||||
UUID_RE = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
|
||||
|
||||
|
||||
def traced_upload(api, actor, chat):
|
||||
trace_id, parent = secrets.token_hex(16), secrets.token_hex(8)
|
||||
response = api.upload(actor, chat, SAMPLE, headers={"traceparent": f"00-{trace_id}-{parent}-01",
|
||||
"X-Request-Id": "obs-" + secrets.token_hex(6)})
|
||||
assert response.headers["x-trace-id"] == trace_id
|
||||
return trace_id, parent, response
|
||||
|
||||
|
||||
def jobs_counter(outcome: str) -> float:
|
||||
return obs.scalar(f'sum(messenger_jobs_processed_total{{outcome="{outcome}"}})', 0.0)
|
||||
|
||||
|
||||
def test_upload_is_one_trace_api_relay_worker_s3_db(api):
|
||||
owner = api.user("obs")
|
||||
chat = api.chat(owner)
|
||||
trace_id, parent, response = traced_upload(api, owner, chat)
|
||||
att = api.wait_status(owner, response.json()["id"], "ready")
|
||||
spans = obs.wait_trace(trace_id, lambda s: any(x["name"] == "db jobs.complete" for x in s), timeout=90)
|
||||
ids = {s["span_id"]: s for s in spans}
|
||||
server = [s for s in spans if s["kind"] == "SERVER"]
|
||||
assert len(server) == 1 and server[0]["service"] == "messenger-api"
|
||||
assert server[0]["parent_id"] == parent # continued, not replaced
|
||||
assert server[0]["name"] == "POST /api/v1/chats/{chat_id}/attachments"
|
||||
producer = [s for s in spans if s["kind"] == "PRODUCER"]
|
||||
consumer = [s for s in spans if s["kind"] == "CONSUMER"]
|
||||
assert len(producer) == 1 and producer[0]["service"] == "messenger-relay"
|
||||
assert len(consumer) == 1 and consumer[0]["service"] == "messenger-worker"
|
||||
assert consumer[0]["parent_id"] == producer[0]["span_id"]
|
||||
assert producer[0]["parent_id"] == server[0]["span_id"] # context stored with the job = the upload request
|
||||
assert any(s["name"] == "db enqueue" and s["parent_id"] == server[0]["span_id"] for s in spans)
|
||||
assert consumer[0]["attrs"]["messenger.job.outcome"] == "succeeded"
|
||||
assert consumer[0]["attrs"]["messenger.attachment.id"] == att["id"]
|
||||
worker_children = {s["name"] for s in spans if s["parent_id"] == consumer[0]["span_id"]}
|
||||
assert {"db jobs.claim", "s3 download", "image render", "s3 put", "db jobs.complete"} <= worker_children
|
||||
puts = [s for s in spans if s["name"] == "s3 put" and s["parent_id"] == consumer[0]["span_id"]]
|
||||
assert len(puts) == 4 # original + thumbnail + crop + optimized
|
||||
for s in spans: # no object keys / urls in span attributes
|
||||
assert not any(k in s["attrs"] for k in ("aws.s3.key", "url.full", "http.url", "db.query.text"))
|
||||
|
||||
|
||||
def test_retry_is_visible_in_the_same_trace():
|
||||
"""WORKER_FAULT_POINTS=transient_error=1: attempt 1 fails (transient), the job is retried via
|
||||
the outbox; both publishes and both worker attempts belong to the upload's trace."""
|
||||
from conftest import Api
|
||||
api = Api()
|
||||
before_retry, before_ok = jobs_counter("retry"), jobs_counter("succeeded")
|
||||
with service_with_env("worker", WORKER_FAULT_POINTS="transient_error=1", JOB_RETRY_BASE_SECONDS="1"):
|
||||
owner = api.user("obsretry")
|
||||
chat = api.chat(owner)
|
||||
trace_id, _, response = traced_upload(api, owner, chat)
|
||||
api.wait_status(owner, response.json()["id"], "ready", timeout=90)
|
||||
spans = obs.wait_trace(trace_id, lambda s: sum(x["kind"] == "CONSUMER" for x in s) >= 2
|
||||
and any(x["name"] == "db jobs.complete" for x in s), timeout=90)
|
||||
consumers = sorted((s for s in spans if s["kind"] == "CONSUMER"), key=lambda s: s["start"])
|
||||
producers = sorted((s for s in spans if s["kind"] == "PRODUCER"), key=lambda s: s["start"])
|
||||
assert len(producers) == 2 and len(consumers) == 2
|
||||
assert [p["attrs"]["messenger.job.attempt"] for p in producers] == [1, 2] or \
|
||||
[str(p["attrs"]["messenger.job.attempt"]) for p in producers] == ["1", "2"]
|
||||
first, second = consumers
|
||||
assert first["attrs"]["messenger.job.outcome"] == "retry" and first["status"] == "ERROR"
|
||||
assert first["attrs"]["messenger.job.error_code"] == "injected_transient"
|
||||
assert second["attrs"]["messenger.job.outcome"] == "succeeded"
|
||||
assert {c["parent_id"] for c in consumers} == {p["span_id"] for p in producers}
|
||||
time.sleep(12) # metric export 5 s + batch + push
|
||||
assert jobs_counter("retry") >= before_retry + 1
|
||||
assert jobs_counter("succeeded") >= before_ok + 1
|
||||
|
||||
|
||||
def test_logs_of_api_and_worker_are_joined_by_trace_id(api):
|
||||
owner = api.user("obslog")
|
||||
chat = api.chat(owner)
|
||||
trace_id, _, response = traced_upload(api, owner, chat)
|
||||
request_id = response.headers["x-request-id"]
|
||||
api.wait_status(owner, response.json()["id"], "ready")
|
||||
deadline = time.monotonic() + 60
|
||||
records = []
|
||||
while time.monotonic() < deadline:
|
||||
records = obs.trace_logs(trace_id, minutes=10)
|
||||
if {"messenger-api", "messenger-worker"} <= {r["service"] for r in records} and \
|
||||
any(r["line"] == "job_done" for r in records):
|
||||
break
|
||||
time.sleep(2)
|
||||
access = [r for r in records if r["service"] == "messenger-api" and r["line"] == "request"]
|
||||
assert access and access[0]["metadata"]["request_id"] == request_id
|
||||
assert access[0]["metadata"]["route"] == "/api/v1/chats/{chat_id}/attachments"
|
||||
assert access[0]["metadata"]["severity_text"] == "INFO"
|
||||
done = [r for r in records if r["service"] == "messenger-worker" and r["line"] == "job_done"]
|
||||
assert done and done[0]["metadata"]["outcome"] == "succeeded"
|
||||
for r in records:
|
||||
assert len(r["metadata"]["span_id"]) == 16 and r["metadata"].get("trace_id") in (None, trace_id)
|
||||
|
||||
|
||||
def test_no_ids_or_raw_paths_in_metric_labels():
|
||||
"""Cardinality guard: no label VALUE of an application series looks like a UUID/hex id, and the
|
||||
route label only holds templates."""
|
||||
series = obs.promql('count by (__name__) ({job=~"messenger-.+"})')
|
||||
assert series, "no application metrics in Prometheus"
|
||||
names = [s["metric"]["__name__"] for s in series]
|
||||
for name in names:
|
||||
for s in obs.promql(f'{name}{{job=~"messenger-.+"}}'):
|
||||
for label, value in s["metric"].items():
|
||||
if label in ("instance",): # container hostname (one per replica)
|
||||
continue
|
||||
assert not UUID_RE.search(value), (name, label, value)
|
||||
assert label not in ("user_id", "chat_id", "message_id", "attachment_id", "request_id", "url_path")
|
||||
routes = {s["metric"]["http_route"] for s in obs.promql("count by (http_route) (http_server_request_duration_seconds_count)")}
|
||||
assert routes and all(r == "UNMATCHED" or r.startswith("/") and not UUID_RE.search(r) for r in routes)
|
||||
assert "/api/v1/chats/{chat_id}/messages" in routes
|
||||
|
||||
|
||||
def test_no_secrets_or_message_text_in_logs_and_traces(api):
|
||||
owner = api.user("obssecret")
|
||||
chat = api.chat(owner)
|
||||
text = "секретный-текст-" + secrets.token_hex(8)
|
||||
response = api.post_message(owner, chat, {"text": text})
|
||||
trace_id = response.headers["x-trace-id"]
|
||||
spans = obs.wait_trace(trace_id, lambda s: any(x["kind"] == "SERVER" for x in s), timeout=60)
|
||||
time.sleep(3)
|
||||
blobs = [str(spans), str(obs.trace_logs(trace_id, minutes=10)),
|
||||
str(obs.logs(f'{{service_name="messenger-api"}} |= "{owner["username"]}"', minutes=10))]
|
||||
for blob in blobs:
|
||||
assert text not in blob
|
||||
assert owner["token"] not in blob
|
||||
assert owner["password"] not in blob
|
||||
assert "Bearer " not in blob and "Basic " not in blob
|
||||
|
||||
|
||||
def test_history_survives_restart_of_the_stores(api):
|
||||
"""Persistent volumes keep the history: a trace, its logs and a metric value recorded BEFORE a
|
||||
restart of Tempo, Loki and Prometheus are still found after it."""
|
||||
from conftest import compose
|
||||
owner = api.user("obshist")
|
||||
chat = api.chat(owner)
|
||||
trace_id, _, response = traced_upload(api, owner, chat)
|
||||
api.wait_status(owner, response.json()["id"], "ready")
|
||||
obs.wait_trace(trace_id, lambda s: any(x["kind"] == "CONSUMER" for x in s), timeout=90)
|
||||
time.sleep(15) # metric pushes (5 s) and log batches are in
|
||||
before = time.time()
|
||||
value_before = obs.scalar('sum(messenger_jobs_processed_total{outcome="succeeded"})')
|
||||
assert value_before and value_before >= 1
|
||||
compose("restart", "tempo", "loki", "prometheus", timeout=180)
|
||||
deadline = time.monotonic() + 180
|
||||
while True:
|
||||
try:
|
||||
spans = obs.trace_spans(trace_id)
|
||||
records = obs.trace_logs(trace_id, minutes=15)
|
||||
old = obs.promql('sum(messenger_jobs_processed_total{outcome="succeeded"})', at=before)
|
||||
if spans and records and old:
|
||||
break
|
||||
except Exception: # noqa: BLE001 - stores still starting
|
||||
pass
|
||||
assert time.monotonic() < deadline, "history not available after the restart"
|
||||
time.sleep(3)
|
||||
assert any(s["kind"] == "SERVER" for s in spans) and any(s["kind"] == "CONSUMER" for s in spans)
|
||||
assert any(r["line"] == "job_done" for r in records)
|
||||
assert float(old[0]["value"][1]) == value_before
|
||||
Reference in New Issue
Block a user