forked from mtusi2026/mtusi2026lab5
Лабораторная 5
This commit is contained in:
@@ -8,8 +8,8 @@ import re
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
def main():
|
||||
lab = json.loads((ROOT/'lab.json').read_text())['number']
|
||||
spec = json.loads((ROOT/'contracts/openapi.json').read_text())
|
||||
lab = json.loads((ROOT/'lab.json').read_text(encoding='utf-8'))['number']
|
||||
spec = json.loads((ROOT/'contracts/openapi.json').read_text(encoding='utf-8'))
|
||||
assert spec['openapi']=='3.1.0'
|
||||
assert spec['info']['version']=='1.%d.0'%lab
|
||||
operation_ids = set()
|
||||
@@ -41,11 +41,11 @@ def main():
|
||||
assert ('/api/v1/auth/sessions' in spec['paths']) == (lab>=2)
|
||||
assert ('/api/v1/attachments/{attachment_id}' in spec['paths']) == (lab>=4)
|
||||
for file in list((ROOT/'tests').glob('*.py'))+list((ROOT/'scripts').glob('*.py')):
|
||||
ast.parse(file.read_text(),filename=str(file))
|
||||
ast.parse(file.read_text(encoding='utf-8'),filename=str(file))
|
||||
for file in ROOT.rglob('*.json'):
|
||||
if any(part in {'.git','.venv','node_modules','vendor','output'} for part in file.parts):
|
||||
continue
|
||||
json.loads(file.read_text())
|
||||
json.loads(file.read_text(encoding='utf-8'))
|
||||
for required in ('README.md','COURSE.md','CONTRIBUTING.md','REPORT.md','contracts/README.md','tests/smoke.py','tests/README.md'):
|
||||
assert (ROOT/required).is_file(), 'missing '+required
|
||||
print('PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.')
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Exercise worker crash failpoints against the running local Compose stack."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
from urllib.parse import urlparse
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, LAB, check
|
||||
|
||||
|
||||
def compose(args, env, timeout=90):
|
||||
result = subprocess.run(
|
||||
["docker", "compose", *args],
|
||||
cwd=ROOT,
|
||||
env=env,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT,
|
||||
text=True,
|
||||
timeout=timeout,
|
||||
)
|
||||
if result.returncode:
|
||||
raise RuntimeError("docker compose failed: " + "\n".join(result.stdout.splitlines()[-25:]))
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def retry_record(attachment_id, env):
|
||||
attachment_id = str(uuid.UUID(attachment_id))
|
||||
query = (
|
||||
"SELECT concat_ws('|',j.status,j.attempt::text,count(ja.id)::text,"
|
||||
"coalesce(min(ja.outcome),'none')) "
|
||||
"FROM jobs j LEFT JOIN job_attempts ja ON ja.job_id=j.id "
|
||||
f"WHERE j.attachment_id='{attachment_id}' GROUP BY j.id"
|
||||
)
|
||||
return compose(
|
||||
["exec", "-T", "postgres", "psql", "-X", "-A", "-t", "-U", "messenger", "-d", "messenger", "-c", query],
|
||||
env,
|
||||
timeout=15,
|
||||
).strip()
|
||||
|
||||
|
||||
def main():
|
||||
if LAB < 5:
|
||||
raise RuntimeError("live fault injection requires lab5")
|
||||
base_url = os.environ.get("BASE_URL", "http://localhost:8080")
|
||||
parsed = urlparse(base_url)
|
||||
if not parsed.hostname:
|
||||
raise ValueError("BASE_URL must be an absolute HTTP(S) URL")
|
||||
env = dict(os.environ)
|
||||
env["HTTP_PORT"] = str(parsed.port or (443 if parsed.scheme == "https" else 80))
|
||||
env["WORKER_FAULT_INJECTION"] = ""
|
||||
client = Client(base_url, timeout=10)
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
results = []
|
||||
|
||||
try:
|
||||
for stage in ("before_original_put", "after_original_put"):
|
||||
compose(["stop", "worker"], env)
|
||||
attachment, original = client.attachment(alice, chat)
|
||||
injection_env = dict(env)
|
||||
injection_env["WORKER_FAULT_INJECTION"] = f"{attachment['id']}:1:{stage}"
|
||||
compose(["up", "-d", "--force-recreate", "worker"], injection_env)
|
||||
|
||||
ready = client.wait_ready(alice, attachment, wait_seconds=60)
|
||||
downloaded = client.call(
|
||||
"GET",
|
||||
f"/api/v1/attachments/{attachment['id']}/content",
|
||||
actor=alice,
|
||||
)
|
||||
check(downloaded["bytes"] == original, "original changed during injected retry")
|
||||
check({item["name"] for item in ready["variants"]} == {"thumbnail", "crop", "optimized"},
|
||||
"retry did not create all pipeline variants")
|
||||
record = retry_record(attachment["id"], env)
|
||||
check(record == "ready|2|1|retry", "injected crash did not recover through retry: " + record)
|
||||
results.append({
|
||||
"stage": stage,
|
||||
"attachment_id": attachment["id"],
|
||||
"status": ready["status"],
|
||||
"job_retry_record": record,
|
||||
"original_unchanged": True,
|
||||
})
|
||||
finally:
|
||||
env["WORKER_FAULT_INJECTION"] = ""
|
||||
compose(["up", "-d", "--force-recreate", "worker"], env)
|
||||
|
||||
print(json.dumps({"result": "PASS", "faults": results}, ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,178 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify failed-job routing and explicit replay against the local Compose stack."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from urllib.parse import urlparse
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, LAB, check
|
||||
|
||||
|
||||
def compose(args, env, input_bytes=None, timeout=90):
|
||||
result = subprocess.run(
|
||||
["docker", "compose", *args],
|
||||
cwd=ROOT,
|
||||
env=env,
|
||||
input=input_bytes,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT,
|
||||
timeout=timeout,
|
||||
)
|
||||
if result.returncode:
|
||||
output = result.stdout.decode("utf-8", errors="replace")
|
||||
raise RuntimeError("docker compose failed: " + "\n".join(output.splitlines()[-25:]))
|
||||
return result.stdout.decode("utf-8", errors="replace").strip()
|
||||
|
||||
|
||||
def put_staging_object(key, data, env):
|
||||
code = (
|
||||
"import os,sys,boto3; "
|
||||
"from botocore.config import Config; "
|
||||
"boto3.client('s3',endpoint_url=os.environ['S3_ENDPOINT'],"
|
||||
"region_name=os.environ.get('S3_REGION','us-east-1'),"
|
||||
"aws_access_key_id=os.environ['S3_ACCESS_KEY_ID'],"
|
||||
"aws_secret_access_key=os.environ['S3_SECRET_ACCESS_KEY'],"
|
||||
"config=Config(signature_version='s3v4',s3={'addressing_style':'path'})).put_object("
|
||||
"Bucket=os.environ['S3_BUCKET'],Key=sys.argv[1],Body=sys.stdin.buffer.read(),"
|
||||
"ContentType='image/png')"
|
||||
)
|
||||
compose(
|
||||
["run", "--rm", "--no-deps", "-T", "--entrypoint", "python", "worker", "-c", code, key],
|
||||
env,
|
||||
input_bytes=data,
|
||||
timeout=45,
|
||||
)
|
||||
|
||||
|
||||
def psql(query, env):
|
||||
return compose(
|
||||
["exec", "-T", "postgres", "psql", "-X", "-A", "-t", "-U", "messenger", "-d", "messenger", "-c", query],
|
||||
env,
|
||||
timeout=15,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
if LAB < 5:
|
||||
raise RuntimeError("live replay test requires lab5")
|
||||
base_url = os.environ.get("BASE_URL", "http://localhost:8080")
|
||||
parsed = urlparse(base_url)
|
||||
if not parsed.hostname:
|
||||
raise ValueError("BASE_URL must be an absolute HTTP(S) URL")
|
||||
env = dict(os.environ)
|
||||
env["HTTP_PORT"] = str(parsed.port or (443 if parsed.scheme == "https" else 80))
|
||||
env["WORKER_FAULT_INJECTION"] = ""
|
||||
client = Client(base_url, timeout=10)
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
attachment = None
|
||||
original = None
|
||||
staging_key = None
|
||||
|
||||
try:
|
||||
compose(["stop", "worker"], env)
|
||||
attachment, original = client.attachment(alice, chat)
|
||||
staging_key = f"staging/{attachment['id']}/original"
|
||||
put_staging_object(staging_key, b"invalid-test-payload", env)
|
||||
compose(["up", "-d", "worker"], env)
|
||||
|
||||
deadline = time.monotonic() + 60
|
||||
failed = None
|
||||
while time.monotonic() < deadline:
|
||||
failed = client.call(
|
||||
"GET",
|
||||
f"/api/v1/attachments/{attachment['id']}",
|
||||
actor=alice,
|
||||
schema="Attachment",
|
||||
)["json"]
|
||||
if failed["status"] == "failed":
|
||||
break
|
||||
time.sleep(0.25)
|
||||
check(failed is not None and failed["status"] == "failed", "invalid staging object did not fail permanently")
|
||||
check(failed["error_code"] == "processing_failed", "unexpected permanent error code")
|
||||
|
||||
attachment_id = str(uuid.UUID(attachment["id"]))
|
||||
failed_event_count = psql(
|
||||
"SELECT count(*) FROM outbox WHERE event_type='attachment.failed' "
|
||||
f"AND payload->>'attachment_id'='{attachment_id}' AND published_at IS NOT NULL",
|
||||
env,
|
||||
)
|
||||
check(failed_event_count == "1", "failed event was not publisher-confirmed")
|
||||
|
||||
put_staging_object(staging_key, original, env)
|
||||
replay_output = compose(
|
||||
["exec", "-T", "worker", "python", "-m", "src.replay", attachment_id, "--operator", "live-lab5-test"],
|
||||
env,
|
||||
timeout=30,
|
||||
)
|
||||
ready = client.wait_ready(alice, failed, wait_seconds=60)
|
||||
downloaded = client.call(
|
||||
"GET",
|
||||
f"/api/v1/attachments/{attachment_id}/content",
|
||||
actor=alice,
|
||||
)
|
||||
check(downloaded["bytes"] == original, "replayed original differs from accepted bytes")
|
||||
state = psql(
|
||||
"SELECT concat_ws('|',j.status,j.attempt::text,j.replay_count::text,count(ja.id)::text) "
|
||||
"FROM jobs j LEFT JOIN job_attempts ja ON ja.job_id=j.id "
|
||||
f"WHERE j.attachment_id='{attachment_id}' GROUP BY j.id",
|
||||
env,
|
||||
)
|
||||
check(state == "ready|1|1|1", "unexpected job state after replay: " + state)
|
||||
operator = psql(
|
||||
"SELECT operator FROM job_replays "
|
||||
f"WHERE attachment_id='{attachment_id}' ORDER BY replayed_at DESC LIMIT 1",
|
||||
env,
|
||||
)
|
||||
check(operator == "live-lab5-test", "replay audit entry is missing")
|
||||
|
||||
psql(
|
||||
"UPDATE jobs SET status='processing',attempt=2,lease_until=NOW()-INTERVAL '1 second' "
|
||||
f"WHERE attachment_id='{attachment_id}'; "
|
||||
"UPDATE attachments SET status='processing',updated_at=NOW() "
|
||||
f"WHERE id='{attachment_id}'",
|
||||
env,
|
||||
)
|
||||
lease_deadline = time.monotonic() + 60
|
||||
leased = None
|
||||
while time.monotonic() < lease_deadline:
|
||||
leased = client.call(
|
||||
"GET",
|
||||
f"/api/v1/attachments/{attachment_id}",
|
||||
actor=alice,
|
||||
schema="Attachment",
|
||||
)["json"]
|
||||
if leased["status"] == "ready":
|
||||
break
|
||||
time.sleep(0.25)
|
||||
check(leased is not None and leased["status"] == "ready", "expired lease did not recover")
|
||||
lease_state = psql(
|
||||
"SELECT concat_ws('|',j.status,j.attempt::text,j.replay_count::text,count(ja.id)::text) "
|
||||
"FROM jobs j LEFT JOIN job_attempts ja ON ja.job_id=j.id "
|
||||
f"WHERE j.attachment_id='{attachment_id}' GROUP BY j.id",
|
||||
env,
|
||||
)
|
||||
check(lease_state == "ready|3|1|1", "unexpected state after lease recovery: " + lease_state)
|
||||
print({
|
||||
"result": "PASS",
|
||||
"attachment_id": attachment_id,
|
||||
"failed_event_published": True,
|
||||
"replay_state": state,
|
||||
"lease_recovery_state": lease_state,
|
||||
"operator": operator,
|
||||
"original_unchanged": True,
|
||||
"replay_command_result": replay_output,
|
||||
"final_status": ready["status"],
|
||||
})
|
||||
finally:
|
||||
if attachment and original and staging_key:
|
||||
put_staging_object(staging_key, original, env)
|
||||
compose(["up", "-d", "worker"], env)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,7 @@
|
||||
@echo off
|
||||
setlocal
|
||||
cd /d "%~dp0.."
|
||||
docker compose down
|
||||
if errorlevel 1 exit /b 1
|
||||
docker compose up -d
|
||||
exit /b %errorlevel%
|
||||
Executable
+5
@@ -0,0 +1,5 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose down
|
||||
docker compose up -d
|
||||
@@ -0,0 +1,13 @@
|
||||
@echo off
|
||||
setlocal
|
||||
cd /d "%~dp0.."
|
||||
if /I "%TARGET_INSTANCE_ID%"=="api-1" (
|
||||
docker compose stop api1
|
||||
exit /b %errorlevel%
|
||||
)
|
||||
if /I "%TARGET_INSTANCE_ID%"=="api-2" (
|
||||
docker compose stop api2
|
||||
exit /b %errorlevel%
|
||||
)
|
||||
echo Unknown TARGET_INSTANCE_ID 1>&2
|
||||
exit /b 1
|
||||
Executable
+16
@@ -0,0 +1,16 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
case "${TARGET_INSTANCE_ID:-}" in
|
||||
api-1)
|
||||
docker compose stop api1
|
||||
;;
|
||||
api-2)
|
||||
docker compose stop api2
|
||||
;;
|
||||
*)
|
||||
echo "Unknown TARGET_INSTANCE_ID" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
@@ -6,17 +6,17 @@ from openapi_spec_validator import validate
|
||||
from jsonschema import Draft202012Validator
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
spec = json.loads((root/'contracts/openapi.json').read_text())
|
||||
spec = json.loads((root/'contracts/openapi.json').read_text(encoding='utf-8'))
|
||||
validate(spec)
|
||||
from referencing import Registry, Resource
|
||||
# The base URI resolves local #/components references inside examples.
|
||||
resource = dict(spec, **{'$schema': 'https://json-schema.org/draft/2020-12/schema'})
|
||||
registry = Registry().with_resource('urn:mtusi:openapi', Resource.from_contents(resource))
|
||||
for name, example in json.loads((root/'contracts/examples.json').read_text()).items():
|
||||
for name, example in json.loads((root/'contracts/examples.json').read_text(encoding='utf-8')).items():
|
||||
schema = {'$ref': 'urn:mtusi:openapi#/components/schemas/' + name}
|
||||
Draft202012Validator(schema, registry=registry).validate(example)
|
||||
for path in (root/'contracts').glob('*.schema.json'):
|
||||
schema = json.loads(path.read_text())
|
||||
schema = json.loads(path.read_text(encoding='utf-8'))
|
||||
Draft202012Validator.check_schema(schema)
|
||||
for example in schema.get('examples',[]):
|
||||
Draft202012Validator(schema).validate(example)
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify an accepted attachment survives worker and full-stack restart."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from urllib.parse import urlparse
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure, LAB, check
|
||||
|
||||
|
||||
def compose(args, env, timeout=120):
|
||||
result = subprocess.run(
|
||||
["docker", "compose", *args],
|
||||
cwd=ROOT,
|
||||
env=env,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT,
|
||||
text=True,
|
||||
timeout=timeout,
|
||||
)
|
||||
if result.returncode:
|
||||
raise RuntimeError("docker compose failed: " + "\n".join(result.stdout.splitlines()[-25:]))
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def main():
|
||||
if LAB < 5:
|
||||
raise RuntimeError("worker outage test requires lab5")
|
||||
base_url = os.environ.get("BASE_URL", "http://localhost:8080")
|
||||
parsed = urlparse(base_url)
|
||||
if not parsed.hostname:
|
||||
raise ValueError("BASE_URL must be an absolute HTTP(S) URL")
|
||||
env = dict(os.environ)
|
||||
env["HTTP_PORT"] = str(parsed.port or (443 if parsed.scheme == "https" else 80))
|
||||
env["WORKER_FAULT_INJECTION"] = ""
|
||||
client = Client(base_url, timeout=10)
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
worker_stopped = False
|
||||
|
||||
try:
|
||||
compose(["stop", "worker"], env)
|
||||
worker_stopped = True
|
||||
attachment, original = client.attachment(alice, chat)
|
||||
check(attachment["status"] == "queued", "upload was not accepted as queued")
|
||||
unavailable = client.call(
|
||||
"GET",
|
||||
f"/api/v1/attachments/{attachment['id']}/content",
|
||||
expected=409,
|
||||
actor=alice,
|
||||
)
|
||||
check(unavailable["json"]["error"]["code"] == "conflict", "queued content was not rejected")
|
||||
confirmed_message = client.message(alice, chat, "API remains available while worker is stopped")
|
||||
|
||||
restart = subprocess.run(
|
||||
[str(ROOT / "scripts" / "restart.cmd")],
|
||||
cwd=ROOT,
|
||||
env=env,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT,
|
||||
text=True,
|
||||
timeout=120,
|
||||
)
|
||||
if restart.returncode:
|
||||
raise RuntimeError("restart hook failed: " + "\n".join(restart.stdout.splitlines()[-25:]))
|
||||
worker_stopped = False
|
||||
|
||||
deadline = time.monotonic() + 90
|
||||
while True:
|
||||
try:
|
||||
client.call("GET", "/health/ready", schema="Health")
|
||||
client.call("GET", "/api/v1/users/me", actor=alice, schema="User")
|
||||
break
|
||||
except Failure:
|
||||
if time.monotonic() >= deadline:
|
||||
raise
|
||||
time.sleep(0.5)
|
||||
|
||||
ready = client.wait_ready(alice, attachment, wait_seconds=60)
|
||||
downloaded = client.call(
|
||||
"GET",
|
||||
f"/api/v1/attachments/{attachment['id']}/content",
|
||||
actor=alice,
|
||||
)
|
||||
check(downloaded["bytes"] == original, "accepted original changed across restart")
|
||||
message_page = client.call(
|
||||
"GET",
|
||||
f"/api/v1/chats/{chat['id']}/messages?limit=100",
|
||||
actor=alice,
|
||||
schema="MessagePage",
|
||||
)["json"]
|
||||
check(any(item == confirmed_message["json"] for item in message_page["items"]),
|
||||
"confirmed message was lost across restart")
|
||||
|
||||
attachment_id = str(uuid.UUID(attachment["id"]))
|
||||
query = (
|
||||
"SELECT concat_ws('|',j.status,j.attempt::text,"
|
||||
"(SELECT count(*) FROM outbox o WHERE o.event_type='attachment.process' "
|
||||
f"AND o.payload->>'attachment_id'='{attachment_id}'),"
|
||||
"(SELECT count(*) FROM outbox o WHERE o.event_type='attachment.process' "
|
||||
f"AND o.payload->>'attachment_id'='{attachment_id}' AND o.published_at IS NOT NULL)) "
|
||||
f"FROM jobs j WHERE j.attachment_id='{attachment_id}'"
|
||||
)
|
||||
state = compose(
|
||||
["exec", "-T", "postgres", "psql", "-X", "-A", "-t", "-U", "messenger", "-d", "messenger", "-c", query],
|
||||
env,
|
||||
timeout=15,
|
||||
)
|
||||
check(state == "ready|1|1|1", "unexpected durable job/outbox state: " + state)
|
||||
print({
|
||||
"result": "PASS",
|
||||
"attachment_id": attachment_id,
|
||||
"accepted_status": attachment["status"],
|
||||
"final_status": ready["status"],
|
||||
"state": state,
|
||||
"original_unchanged": True,
|
||||
"confirmed_message_preserved": True,
|
||||
})
|
||||
finally:
|
||||
if worker_stopped:
|
||||
compose(["up", "-d", "worker"], env)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user