forked from mtusi2026/mtusi2026lab5
тесты lab4 переведены на 202 + worker; unit-тесты pipeline; кейсы рецензий как 415
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> PNG с фильтром строки 5/0xff, IDAT не zlib, JPEG из 27 байт, SOS с компонентом не из SOF: 415 при загрузке. 40 Мпикс проходит до ready в лимите памяти worker.
This commit is contained in:
+99
-40
@@ -120,21 +120,33 @@ def service_down(service: str, how: str = "stop"):
|
||||
wait_stand()
|
||||
|
||||
|
||||
def recreate(service: str, env: dict, scale: int | None = None) -> None:
|
||||
"""`docker compose up` of ONE service with the given environment (no dependency restarts)."""
|
||||
cmd = ["docker", "compose", "up", "-d", "--no-deps", "--wait", service]
|
||||
if scale is not None:
|
||||
cmd[4:4] = ["--scale", f"{service}={scale}"]
|
||||
subprocess.run(cmd, cwd=ROOT, env=env, capture_output=True, text=True, check=True, timeout=180)
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def api_with_env(**overrides: str):
|
||||
"""Recreate the api container with environment overrides (e.g. SESSION_TTL_SECONDS=2),
|
||||
then ALWAYS recreate it with the normal configuration."""
|
||||
env = {**os.environ, **overrides}
|
||||
subprocess.run(["docker", "compose", "up", "-d", "--wait", "api"], cwd=ROOT, env=env,
|
||||
capture_output=True, text=True, check=True, timeout=180)
|
||||
wait_stand()
|
||||
def service_with_env(service: str, scale: int | None = None, **overrides: str):
|
||||
"""Recreate a service (api, relay, worker) with environment overrides (e.g. FAULT_POINTS of the
|
||||
worker = WORKER_FAULT_POINTS), then ALWAYS recreate it with the normal configuration."""
|
||||
clean = {k: v for k, v in os.environ.items() if k not in overrides}
|
||||
recreate(service, {**os.environ, **overrides}, scale)
|
||||
if service == "api":
|
||||
wait_stand()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
clean = {k: v for k, v in os.environ.items() if k not in overrides}
|
||||
subprocess.run(["docker", "compose", "up", "-d", "--wait", "api"], cwd=ROOT, env=clean,
|
||||
capture_output=True, text=True, check=True, timeout=180)
|
||||
wait_stand()
|
||||
recreate(service, clean, 1 if scale is not None and service != "api" else None)
|
||||
wait_healthy(service)
|
||||
if service == "api":
|
||||
wait_stand()
|
||||
|
||||
|
||||
def api_with_env(**overrides: str):
|
||||
return service_with_env("api", **overrides)
|
||||
|
||||
|
||||
def running_replicas() -> list[dict]:
|
||||
@@ -235,7 +247,7 @@ class Api:
|
||||
def send(self, actor: dict, chat: dict, text: str, key: str | None = None) -> dict:
|
||||
return self.post_message(actor, chat, {"text": text}, key=key).json()
|
||||
|
||||
def upload(self, actor: dict, chat: dict, data, expected=201, *, content_type: str | None = "image/png",
|
||||
def upload(self, actor: dict, chat: dict, data, expected=202, *, content_type: str | None = "image/png",
|
||||
filename: str | None = "photo.png", query: str | None = None, headers: dict | None = None):
|
||||
"""POST raw bytes to /chats/{id}/attachments. `query` replaces the whole query string
|
||||
(to send hand-made percent-encoding); `data` may be bytes or an iterator (chunked)."""
|
||||
@@ -247,12 +259,31 @@ class Api:
|
||||
path = f"/api/v1/chats/{chat['id']}/attachments" + (f"?{query}" if query else "")
|
||||
if isinstance(data, (bytes, bytearray)):
|
||||
return self.call("POST", path, expected, token=actor["token"], raw=bytes(data), headers=h,
|
||||
schema="Attachment" if expected == 201 else None)
|
||||
schema="Attachment" if expected == 202 else None)
|
||||
h["Authorization"] = "Bearer " + actor["token"]
|
||||
response = self.client.post(path, content=data, headers=h)
|
||||
assert response.status_code == expected, (response.status_code, response.text[:300])
|
||||
return response
|
||||
|
||||
def attachment(self, actor: dict, attachment_id: str, expected=200) -> dict:
|
||||
return self.call("GET", f"/api/v1/attachments/{attachment_id}", expected, token=actor["token"],
|
||||
schema="Attachment" if expected == 200 else None).json()
|
||||
|
||||
def wait_status(self, actor: dict, attachment_id: str, *statuses: str, timeout: float = 60) -> dict:
|
||||
"""Poll the metadata until the status is one of `statuses` (default: a final one)."""
|
||||
wanted = statuses or ("ready", "failed")
|
||||
deadline = time.monotonic() + timeout
|
||||
while True:
|
||||
att = self.attachment(actor, attachment_id)
|
||||
if att["status"] in wanted:
|
||||
return att
|
||||
assert time.monotonic() < deadline, f"attachment stayed {att['status']}, wanted {wanted}"
|
||||
time.sleep(0.3)
|
||||
|
||||
def content(self, actor: dict, attachment_id: str, variant: str | None = None, expected=200):
|
||||
query = f"?variant={variant}" if variant else ""
|
||||
return self.call("GET", f"/api/v1/attachments/{attachment_id}/content{query}", expected, token=actor["token"])
|
||||
|
||||
def history(self, actor: dict, chat: dict, limit: int) -> tuple[list[dict], int]:
|
||||
"""Walk all pages; returns (items, number_of_pages)."""
|
||||
items, pages, cursor = [], 0, None
|
||||
@@ -300,73 +331,101 @@ def run_hook(name: str, timeout: float = 180, **env: str) -> subprocess.Complete
|
||||
timeout=timeout, env={**os.environ, **env})
|
||||
|
||||
|
||||
def s3_exec(body: str, service: str = "api", stdin: str | None = None) -> str:
|
||||
"""Run `body` (async Python, `s` = messenger.storage.Storage) INSIDE a container that holds S3
|
||||
credentials: `api` (Read+Write, the API's own key pair) or `reconciler` (+List). The S3 port is
|
||||
not published on the host; this is how the tests inject faults directly into the bucket."""
|
||||
def s3_exec(body: str, bucket: str = "final", service: str = "worker", stdin: str | None = None) -> str:
|
||||
"""Run `body` (async Python, `s` = messenger.storage.Storage of the final or the staging bucket)
|
||||
INSIDE a container that holds S3 credentials: `worker` (Read+Write both buckets, no List) or
|
||||
`auditor` (Read+List, no Write). The S3 port is not published on the host; this is how the
|
||||
tests look into the buckets and inject faults."""
|
||||
script = ("import asyncio, base64, json, sys\n"
|
||||
"from messenger.config import Settings, s3_settings\n"
|
||||
"from messenger.storage import Storage, ObjectMissing\n"
|
||||
"async def main():\n"
|
||||
" st = Settings(host='', port=0, env='lab', log_level='info', shutdown_timeout=0, max_body_bytes=1024, **s3_settings())\n"
|
||||
" s = Storage(st)\n"
|
||||
f" s = Storage(st, bucket=st.s3_staging_bucket if {bucket == 'staging'} else None)\n"
|
||||
" await s.open()\n"
|
||||
" try:\n" + "".join(" " + line + "\n" for line in body.splitlines()) +
|
||||
" finally:\n"
|
||||
" await s.close()\n"
|
||||
"asyncio.run(main())\n")
|
||||
if service == "api":
|
||||
cmd = ["exec", "-T", "api", "python", "-c", script]
|
||||
else:
|
||||
if service == "auditor":
|
||||
cmd = ["run", "--rm", "--no-deps", "-T", "--entrypoint", "python", service, "-c", script]
|
||||
else:
|
||||
cmd = ["exec", "-T", service, "python", "-c", script]
|
||||
return compose(*cmd, timeout=120, stdin=stdin).stdout.strip()
|
||||
|
||||
|
||||
def s3_put(key: str, data: bytes) -> None:
|
||||
def s3_put(key: str, data: bytes, bucket: str = "final") -> None:
|
||||
"""Write raw bytes under `key` (base64 over stdin: Windows limits command lines to 32 KiB)."""
|
||||
s3_exec(f"await s.put({key!r}, base64.b64decode(sys.stdin.read()), 'image/png', {{}})",
|
||||
s3_exec(f"await s.put({key!r}, base64.b64decode(sys.stdin.read()), 'image/png', {{}})", bucket,
|
||||
stdin=base64.b64encode(data).decode())
|
||||
|
||||
|
||||
def s3_delete(key: str) -> None:
|
||||
s3_exec(f"await s.delete({key!r})")
|
||||
def s3_delete(key: str, bucket: str = "final") -> None:
|
||||
s3_exec(f"await s.delete({key!r})", bucket)
|
||||
|
||||
|
||||
def s3_size(key: str) -> int | None:
|
||||
out = s3_exec(f"try:\n print((await s.head({key!r})).size)\nexcept ObjectMissing:\n print(-1)")
|
||||
def s3_size(key: str, bucket: str = "final") -> int | None:
|
||||
out = s3_exec(f"try:\n print((await s.head({key!r})).size)\nexcept ObjectMissing:\n print(-1)", bucket)
|
||||
size = int(out.splitlines()[-1])
|
||||
return None if size < 0 else size
|
||||
|
||||
|
||||
def s3_keys() -> set[str]:
|
||||
"""Every object key under o/ (needs List: runs with the reconciler's key pair)."""
|
||||
def s3_keys(prefix: str, bucket: str = "final") -> set[str]:
|
||||
"""Every object key under `prefix` (needs List: runs with the auditor's key pair)."""
|
||||
out = s3_exec("keys, after = [], None\n"
|
||||
"while True:\n"
|
||||
" page, more = await s.list_page('o/', after, 1000)\n"
|
||||
f" page, more = await s.list_page({prefix!r}, after, 1000)\n"
|
||||
" keys += [o.key for o in page]\n"
|
||||
" if not more or not page:\n"
|
||||
" break\n"
|
||||
" after = page[-1].key\n"
|
||||
"print(json.dumps(keys))", service="reconciler")
|
||||
"print(json.dumps(keys))", bucket, service="auditor")
|
||||
return set(json.loads(out.splitlines()[-1]))
|
||||
|
||||
|
||||
def reconcile(*args: str, expect_code: int = 0) -> dict:
|
||||
"""Run the reconciler CLI (compose service, profile tools) and return its JSON report."""
|
||||
# --no-deps: never let `compose run` start a store that a test has stopped on purpose.
|
||||
result = compose("run", "--rm", "--no-deps", "-T", "reconciler", "--samples", "100000", *args, check=False,
|
||||
timeout=300)
|
||||
assert result.returncode == expect_code, (result.returncode, result.stderr[-2000:])
|
||||
def jobctl(*args: str, expect_code: int = 0) -> dict:
|
||||
"""Operator CLI (compose service jobctl, profile tools); returns its JSON output."""
|
||||
result = compose("run", "--rm", "--no-deps", "-T", "jobctl", *args, check=False, timeout=120)
|
||||
assert result.returncode == expect_code, (result.returncode, result.stdout[-1000:], result.stderr[-1000:])
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
def findings_by_key(report: dict) -> dict[str, dict]:
|
||||
return {item["key"]: dict(item, kind=kind) for kind, items in report["samples"].items() for item in items}
|
||||
def audit(*args: str) -> dict:
|
||||
"""Read-only invariant checker (compose service auditor); asserts that it found no violation."""
|
||||
result = compose("run", "--rm", "--no-deps", "-T", "auditor", *args, check=False, timeout=300)
|
||||
report = json.loads(result.stdout)
|
||||
assert result.returncode == 0 and report["ok"], json.dumps(report.get("violations"), ensure_ascii=False)[:3000]
|
||||
return report
|
||||
|
||||
|
||||
def job_rows(attachment_id: str) -> list[dict]:
|
||||
out = psql("SELECT coalesce(json_agg(json_build_object('id', id, 'state', state, 'attempt', attempt, 'kind', kind, "
|
||||
"'pipeline_version', pipeline_version, 'error_code', error_code) ORDER BY created_at), '[]') "
|
||||
"FROM jobs WHERE attachment_id = '%s'" % attachment_id)
|
||||
return json.loads(out)
|
||||
|
||||
|
||||
def events_of(attachment_id: str) -> list[dict]:
|
||||
out = psql("SELECT coalesce(json_agg(json_build_object('event', e.event, 'attempt', e.attempt, 'actor', e.actor, "
|
||||
"'error_code', e.error_code, 'detail', e.detail, 'at', e.at) ORDER BY e.id), '[]') "
|
||||
"FROM job_events e JOIN jobs j ON j.id = e.job_id WHERE j.attachment_id = '%s'" % attachment_id)
|
||||
return json.loads(out)
|
||||
|
||||
|
||||
def queue_depth(queue: str = "messenger.attachment-jobs") -> int:
|
||||
out = compose("exec", "-T", "broker", "rabbitmqctl", "-q", "list_queues", "name", "messages").stdout
|
||||
for line in out.splitlines():
|
||||
name, _, count = line.partition("\t")
|
||||
if name == queue:
|
||||
return int(count)
|
||||
raise AssertionError("queue not found: " + queue)
|
||||
|
||||
|
||||
def attachment_row(attachment_id: str) -> dict | None:
|
||||
out = psql("SELECT json_build_object('status', status, 'object_key', object_key, 'size', size_bytes, "
|
||||
"'lost_reason', lost_reason) FROM attachments WHERE id = '%s'" % attachment_id)
|
||||
"'lost_reason', lost_reason, 'staging_key', staging_key, 'staging_state', staging_state, "
|
||||
"'published_version', published_version, 'error_code', error_code) "
|
||||
"FROM attachments WHERE id = '%s'" % attachment_id)
|
||||
return json.loads(out) if out else None
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user