перенос 4 лабы и реализация 5

This commit is contained in:
Ванек
2026-11-12 18:53:34 +03:00
parent 276dbdad8a
commit eca7c0f763
83 changed files with 13505 additions and 57 deletions
+275
View File
@@ -0,0 +1,275 @@
"""Реальные отказы/очистка/память уровня 4; только временный тестовый стенд."""
from concurrent.futures import ThreadPoolExecutor
import hashlib
import io
import json
import os
import socket
import subprocess
import threading
import time
from urllib.parse import urlsplit
from uuid import uuid4
from PIL import Image
from helpers import Client, ROOT
from client import Failure
def run_checks(base, env, compose, apis, script, sql):
result = {}
client = Client(base, timeout=30)
alice, bob, _, chat = client.bootstrap()
png = (ROOT / "tests/fixtures/sample.png").read_bytes()
upload_path = "/api/v1/chats/" + chat["id"] + "/attachments?filename=sample.png"
def upload():
return client.call("POST", upload_path, 201, actor=alice, raw=png,
headers={"Content-Type": "image/png"}, schema="Attachment")
def inside(code, data=None):
completed = subprocess.run(["docker", "exec", "-i", apis()[0]["Id"], "python", "-c", code],
input=json.dumps(data), capture_output=True, text=True, timeout=45, check=True)
return json.loads(completed.stdout)
def cleanup():
return inside("from src import db; from src.cleanup import cleanup_once; import json; "
"db.pool.open(wait=True); print(json.dumps(cleanup_once())); db.pool.close()")
def stat(key):
return inside("import json,sys; from src import object_store; from minio.error import S3Error\n"
"key=json.load(sys.stdin)\n"
"try:\n r=object_store.client.stat_object(object_store.BUCKET,key); print(json.dumps({'size':r.size}))\n"
"except S3Error as e:\n print(json.dumps({'error':e.code}))", key)
def age(key):
sql("UPDATE attachment_uploads SET created_at=clock_timestamp()-interval '2 hours' WHERE object_key='" + key + "'")
compose("stop", "cleanup")
try:
for _ in range(2):
compose("run", "--rm", "s3-bootstrap")
ready = upload()["json"]
key = sql("SELECT object_key FROM attachments WHERE id='" + ready["id"] + "'")
backend_id = compose("ps", "-q", "s3-storage")
backend = json.loads(subprocess.check_output(["docker", "inspect", backend_id], text=True))[0]
assert not set(backend["NetworkSettings"]["Networks"]) & set(apis()[0]["NetworkSettings"]["Networks"])
backend_ip = next(iter(backend["NetworkSettings"]["Networks"].values()))["IPAddress"]
# Вызов S3 напрямую из контейнера клиента, минуя HTTP API приложения.
result["private_bucket"] = inside("""
import io,json,socket,sys
from urllib.error import HTTPError
from urllib.request import urlopen
from minio.error import S3Error
from src import object_store
data=json.load(sys.stdin); key=data['key']
try:
urlopen('http://s3:9000/'+object_store.BUCKET+'/'+key,timeout=3)
raise AssertionError('public original')
except HTTPError as e:
assert e.code == 403
for operation in (lambda: object_store.client.make_bucket('forbidden-bucket'),
lambda: object_store.client.put_object(object_store.BUCKET,'outside-prefix',io.BytesIO(b'x'),1)):
try:
operation()
raise AssertionError('excess application permissions')
except S3Error as e:
assert e.code == 'AccessDenied', e.code
for port in (9333,8888,8080):
with socket.socket() as connection:
connection.settimeout(1)
assert connection.connect_ex(('s3',port)) != 0, 'admin/backend port open'
with socket.socket() as connection:
connection.settimeout(.5)
assert connection.connect_ex((data['backend_ip'],port)) != 0, 'storage network reachable from API'
print(json.dumps({'anonymous_get':403,'create_bucket':'AccessDenied','write_outside_prefix':'AccessDenied',
'admin_ports_unreachable':[9333,8888,8080],'storage_network_isolated':True,'bootstrap_runs':2}))
""", {"key":key, "backend_ip":backend_ip})
print("PASS: private S3, limited credentials, isolated administration, repeated bootstrap", flush=True)
# Останавливаем именно реплику, которая ответила на upload, а затем читаем другой.
uploaded = upload()
target = uploaded["headers"]["X-Instance-Id"]
stopped_at = time.monotonic()
subprocess.run([str(ROOT / "scripts/stop-one.sh")], cwd=ROOT,
env=dict(env, TARGET_INSTANCE_ID=target), check=True, timeout=15)
script("wait-ready.sh")
while True:
try:
response = client.call("GET", "/api/v1/attachments/" + uploaded["json"]["id"] + "/content", actor=bob)
break
except Failure:
assert time.monotonic() - stopped_at < 10, "download failover exceeded 10 seconds"
time.sleep(.1)
assert response["bytes"] == png and response["headers"]["X-Instance-Id"] != target
stopped = next(info for info in apis() if info["Config"]["Hostname"] == target)
assert not stopped["State"]["Running"]
result["upload_replica_failover"] = {"uploaded_by": target, "stopped_container": stopped["Id"],
"downloaded_by": response["headers"]["X-Instance-Id"], "sha256": hashlib.sha256(png).hexdigest(),
"recovery_seconds":round(time.monotonic()-stopped_at,3)}
compose("start", "api")
script("wait-ready.sh")
print("PASS: original downloaded through another replica after stopping uploader", flush=True)
# Незавершённое HTTP-тело не достигает S3 и не создаёт метаданных/журнала.
before = sql("SELECT (SELECT count(*) FROM attachments)||':'||(SELECT count(*) FROM attachment_uploads)")
address = urlsplit(base)
with socket.create_connection((address.hostname, address.port), timeout=3) as connection:
headers = ("POST " + upload_path + " HTTP/1.1\r\nHost: localhost\r\nAuthorization: Bearer " + alice["token"] +
"\r\nContent-Type: image/png\r\nContent-Length: 1000000\r\n\r\n").encode()
connection.sendall(headers + png[:30])
time.sleep(0.5)
assert sql("SELECT (SELECT count(*) FROM attachments)||':'||(SELECT count(*) FROM attachment_uploads)") == before
result["interrupted_body"] = {"metadata_or_journal_created": False}
# Детерминированный реальный отказ PostgreSQL ПОСЛЕ успешного S3 PUT.
sql("""CREATE FUNCTION lab4_reject_attachment() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN RAISE EXCEPTION 'injected storage failure' USING ERRCODE='08006'; END $$;
CREATE TRIGGER lab4_reject BEFORE INSERT ON attachments FOR EACH ROW EXECUTE FUNCTION lab4_reject_attachment();""")
try:
failure = client.call("POST", upload_path, 503, actor=alice, raw=png, headers={"Content-Type": "image/png"})
assert failure["json"]["error"]["code"] == "unavailable"
finally:
sql("DROP TRIGGER lab4_reject ON attachments; DROP FUNCTION lab4_reject_attachment()")
pending_key = sql("SELECT object_key FROM attachment_uploads ORDER BY created_at DESC LIMIT 1")
assert stat(pending_key)["size"] == len(png)
assert sql("SELECT count(*) FROM attachments WHERE object_key='" + pending_key + "'") == "0"
assert cleanup()["removed"] == 0
age(pending_key)
lock_code = ("from src import db; from src.attachments import lock_upload; import sys\n"
"db.pool.open(wait=True)\nwith db.connection() as c:\n"
" lock_upload(c,'" + pending_key + "'); print('locked',flush=True); sys.stdin.readline()\n"
"db.pool.close()")
holder = subprocess.Popen(["docker", "exec", "-i", apis()[0]["Id"], "python", "-u", "-c", lock_code],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
try:
assert holder.stdout.readline().strip() == "locked"
assert cleanup()["skipped_active"] == 1
assert stat(pending_key)["size"] == len(png)
finally:
holder.communicate("\n", timeout=10)
assert cleanup()["removed"] == 1
assert stat(pending_key).get("error") == "NoSuchKey"
assert cleanup()["removed"] == 0
# Даже устаревшая ошибочная запись журнала не позволяет удалить ready-файл.
sql("INSERT INTO attachment_uploads(id,object_key,created_at) VALUES ('" + str(uuid4()) + "','" + key +
"',clock_timestamp()-interval '2 hours')")
assert cleanup()["kept_ready"] == 1
assert client.call("GET", "/api/v1/attachments/" + ready["id"] + "/content", actor=bob)["bytes"] == png
result["compensation"] = {"failure_after_put":503, "orphan_recorded":True, "fresh_kept":True,
"active_locked_kept":True, "expired_removed":True, "ready_kept":True, "repeat_safe":True}
print("PASS: post-PUT DB failure recorded; cleanup protects fresh, active and ready uploads", flush=True)
try:
compose("stop", "--timeout", "8", "s3")
result["s3_outage"] = inside("""
import json,sys
from urllib.request import Request,urlopen
from urllib.error import HTTPError
data=json.load(sys.stdin)
statuses={}
for name,method,path,body in [('live','GET','/health/live',None),('ready','GET','/health/ready',None),
('download','GET','/api/v1/attachments/'+data['id']+'/content',None),
('upload','POST',data['upload'],bytes.fromhex(data['png']))]:
req=Request('http://127.0.0.1:8080'+path,data=body,method=method,
headers={'Authorization':'Bearer '+data['token'],'Content-Type':'image/png'})
try: response=urlopen(req,timeout=8)
except HTTPError as error: response=error
with response:
statuses[name]=response.status
payload=json.load(response)
if name!='live':
assert response.status==503 and payload['error']['code']=='unavailable'
assert payload['error']['request_id']==response.headers['X-Request-Id']
assert statuses['live']==200
print(json.dumps(statuses))
""", {"id":ready["id"], "token":alice["token"], "upload":upload_path, "png":png.hex()})
finally:
compose("start", "s3")
script("wait-ready.sh")
assert client.call("GET", "/api/v1/attachments/" + ready["id"] + "/content", actor=bob)["bytes"] == png
sql("UPDATE attachment_uploads SET created_at=clock_timestamp()-interval '2 hours'")
assert cleanup()["removed"] >= 1
result["s3_outage"]["original_preserved_after_recovery"] = True
print("PASS: S3 outage gives API 503; recovery preserves original and session", flush=True)
# Доказываем работу постоянного worker, а не только ручного вызова cleanup_once.
inside("import io,json; from src import object_store; "
"object_store.put('attachments/cleanup-worker-test',io.BytesIO(b'x'),1,'application/octet-stream'); print('{}')")
sql("INSERT INTO attachment_uploads(id,object_key,created_at) VALUES ('" + str(uuid4()) +
"','attachments/cleanup-worker-test',clock_timestamp()-interval '2 hours')")
compose("start", "cleanup")
deadline = time.monotonic() + 40
while sql("SELECT count(*) FROM attachment_uploads WHERE object_key='attachments/cleanup-worker-test'") != "0":
assert time.monotonic() < deadline, "automatic cleanup not running"
time.sleep(0.2)
assert stat('attachments/cleanup-worker-test').get("error") == "NoSuchKey"
result["compensation"]["automatic_worker"] = True
# 10 одновременно отправляемых реальных PNG ~5.5 MiB; монитор cgroup каждые 20 ms.
image = Image.frombytes("RGB", (1600, 1200), os.urandom(1600 * 1200 * 3))
buffer = io.BytesIO()
image.save(buffer, format="PNG")
image.close()
data = buffer.getvalue()
expected_sha = hashlib.sha256(data).hexdigest()
monitor_code = """
from pathlib import Path
import json,sys,threading,time
root=Path('/sys/fs/cgroup'); stop=threading.Event(); samples=[]
threading.Thread(target=lambda:(sys.stdin.readline(),stop.set()),daemon=True).start()
start=time.monotonic(); before=int((root/'memory.current').read_text())
print('ready',flush=True)
while not stop.is_set():
samples.append([round(time.monotonic()-start,3),int((root/'memory.current').read_text())])
stop.wait(.02)
print(json.dumps({'baseline_bytes':before,'sample_peak_bytes':max(s[1] for s in samples),
'lifetime_peak_bytes':int((root/'memory.peak').read_text()),'samples':samples}),flush=True)
"""
monitors = []
responses = []
try:
for info in apis():
process = subprocess.Popen(["docker", "exec", "-i", info["Id"], "python", "-u", "-c", monitor_code],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
assert process.stdout.readline().strip() == "ready"
monitors.append((info, process))
barrier = threading.Barrier(10)
def send(_):
concurrent_client = Client(base, timeout=60)
barrier.wait(timeout=15)
return concurrent_client.call("POST", upload_path, 201, actor=alice, raw=data,
headers={"Content-Type":"image/png"}, schema="Attachment")
started = time.monotonic()
with ThreadPoolExecutor(max_workers=10) as pool:
responses = list(pool.map(send, range(10)))
elapsed = time.monotonic() - started
finally:
memory = []
for info, process in monitors:
output, error = process.communicate("\n", timeout=10)
assert process.returncode == 0, error
measurement = json.loads(output)
measurement.update({"instance": info["Config"]["Hostname"], "limit_bytes": info["HostConfig"]["Memory"]})
assert measurement["sample_peak_bytes"] < measurement["limit_bytes"]
memory.append(measurement)
assert len(responses) == 10
assert len({r["headers"]["X-Instance-Id"] for r in responses}) >= 2
for response in responses:
assert response["json"]["sha256"] == expected_sha and response["json"]["size_bytes"] == len(data)
original = client.call("GET", "/api/v1/attachments/" + response["json"]["id"] + "/content", actor=bob)
assert hashlib.sha256(original["bytes"]).hexdigest() == expected_sha
assert all(not i["State"]["OOMKilled"] for i in apis())
timings = sorted(r["elapsed"] * 1000 for r in responses)
result["parallel_uploads"] = {"concurrency":10, "successful":10, "errors":0,
"dimensions":[1600,1200], "size_bytes":len(data), "sha256":expected_sha,
"duration_seconds":round(elapsed,3), "successful_rps":round(10/elapsed,3),
"p50_ms":round(timings[4],3), "p95_ms":round(timings[-1],3),
"memory_sample_interval_seconds":0.02, "memory_includes_monitor_process":True,
"memory":memory, "all_original_checksums_verified":True, "oom_killed":False}
print("PASS: 10 concurrent real PNG uploads; all checksums match; memory peaks:",
[m["sample_peak_bytes"] for m in memory], flush=True)
return result
finally:
compose("start", "s3", "api", "cleanup")
+319
View File
@@ -0,0 +1,319 @@
"""Проверки уровня 4 в отдельном Compose project с синтетическими данными."""
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timezone
import json
import os
import platform
import socket
import subprocess
import sys
import threading
import time
from urllib.error import HTTPError
from urllib.request import urlopen
from uuid import uuid4
from helpers import Client, ROOT
from client import Failure
from resilience import history
from attachment_checks import run_checks
from postgres_pause import check_postgres_pause
def docker(*args):
return subprocess.check_output(["docker", *args], text=True, timeout=180).strip()
def main():
with socket.socket() as sock:
sock.bind(("127.0.0.1", 0))
port = sock.getsockname()[1]
project = "lab4-check-" + uuid4().hex[:10]
base = f"http://127.0.0.1:{port}"
env = dict(os.environ, COMPOSE_PROJECT_NAME=project, HOST_PORT=str(port),
API_REPLICAS="2", SESSION_TTL_SECONDS="3600", BASE_URL=base)
result = {"utc": datetime.now(timezone.utc).isoformat(), "project": project,
"base_url": base, "host": platform.system() + " " + platform.machine(),
"docker": docker("info", "--format", "{{.ServerVersion}} {{.Architecture}} CPUs={{.NCPU}} RAM={{.MemTotal}}"),
"commit": docker("compose", "version", "--short"),
"profile": {"workers": 4, "pause_seconds": 0.05, "operation": "POST message then GET history, same-key retry after uncertain POST"}}
result["compose_version"] = result.pop("commit")
result["source_commit"] = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True).strip()
result["working_tree"] = True
def compose(*args):
return subprocess.check_output(["docker", "compose", *args], cwd=ROOT, env=env, text=True, timeout=180).strip()
def script(name):
subprocess.run([str(ROOT / "scripts" / name)], cwd=ROOT, env=env, check=True, timeout=240)
def inspect_all():
ids = compose("ps", "-a", "-q").split()
return json.loads(docker("inspect", *ids))
def apis():
return [i for i in inspect_all() if i["Config"]["Labels"]["com.docker.compose.service"] == "api"]
def metadata(info):
return {"id": info["Id"], "instance": info["Config"]["Hostname"],
"service": info["Config"]["Labels"]["com.docker.compose.service"],
"image": info["Image"], "started_at": info["State"]["StartedAt"],
"running": info["State"]["Running"], "exit_code": info["State"]["ExitCode"],
"memory_bytes": info["HostConfig"]["Memory"], "nano_cpus": info["HostConfig"]["NanoCpus"],
"published_ports": info["HostConfig"]["PortBindings"],
"mounts": [{"type": m["Type"], "destination": m["Destination"], "name": m.get("Name")} for m in info["Mounts"]]}
def sql(query):
return compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-At", "-c", query)
def check_shutdown():
info = apis()[0]
# Внутреннее подключение через docker exec не публикует порт API на хост.
pending_code = """import socket,time
s=socket.create_connection(('127.0.0.1',8080),timeout=2)
s.sendall(b'POST /api/v1/users HTTP/1.1\\r\\nHost: localhost\\r\\nContent-Type: application/json\\r\\nContent-Length: 1000\\r\\nExpect: 100-continue\\r\\n\\r\\n')
assert b'100 Continue' in s.recv(1024)
s.sendall(b'{"username":')
print('pending',flush=True)
time.sleep(30)
"""
pending = subprocess.Popen(["docker", "exec", info["Id"], "python", "-u", "-c", pending_code],
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
try:
assert pending.stdout.readline().strip() == "pending"
started = time.monotonic()
docker("kill", "--signal=TERM", info["Id"])
first_refusal = None
while True:
state = json.loads(docker("inspect", info["Id"]))[0]["State"]
if not state["Running"]:
break
assert time.monotonic() - started < 8
probe = subprocess.run(["docker", "exec", info["Id"], "python", "-c",
"import socket; s=socket.socket(); s.settimeout(.2); raise SystemExit(s.connect_ex(('127.0.0.1',8080)))"],
capture_output=True, timeout=3)
if probe.returncode and first_refusal is None:
first_refusal = time.monotonic() - started
time.sleep(0.1)
elapsed = time.monotonic() - started
assert first_refusal is not None and first_refusal < elapsed < 8
assert state["ExitCode"] == 0 and not state["OOMKilled"]
logs = subprocess.run(["docker", "logs", info["Id"]], capture_output=True, text=True, check=True)
assert "Application shutdown complete" in logs.stdout + logs.stderr
result["sigterm"] = {"instance": info["Config"]["Hostname"], "unfinished_request": True,
"shutdown_seconds": round(elapsed, 3), "new_connections_refused_seconds": round(first_refusal, 3),
"exit_code": state["ExitCode"], "oom_killed": state["OOMKilled"]}
print("PASS: SIGTERM with unfinished request:", json.dumps(result["sigterm"]), flush=True)
finally:
pending.communicate(timeout=10)
compose("start", "api")
script("wait-ready.sh")
def load_action(label, action, target=None):
client = Client(base, timeout=2)
alice, bob, _, chat = client.bootstrap()
original = client.message(alice, chat, "До воздействия")["json"]
stop = threading.Event()
lock = threading.Lock()
successes, errors, confirmed = [], [], {}
started = time.monotonic()
def worker(index):
c = Client(base, timeout=2)
key = uuid4().hex
while not stop.is_set():
for method in ("POST", "GET"):
try:
if method == "POST":
response = c.message(alice, chat, "load-" + key, key=key)
with lock:
confirmed[response["json"]["id"]] = response["json"]
key = uuid4().hex
else:
response = c.call("GET", "/api/v1/chats/" + chat["id"] + "/messages?limit=100",
actor=bob, schema="MessagePage")
with lock:
successes.append((time.monotonic() - started, method,
response["headers"]["X-Instance-Id"], response["elapsed"]))
except Failure as exc:
with lock:
errors.append((time.monotonic() - started, method, str(exc)))
stop.wait(0.05)
with ThreadPoolExecutor(max_workers=4) as pool:
futures = [pool.submit(worker, i) for i in range(4)]
time.sleep(1)
action_start = time.monotonic() - started
try:
action_info = action()
action_end = time.monotonic() - started
# Охватывает обнаружение отказа и устойчивую работу после него.
time.sleep(max(3, 15 - (action_end - action_start)))
finally:
stop.set()
for future in futures:
future.result()
elapsed = time.monotonic() - started
items = history(client, bob, chat)
by_id = {m["id"]: m for m in items}
assert len(items) == len(by_id) == len({m["text"] for m in items}), "Повтор создал дубль"
assert by_id.get(original["id"]) == original
assert all(by_id.get(mid) == msg for mid, msg in confirmed.items()), "Потеря подтверждённого сообщения"
after = [s for s in successes if s[0] >= action_end]
assert {s[1] for s in after} == {"POST", "GET"}, "Нет чтений/записей после воздействия"
recovery = {method: round(min(s[0] for s in successes if s[0] >= action_start and s[1] == method) - action_start, 3)
for method in ("POST", "GET")}
assert max(recovery.values()) <= 10, recovery
max_gap = {}
for method in ("POST", "GET"):
moments = sorted(s[0] for s in successes if s[1] == method)
max_gap[method] = round(max(b - a for a, b in zip(moments, moments[1:])), 3)
assert max(max_gap.values()) <= 10, max_gap
if target:
assert target not in {s[2] for s in after[-20:]}, "Остановленная реплика ещё отвечает"
buckets = []
for second in range(int(elapsed) + 1):
buckets.append({"second": second, "successes": sum(second <= s[0] < second + 1 for s in successes),
"errors": sum(second <= e[0] < second + 1 for e in errors)})
latencies = sorted(s[3] * 1000 for s in successes)
summary = {"label": label, "duration_seconds": round(elapsed, 3), "successful_requests": len(successes),
"successful_writes": len(confirmed), "errors": len(errors), "successful_rps": round(len(successes) / elapsed, 2),
"first_success_after_action_seconds": recovery, "maximum_success_gap_seconds": max_gap,
"action_start_seconds": round(action_start, 3), "action_end_seconds": round(action_end, 3),
"p50_ms": round(latencies[len(latencies) // 2], 3),
"p95_ms": round(latencies[int(len(latencies) * .95)], 3),
"confirmed_data_preserved": True, "duplicate_messages": 0,
"instances": sorted({s[2] for s in successes}), "per_second": buckets,
"error_samples": errors[:5], "action": action_info}
print(json.dumps({k: v for k, v in summary.items() if k not in ("per_second", "error_samples", "action")}, ensure_ascii=False), flush=True)
return summary
print("Command: ./scripts/check-docker.sh; project:", project, flush=True)
print("Docker:", result["docker"], flush=True)
try:
script("start.sh")
initial = inspect_all()
result["containers"] = [metadata(info) for info in initial]
assert len(apis()) == 2
for info in initial:
assert info["HostConfig"]["Memory"] > 0 and info["HostConfig"]["NanoCpus"] > 0
if info["Config"]["Labels"]["com.docker.compose.service"] != "lb":
assert not info["HostConfig"]["PortBindings"]
for info in apis():
assert docker("exec", info["Id"], "id", "-u") == "10001"
assert all(m["Destination"].startswith("/run/secrets/") for m in info["Mounts"])
print("PASS: 2 real API containers, CPU/RAM limits, API non-root and no public ports; only LB published", flush=True)
subprocess.run([str(ROOT / "scripts/check.sh")], cwd=ROOT, env=env, check=True, timeout=240)
result["api_tests"] = "public smoke + student unittest suite passed"
subprocess.run([str(ROOT / "scripts/demo.sh")], cwd=ROOT, env=env, check=True, stdout=subprocess.DEVNULL, timeout=30)
assert sql("SELECT count(*) FROM schema_migrations") == "3"
count = sql("SELECT count(*) FROM messages")
for _ in range(2):
compose("run", "--rm", "migrate")
assert sql("SELECT count(*) FROM schema_migrations") == "3"
assert sql("SELECT count(*) FROM messages") == count
print("PASS: migrations only in one-shot service; repeated execution preserves data", flush=True)
result["attachments"] = run_checks(base, env, compose, apis, script, sql)
replay_client = Client(base)
replay_actor, _, _, replay_chat = replay_client.bootstrap()
replay_key = uuid4().hex
saved_message = replay_client.message(replay_actor, replay_chat, "Повтор после рестарта", key=replay_key)["json"]
before = {i["Id"]: metadata(i) for i in inspect_all() if i["State"]["Running"]}
subprocess.run(["make", "test-persistence", "PYTHON=" + sys.executable, "ACTION_SCRIPT=scripts/restart.sh"],
cwd=ROOT, env=env, check=True, timeout=180)
after = {i["Id"]: metadata(i) for i in inspect_all() if i["State"]["Running"]}
assert before.keys() == after.keys()
assert all(before[cid]["started_at"] != after[cid]["started_at"] for cid in before)
assert replay_client.message(replay_actor, replay_chat, "Повтор после рестарта", key=replay_key)["json"] == saved_message
result["persistence"] = {"before": list(before.values()), "after": list(after.values()), "passed": True,
"idempotency_replay_after_restart": True}
print("PASS: both API, LB, PostgreSQL, Valkey, S3 and cleaner actually restarted; data and session preserved", flush=True)
check_shutdown()
dependency_client = Client(base)
actor = dependency_client.user("deps")
result["dependency_readiness"] = []
for dependency in ("valkey", "postgres", "s3"):
try:
compose("stop", "--timeout", "8", dependency)
probe_id = apis()[0]["Id"]
readiness = subprocess.run(["docker", "exec", probe_id, "python", "-m", "src.healthcheck"], capture_output=True, timeout=10)
assert readiness.returncode == 1
live = docker("exec", probe_id, "python", "-c",
"from urllib.request import urlopen; print(urlopen('http://127.0.0.1:8080/health/live').status)")
assert live == "200"
deadline = time.monotonic() + 8
while True:
try:
urlopen(base + "/health/ready", timeout=2).close()
except HTTPError as error:
if error.code == 503:
break
raise
except OSError:
# Уже отправленный запрос может истечь до исключения backend.
pass
assert time.monotonic() < deadline
time.sleep(0.1)
result["dependency_readiness"].append({"dependency": dependency, "api_live": 200, "api_ready": 503, "lb_ready": 503})
print("PASS:", dependency, "outage: API live=200, ready=503, LB ready=503", flush=True)
finally:
compose("start", dependency)
script("wait-ready.sh")
dependency_client.call("GET", "/api/v1/users/me", actor=actor, schema="User")
result["postgres_pause"] = check_postgres_pause(compose, apis, base)
subprocess.run(["make", "test-failover", "PYTHON=" + sys.executable, "ACTION_SCRIPT=scripts/stop-one.sh"],
cwd=ROOT, env=env, check=True, timeout=90)
assert sum(i["State"]["Running"] for i in apis()) == 1
result["public_failover"] = {"passed": True, "containers_after": [metadata(i) for i in apis()]}
compose("start", "api")
script("wait-ready.sh")
result["failovers"] = []
for info in apis():
target = info["Config"]["Hostname"]
def stop_target():
subprocess.run([str(ROOT / "scripts/stop-one.sh")], cwd=ROOT,
env=dict(env, TARGET_INSTANCE_ID=target), check=True, timeout=10)
stopped = json.loads(docker("inspect", info["Id"]))[0]
assert not stopped["State"]["Running"]
assert not stopped["State"]["OOMKilled"] and stopped["State"]["ExitCode"] == 0
# Uvicorn пишет в stderr; получаем оба потока без вывода запросов.
logs_result = subprocess.run(["docker", "logs", info["Id"]], capture_output=True, text=True, check=True)
assert "Application shutdown complete" in logs_result.stdout + logs_result.stderr
return metadata(stopped)
result["failovers"].append(load_action("stop " + target, stop_target, target))
compose("start", "api")
script("wait-ready.sh")
before = {i["Id"]: metadata(i) for i in inspect_all() if i["State"]["Running"]}
def replace():
script("rolling-update.sh")
after = {i["Id"]: metadata(i) for i in inspect_all() if i["State"]["Running"]}
old_api = {i["id"] for i in before.values() if i["service"] == "api"}
new_api = {i["id"] for i in after.values() if i["service"] == "api"}
assert len(new_api) == 2 and not old_api & new_api
for cid, info in before.items():
if info["service"] != "api":
assert after[cid]["started_at"] == info["started_at"]
return {"before": list(before.values()), "after": list(after.values())}
result["rolling_update"] = load_action("sequential API replacement", replace)
result["passed"] = True
print("PASS: all lab4 grade-4 checks completed", flush=True)
finally:
output = ROOT / "evidence" / "lab4-checks.json"
output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n")
compose("down", "--volumes", "--timeout", "8")
print("Removed only temporary test containers and volumes:", project, flush=True)
if __name__ == "__main__":
main()
+42
View File
@@ -0,0 +1,42 @@
from pathlib import Path
import sys
import unittest
from urllib.parse import urlencode
from uuid import uuid4
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client
class ApiTestCase(unittest.TestCase):
def setUp(self):
self.client = Client()
self.alice, self.bob, self.eve, self.chat = self.client.bootstrap()
self.path = "/api/v1/chats/" + self.chat["id"]
def assert_error(self, method, path, status, code, **kwargs):
if method == "POST" and path.endswith("/messages"):
kwargs["headers"] = {"Idempotency-Key": uuid4().hex, **kwargs.get("headers", {})}
result = self.client.call(method, path, status, **kwargs)
self.assertEqual(result["json"]["error"]["code"], code)
return result["json"]["error"]
def read_all(self, path, actor, schema, limit=3):
items = []
cursor = None
seen_cursors = set()
while True:
query = {"limit": limit}
if cursor is not None:
query["cursor"] = cursor
page = self.client.call("GET", path + "?" + urlencode(query), actor=actor, schema=schema)["json"]
self.assertLessEqual(len(page["items"]), limit)
items.extend(page["items"])
cursor = page["next_cursor"]
if cursor is None:
return items
self.assertTrue(page["items"], "Пустая страница не должна вести к следующей")
self.assertNotIn(cursor, seen_cursors, "Зацикливание пагинации")
seen_cursors.add(cursor)
+324
View File
@@ -0,0 +1,324 @@
"""Реальный Compose-стенд: обязательный минимум и все критерии lab5 на 4."""
from datetime import datetime, timezone
import hashlib
import io
import json
import os
from pathlib import Path
import platform
import socket
import subprocess
import sys
from tempfile import TemporaryDirectory
import time
from uuid import uuid4
from PIL import Image
from helpers import Client, ROOT
from verify_restart import verify as verify_restart
def main():
with socket.socket() as sock:
sock.bind(('127.0.0.1', 0))
port = sock.getsockname()[1]
project = 'lab5-check-' + uuid4().hex[:10]
base = 'http://127.0.0.1:' + str(port)
env = dict(os.environ, COMPOSE_PROJECT_NAME=project, HOST_PORT=str(port), BASE_URL=base,
API_REPLICAS='2', ENABLE_FAULT_INJECTION='1', JOB_TIMEOUT_SECONDS='5',
JOB_LEASE_SECONDS='15', JOB_MAX_ATTEMPTS='5', JOB_BACKOFF_SECONDS='0.15')
result = {'utc': datetime.now(timezone.utc).isoformat(), 'command': './scripts/check-docker.sh',
'project': project, 'host': platform.system() + ' ' + platform.machine(),
'source_commit': subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip(),
'working_tree': True, 'configuration': {'concurrency': 2, 'prefetch': 1, 'attempts': 5,
'timeout_seconds': 5, 'lease_seconds': 15, 'backoff_base_seconds': 0.15}, 'checks': {}}
def command(args, timeout=240, check=True):
return subprocess.run(args, cwd=ROOT, env=env, text=True, capture_output=True, timeout=timeout, check=check)
def compose(*args, timeout=240, check=True):
return command(['docker', 'compose', *args], timeout, check)
def sql(query):
return compose('exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-At', '-c', query).stdout.strip()
def worker_code(code, service='worker'):
return compose('exec', '-T', service, 'python', '-c', code).stdout.strip()
def wait(predicate, seconds=60, description='condition'):
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
value = predicate()
if value:
return value
time.sleep(0.2)
raise AssertionError('Timeout: ' + description)
def fault(job_id, point, action='crash', service='worker'):
# docker cp позволяет установить failpoint также в остановленный publisher.
container = compose('ps', '-aq', service).stdout.strip()
with TemporaryDirectory(prefix='pipeline-fault-') as directory:
source = Path(directory) / 'fault'
source.write_text(action)
source.chmod(0o644)
command(['docker', 'cp', str(source), container + ':/tmp/pipeline-faults/' + job_id + '.' + point])
def hit(job_id, point, service='worker'):
probe = compose('exec', '-T', service, 'python', '-c', 'from pathlib import Path; print(Path(' + repr('/tmp/pipeline-faults/' + job_id + '.' + point + '.hit') + ').exists())', check=False)
return probe.returncode == 0 and probe.stdout.strip() == 'True'
def job_id(att):
return sql("SELECT id FROM attachment_jobs WHERE attachment_id='" + att['id'] + "'")
def objects(att):
prefix = 'attachments/' + att['id'].replace('-', '') + '/v1/'
return json.loads(worker_code('import json; from src import object_store as s; print(json.dumps(sorted(o.object_name for o in s.client.list_objects(s.BUCKET,prefix=' + repr(prefix) + ',recursive=True))))', service='cleanup'))
def stage_exists(att):
key = sql("SELECT staging_key FROM attachment_jobs WHERE attachment_id='" + att['id'] + "'")
return int(worker_code('from src import object_store as s; print(sum(1 for o in s.client.list_objects(s.BUCKET,prefix=' + repr(key) + ',recursive=True)))', service='cleanup')) == 1
def record(name, **data):
result['checks'][name] = {'passed': True, **data}
print('PASS:', name, json.dumps(data, ensure_ascii=False), flush=True)
def metadata(att):
return client.call('GET', '/api/v1/attachments/' + att['id'], actor=alice, schema='Attachment')['json']
def status(att, wanted, seconds=60):
return wait(lambda: (value if (value := metadata(att))['status'] == wanted else None), seconds, wanted)
def upload(data=None, mime='image/png'):
return client.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=sample.png', 202,
actor=alice, raw=data or png, headers={'Content-Type': mime}, schema='Attachment')['json']
def assert_variants(att, original):
ready = status(att, 'ready')
assert {v['name'] for v in ready['variants']} == {'thumbnail', 'crop', 'optimized'}
original_response = client.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=bob)
assert original_response['bytes'] == original
assert ready['sha256'] == hashlib.sha256(original).hexdigest()
variants = {}
for variant in ready['variants']:
response = client.call('GET', '/api/v1/attachments/' + att['id'] + '/content?variant=' + variant['name'], actor=bob)
data = response['bytes']
assert len(data) == variant['size_bytes'] and hashlib.sha256(data).hexdigest() == variant['sha256']
with Image.open(io.BytesIO(data)) as image:
image.load()
assert image.size == (variant['width'], variant['height'])
assert image.format == ('WEBP' if variant['name'] == 'optimized' else 'JPEG')
assert not image.getexif()
variants[variant['name']] = {'size': list(image.size), 'bytes': len(data)}
assert len(objects(att)) == 4
return variants
def queue_payload(att):
return json.loads(worker_code('''import json
from src import db,broker
from src.storage import utc
db.pool.open(wait=True)
with db.connection() as c:
j=c.execute("SELECT * FROM attachment_jobs WHERE attachment_id=%s",(''' + repr(att['id']) + ''',)).fetchone()
payload={'schema_version':1,'job_id':str(j['id']),'attachment_id':str(j['attachment_id']),'type':'attachment.process.v1','pipeline_version':1,'attempt':j['attempt'],'created_at':utc(j['created_at'])}
print(json.dumps(payload))
db.pool.close()
'''))
def duplicate(att, count=2):
payload = queue_payload(att)
from jsonschema import Draft202012Validator, FormatChecker
Draft202012Validator(json.loads((ROOT / 'contracts/jobs.schema.json').read_text()), format_checker=FormatChecker()).validate(payload)
worker_code('import json; from src import broker; c=broker.connect(); p=' + repr(json.dumps(payload)) + '; [c.xadd(broker.STREAM,{"job":p}) for _ in range(' + str(count) + ')]')
try:
result['docker'] = command(['docker', 'info', '--format', '{{.ServerVersion}} {{.Architecture}} CPUs={{.NCPU}} RAM={{.MemTotal}}']).stdout.strip()
command([str(ROOT / 'scripts/start.sh')], timeout=300)
for service in ('worker', 'publisher'):
worker_code("from pathlib import Path; Path('/tmp/pipeline-faults').mkdir(exist_ok=True)", service)
ids = compose('ps', '-aq').stdout.split()
infos = json.loads(command(['docker', 'inspect', *ids]).stdout)
result['containers'] = [{'id': info['Id'], 'service': info['Config']['Labels']['com.docker.compose.service'],
'image': info['Config']['Image'], 'memory_bytes': info['HostConfig']['Memory'],
'nano_cpus': info['HostConfig']['NanoCpus'],
'mounts': [{'destination': m['Destination'], 'name': m.get('Name')} for m in info['Mounts']]} for info in infos]
assert sum(i['Config']['Labels']['com.docker.compose.service'] == 'api' for i in infos) == 2
for info in infos:
assert info['HostConfig']['Memory'] and info['HostConfig']['NanoCpus']
if info['Config']['Labels']['com.docker.compose.service'] != 'lb':
assert not info['HostConfig']['PortBindings']
record('topology_and_limits', api_replicas=2, broker='Valkey Streams with AOF fsync always', worker_processes=2)
public = command(['make', 'check', 'validate', 'test', 'PYTHON=' + sys.executable])
print(public.stdout, end='', flush=True)
record('public_smoke_and_schema')
unit = command([sys.executable, '-m', 'unittest', 'discover', '-s', 'student-tests', '-v'])
print(unit.stdout + unit.stderr, end='', flush=True)
record('student_api_regressions')
client = Client(base)
alice, bob, eve, chat = client.bootstrap()
png = (ROOT / 'tests/fixtures/sample.png').read_bytes()
# Worker stopped: queued already linkable; API and broker restarts preserve accepted bytes/job.
compose('stop', '--timeout', '3', 'worker')
att = upload()
assert att['status'] == 'queued' and stage_exists(att)
client.call('GET', '/api/v1/attachments/' + att['id'] + '/content', 409, actor=alice)
msg = client.message(bob, chat, '', attachments=[att['id']])['json']
jid = job_id(att)
wait(lambda: sql("SELECT published_at IS NOT NULL FROM attachment_outbox WHERE job_id='" + jid + "'") == 't')
messages = json.loads(worker_code('from src import broker; import json; c=broker.connect(); print(json.dumps([json.loads(fields["job"]) for _,fields in c.xrange(broker.STREAM)]))', service='publisher'))
from jsonschema import Draft202012Validator, FormatChecker
validator = Draft202012Validator(json.loads((ROOT / 'contracts/jobs.schema.json').read_text()), format_checker=FormatChecker())
assert messages
for payload in messages:
validator.validate(payload)
compose('restart', '--timeout', '3', 'api', 'broker')
command([str(ROOT / 'scripts/wait-ready.sh')])
assert metadata(att)['status'] == 'queued'
compose('start', 'worker')
variants = assert_variants(att, png)
assert variants['thumbnail']['size'] == [256, 160] and variants['crop']['size'] == [128, 128]
record('worker_offline_api_broker_restart', attachment_id=att['id'], job_id=jid, message_id=msg['id'], variants=variants)
# COMMIT -> publish gap and XADD -> outbox COMMIT gap, each crash is automatic.
for point in ('before_publish', 'after_publish'):
compose('stop', '--timeout', '3', 'publisher')
att = upload(); jid = job_id(att)
assert sql("SELECT published_at IS NULL FROM attachment_outbox WHERE job_id='" + jid + "'") == 't'
fault(jid, point, service='publisher')
compose('start', 'publisher')
wait(lambda: hit(jid, point, 'publisher'), description=point)
assert_variants(att, png)
record('outbox_crash_' + point, job_id=jid, automatic_recovery=True)
# Worker crash after PUT before result COMMIT and after result COMMIT before ACK.
for point in ('after_objects', 'before_ack'):
compose('stop', '--timeout', '3', 'publisher')
att = upload(); jid = job_id(att)
fault(jid, point)
compose('start', 'publisher')
wait(lambda: hit(jid, point), description=point)
assert_variants(att, png)
if point == 'after_objects':
assert int(sql("SELECT attempt FROM attachment_jobs WHERE id='" + jid + "'")) >= 2
snapshot = metadata(att)
duplicate(att, 4)
wait(lambda: worker_code('from src import broker; c=broker.connect(); print(c.xpending(broker.STREAM,broker.GROUP)["pending"])') == '0', seconds=45, description='pending ACK')
assert metadata(att) == snapshot and len(objects(att)) == 4
record('worker_crash_' + point, job_id=jid, attempt=int(sql("SELECT attempt FROM attachment_jobs WHERE id='" + jid + "'")), canonical_objects=4, duplicate_noop=True)
# Transient S3 errors, jittered backoff, exhausted registry and explicit replay.
compose('stop', '--timeout', '3', 'publisher')
att = upload(); jid = job_id(att)
fault(jid, 'before_process', 'transient:5')
compose('start', 'publisher')
status(att, 'failed')
failed = metadata(att)
assert failed['error_code'] == 'retry_exhausted'
client.call('GET', '/api/v1/attachments/' + att['id'] + '/content', 409, actor=alice)
client.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=bob,
body={'text': '', 'attachment_ids': [att['id']]}, headers={'Idempotency-Key': uuid4().hex})
registry = json.loads(compose('exec', '-T', 'worker', 'python', '-m', 'src.job_admin', 'failed').stdout)
assert any(row['job_id'] == jid for row in registry)
compose('exec', '-T', 'worker', 'python', '-m', 'src.job_admin', 'replay', jid)
assert_variants(att, png)
attempt = sql("SELECT attempt FROM attachment_jobs WHERE id='" + jid + "'")
rejected = compose('exec', '-T', 'worker', 'python', '-m', 'src.job_admin', 'replay', jid, check=False)
assert rejected.returncode != 0
assert sql("SELECT attempt FROM attachment_jobs WHERE id='" + jid + "'") == attempt
audit = json.loads(sql("SELECT json_agg(json_build_object('event',event,'attempt',attempt,'error_code',error_code,'at',created_at) ORDER BY id) FROM attachment_job_events WHERE job_id='" + jid + "'"))
record('bounded_retry_failed_registry_replay', job_id=jid, max_automatic_attempts=5, audit=audit, ready_replay_rejected=True)
# Permanent error from damaged staging: one attempt, safe code, no retry.
compose('stop', '--timeout', '3', 'publisher')
invalid = upload(); jid = job_id(invalid)
key = sql("SELECT staging_key FROM attachment_jobs WHERE id='" + jid + "'")
worker_code('import io; from src import object_store as s; s.put(' + repr(key) + ',io.BytesIO(b"bad"),3,"image/png")')
compose('start', 'publisher')
status(invalid, 'failed')
assert metadata(invalid)['error_code'] == 'invalid_image'
assert sql("SELECT attempt FROM attachment_jobs WHERE id='" + jid + "'") == '1'
record('permanent_error', job_id=jid, attempt=1, error_code='invalid_image')
# Реальные timeout и MemoryError внутри ограниченного resize subprocess.
for action, error_code in [('timeout', 'processing_timeout'), ('memory', 'resource_limit')]:
compose('stop', '--timeout', '3', 'publisher')
att = upload(); jid = job_id(att)
fault(jid, 'transform', action)
compose('start', 'publisher')
assert_variants(att, png)
assert sql("SELECT count(*) FROM attachment_job_events WHERE job_id='" + jid + "' AND error_code='" + error_code + "'") == '1'
record('image_subprocess_' + action, job_id=jid, timeout_seconds=5, task_memory_mb=640, recovered=True)
# Alpha, small input, EXIF rotation and floor rounding in real HTTP downloads.
cases = []
alpha = io.BytesIO(); Image.new('RGBA', (17, 9), (255, 0, 0, 0)).save(alpha, format='PNG')
att = upload(alpha.getvalue())
data = assert_variants(att, alpha.getvalue())
assert data['thumbnail']['size'] == [17, 9] and data['optimized']['size'] == [17, 9]
thumb = client.call('GET', '/api/v1/attachments/' + att['id'] + '/content?variant=thumbnail', actor=bob)['bytes']
with Image.open(io.BytesIO(thumb)) as image:
assert all(channel >= 250 for channel in image.getpixel((8, 4)))
cases.append({'case': 'small_alpha_on_white', 'variants': data})
photo = io.BytesIO(); exif = Image.Exif(); exif[274] = 6
Image.new('RGB', (321, 201), 'orange').save(photo, format='JPEG', exif=exif)
att = upload(photo.getvalue(), 'image/jpeg')
data = assert_variants(att, photo.getvalue())
assert data['thumbnail']['size'] == [160, 256]
cases.append({'case': 'exif_orientation_6_and_floor', 'variants': data})
record('image_semantics', cases=cases)
# Cleanup preserves active staging even if old; removes ready and expired failed.
compose('stop', '--timeout', '3', 'worker')
active = upload()
sql("UPDATE attachments SET created_at=clock_timestamp()-interval '2 days',updated_at=clock_timestamp()-interval '2 days' WHERE id='" + active['id'] + "'")
sql("UPDATE attachments SET updated_at=clock_timestamp()-interval '2 days' WHERE id='" + invalid['id'] + "'")
orphan_id = str(uuid4())
orphan_key = 'attachments/staging/' + orphan_id.replace('-', '')
sql("INSERT INTO attachment_uploads(id,object_key,created_at) VALUES ('" + orphan_id + "','" + orphan_key + "',clock_timestamp()-interval '2 days')")
worker_code('import io; from src import object_store as s; s.put(' + repr(orphan_key) + ',io.BytesIO(b"orphan"),6,"image/png")', service='cleanup')
compose('run', '--rm', '--no-deps', 'cleanup', 'python', '-m', 'src.cleanup', '--once')
assert sql("SELECT count(*) FROM attachment_uploads WHERE id='" + orphan_id + "'") == '0'
assert worker_code('from src import object_store as s; print(sum(1 for o in s.client.list_objects(s.BUCKET,prefix=' + repr(orphan_key) + ',recursive=True)))', service='cleanup') == '0'
assert stage_exists(active)
assert not stage_exists(invalid)
assert not stage_exists(att)
rejected = compose('exec', '-T', 'cleanup', 'python', '-m', 'src.job_admin', 'replay', job_id(invalid), check=False)
assert rejected.returncode != 0
compose('start', 'worker'); assert_variants(active, png)
record('staging_cleanup', active_preserved=True, orphan_removed=True, ready_removed=True, expired_failed_removed=True, expired_replay_rejected=True)
# Broker outage doesn't force synchronous resize: outbox recovers after restart.
compose('stop', '--timeout', '3', 'broker')
att = upload()
assert att['status'] == 'queued'
client.message(alice, chat, 'Broker offline; text API still works')
compose('start', 'broker'); assert_variants(att, png)
record('broker_offline_outbox', attachment_id=att['id'], recovered=True)
record('public_persistence', restart_proof=verify_restart(env))
failover = command(['make', 'test-failover', 'PYTHON=' + sys.executable, 'ACTION_SCRIPT=scripts/stop-one.sh'])
print(failover.stdout, end='', flush=True)
compose('start', 'api')
command([str(ROOT / 'scripts/wait-ready.sh')])
record('public_api_failover')
result['passed'] = True
print('PASS: all lab5 grade-4 criteria completed', flush=True)
except subprocess.CalledProcessError as error:
# Команды не содержат credentials, но runtime logs не сохраняем автоматически.
print('Command failed:', error.cmd[:4], error.returncode, flush=True)
print(error.stdout, error.stderr, flush=True)
raise
finally:
output = ROOT / 'evidence/lab5-checks.json'
output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + '\n')
if os.environ.get('KEEP_TEST_STACK') == '1' and not result.get('passed'):
print('Kept isolated failed test stack:', project, flush=True)
else:
compose('down', '--volumes', '--timeout', '5')
print('Removed isolated test stack:', project, flush=True)
if __name__ == '__main__':
main()
+145
View File
@@ -0,0 +1,145 @@
"""Пауза живой PostgreSQL: прямой readiness, ограниченное SQL I/O и восстановление."""
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timezone
import json
import os
from pathlib import Path
import socket
import subprocess
import sys
import time
from uuid import uuid4
from helpers import Client, ROOT
from client import Failure
def check_postgres_pause(compose, apis, base):
client = Client(base)
alice, bob, _, chat = client.bootstrap()
saved_message = client.message(alice, chat, "До паузы PostgreSQL")["json"]
before = {info["Id"]:info["State"]["StartedAt"] for info in apis() if info["State"]["Running"]}
probe_id = sorted(before)[0]
def direct_probe(path, expected):
# HTTP напрямую в API, без HAProxy и его собственных таймаутов/503.
code = """
import json,time
from urllib.error import HTTPError
from urllib.request import urlopen
started=time.monotonic()
try: response=urlopen('http://127.0.0.1:8080/PATH',timeout=5)
except HTTPError as error: response=error
with response:
body=json.load(response)
elapsed=time.monotonic()-started
assert response.status==EXPECTED, response.status
assert response.headers['X-Request-Id'] and response.headers['X-Instance-Id']
if response.status==503:
assert body['error']['code']=='unavailable'
assert body['error']['request_id']==response.headers['X-Request-Id']
assert elapsed<4.5, elapsed
print(json.dumps({'status':response.status,'elapsed_seconds':round(elapsed,3)}))
""".replace("PATH", path).replace("EXPECTED", str(expected))
completed = subprocess.run(["docker", "exec", probe_id, "python", "-c", code],
capture_output=True, text=True, timeout=8, check=True)
return json.loads(completed.stdout)
# Соединение получено ДО pause: проверяем именно выполняющийся SQL, а не
# только timeout получения нового соединения или check callback пула.
query_code = """
import json,sys,time
import psycopg
from src import db
db.pool.open(wait=True,timeout=10)
conn=db.pool.getconn()
conn.execute('SET statement_timeout=0')
print('connected',flush=True)
sys.stdin.readline()
started=time.monotonic()
try:
try: conn.execute('SELECT 1')
except psycopg.OperationalError:
elapsed=time.monotonic()-started
assert elapsed<4.5, elapsed
assert conn.closed, 'timed out connection was not discarded'
print(json.dumps({'elapsed_seconds':round(elapsed,3),'connection_closed':conn.closed}),flush=True)
else: raise AssertionError('paused database answered a query')
finally:
db.pool.putconn(conn)
db.pool.close()
"""
query = subprocess.Popen(["docker", "exec", "-i", probe_id, "python", "-u", "-c", query_code],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
result = {}
try:
assert query.stdout.readline().strip() == "connected"
compose("pause", "postgres")
paused_at = time.monotonic()
output, error = query.communicate("\n", timeout=10)
assert query.returncode == 0, "SQL I/O deadline failed: " + error
result["sql_without_server_timeout"] = json.loads(output)
result["direct_ready"] = direct_probe("health/ready", 503)
result["direct_live"] = direct_probe("health/live", 200)
# Повторные запросы при длительной паузе не должны оставлять занятые потоки.
with ThreadPoolExecutor(max_workers=10) as executor:
result["repeated_ready"] = list(executor.map(lambda _: direct_probe("health/ready", 503), range(10)))
# Сервер остаётся на pause не менее 12 секунд; ограничиваем именно API.
remaining = 12 - (time.monotonic() - paused_at)
if remaining > 0:
time.sleep(remaining)
result["ready_after_12_seconds"] = direct_probe("health/ready", 503)
result["live_after_repeated_requests"] = direct_probe("health/live", 200)
result["paused_seconds"] = round(time.monotonic() - paused_at, 3)
finally:
compose("unpause", "postgres")
if query.poll() is None:
query.communicate(timeout=10)
resumed_at = time.monotonic()
while True:
try:
result["recovered_ready"] = direct_probe("health/ready", 200)
client.call("GET", "/api/v1/users/me", actor=alice, schema="User")
messages = client.call("GET", "/api/v1/chats/" + chat["id"] + "/messages", actor=bob, schema="MessagePage")["json"]["items"]
assert saved_message in messages
break
except (subprocess.CalledProcessError, Failure):
assert time.monotonic() - resumed_at < 30, "readiness did not recover after unpause"
time.sleep(.2)
assert before == {info["Id"]:info["State"]["StartedAt"] for info in apis() if info["State"]["Running"]}
result.update({"recovery_seconds":round(time.monotonic()-resumed_at,3), "api_not_restarted":True,
"existing_session_and_message_preserved":True, "passed":True})
print("PASS: paused PostgreSQL: SQL and direct readiness bounded; live works; unpause restores API without restart", flush=True)
return result
def main():
with socket.socket() as listener:
listener.bind(("127.0.0.1", 0))
port = listener.getsockname()[1]
project = "lab4-pg-pause-" + uuid4().hex[:10]
base = f"http://127.0.0.1:{port}"
env = dict(os.environ, COMPOSE_PROJECT_NAME=project, HOST_PORT=str(port), API_REPLICAS="2", BASE_URL=base)
def compose(*args):
return subprocess.check_output(["docker", "compose", *args], cwd=ROOT, env=env, text=True, timeout=180).strip()
def apis():
ids = compose("ps", "-a", "-q", "api").split()
return json.loads(subprocess.check_output(["docker", "inspect", *ids], text=True))
result = {"utc":datetime.now(timezone.utc).isoformat(), "project":project,
"command":".venv/bin/python student-tests/postgres_pause.py", "passed":False}
try:
compose("up", "-d", "--no-build", "lb")
subprocess.run([str(ROOT / "scripts/wait-ready.sh")], cwd=ROOT, env=env, check=True, timeout=120)
result.update(check_postgres_pause(compose, apis, base))
print(json.dumps(result, ensure_ascii=False), flush=True)
finally:
Path(ROOT / "evidence/postgres-pause.json").write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n")
compose("down", "--volumes", "--timeout", "8")
if __name__ == "__main__":
main()
+164
View File
@@ -0,0 +1,164 @@
import base64
import json
from urllib.parse import urlencode
from uuid import uuid4
from helpers import ApiTestCase
class ApiTests(ApiTestCase):
def test_duplicate_username(self):
self.assert_error("POST", "/api/v1/users", 409, "conflict", body=self.alice["registration"])
def test_invalid_user_fields(self):
invalid_bodies = [
{}, [], None,
{"username": "ab", "display_name": "Имя"},
{"username": "UPPER", "display_name": "Имя"},
{"username": "name\n", "display_name": "Имя"},
{"username": "язык", "display_name": "Имя"},
{"username": "a" * 33, "display_name": "Имя"},
{"username": 123, "display_name": "Имя"},
{"username": "valid_name", "display_name": " \t\n"},
{"username": "valid_name", "display_name": "👋" * 101},
{"username": "valid_name", "display_name": False},
{"username": "valid_name", "display_name": "Имя", "extra": 1},
]
for body in invalid_bodies:
if isinstance(body, dict):
body = {**body, "password": "Synthetic-password-123"}
with self.subTest(body=body):
self.assert_error("POST", "/api/v1/users", 400, "invalid_request",
raw=json.dumps(body).encode(), headers={"Content-Type": "application/json"})
def test_malformed_json_and_encoding(self):
invalid_bodies = [
b'{"username":', b'', b'not JSON', b'\xff',
'{"username":"valid_name","display_name":"Имя"}'.encode("utf-16"),
b'{"username":"valid_name","display_name":"\\ud800"}',
]
for body in invalid_bodies:
with self.subTest(body=body):
self.assert_error("POST", "/api/v1/users", 400, "invalid_request",
raw=body, headers={"Content-Type": "application/json"})
def test_wrong_content_type(self):
self.assert_error("POST", "/api/v1/users", 415, "unsupported_media_type",
raw=b'{}', headers={"Content-Type": "text/plain"})
def test_identification_and_authentication_order(self):
self.assert_error("GET", "/api/v1/users/me", 401, "unauthorized")
self.assert_error("GET", "/api/v1/users/me", 401, "unauthorized",
headers={"X-User-Id": self.alice["id"]})
self.assert_error("GET", "/api/v1/users/me", 401, "unauthorized",
headers={"Authorization": "Bearer unknown-session"})
self.assert_error("POST", self.path + "/messages", 401, "unauthorized",
raw=b'{', headers={"Content-Type": "application/json"})
me = self.client.call("GET", "/api/v1/users/me", schema="User", actor=self.alice,
headers={"X-User-Id": self.bob["id"]})["json"]
self.assertEqual(me, self.alice["user"])
def test_invalid_chat_members(self):
invalid_members = [
[], [self.bob["id"]], [self.alice["id"], str(uuid4())],
[self.alice["id"], self.alice["id"]],
[self.alice["id"], self.alice["id"].upper()],
[self.alice["id"], "not-a-uuid"], [True], self.alice["id"],
[self.alice["id"]] + [str(uuid4()) for _ in range(100)],
]
for members in invalid_members:
with self.subTest(members=members):
self.assert_error("POST", "/api/v1/chats", 400, "invalid_request", actor=self.alice,
body={"title": "Чат", "member_ids": members})
chats = self.read_all("/api/v1/chats", self.alice, "ChatPage")
self.assertEqual([chat["id"] for chat in chats], [self.chat["id"]])
def test_invalid_chat_title(self):
for title in ("", " \n", "a" * 101, 123, None):
with self.subTest(title=title):
self.assert_error("POST", "/api/v1/chats", 400, "invalid_request", actor=self.alice,
body={"title": title, "member_ids": [self.alice["id"]]})
def test_chat_access(self):
outsider = self.assert_error("GET", self.path, 404, "not_found", actor=self.eve)
missing = self.assert_error("GET", "/api/v1/chats/" + str(uuid4()), 404, "not_found", actor=self.eve)
self.assertEqual(outsider["message"], missing["message"])
self.assert_error("GET", self.path + "/messages", 404, "not_found", actor=self.eve)
self.assert_error("POST", self.path + "/messages", 404, "not_found", actor=self.eve, body={"text": "Чужое"})
self.assertEqual(self.read_all("/api/v1/chats", self.eve, "ChatPage"), [])
self.assert_error("GET", "/api/v1/chats/not-a-uuid", 400, "invalid_request", actor=self.alice)
def test_invalid_message_fields(self):
for text in ("", " \t\n", "👋" * 4001, 123, True, None, []):
with self.subTest(text_type=type(text).__name__):
self.assert_error("POST", self.path + "/messages", 400, "invalid_request",
actor=self.alice, body={"text": text})
self.assert_error("POST", self.path + "/messages", 400, "invalid_request", actor=self.alice,
body={"text": "Подмена автора", "sender_id": self.bob["id"]})
self.assertEqual(self.read_all(self.path + "/messages", self.alice, "MessagePage"), [])
def test_unicode_and_text_preservation(self):
for text in (" Привет, мир 👋\n", "👋" * 4000):
message = self.client.message(self.bob, self.chat, text)["json"]
self.assertEqual(message["text"], text)
self.assertEqual(message["sender_id"], self.bob["id"])
items = self.read_all(self.path + "/messages", self.alice, "MessagePage")
self.assertEqual([item["text"] for item in items], [" Привет, мир 👋\n", "👋" * 4000])
def test_message_pagination_and_changing_limit(self):
sent = [self.client.message(self.alice, self.chat, f"Сообщение {i}")["json"] for i in range(8)]
items = self.read_all(self.path + "/messages", self.bob, "MessagePage", limit=3)
self.assertEqual(items, sorted(sent, key=lambda item: (item["created_at"], item["id"])))
first = self.client.call("GET", self.path + "/messages?limit=1", actor=self.alice, schema="MessagePage")["json"]
query = urlencode({"limit": 100, "cursor": first["next_cursor"]})
rest = self.client.call("GET", self.path + "/messages?" + query, actor=self.alice, schema="MessagePage")["json"]
self.assertEqual(first["items"] + rest["items"], items)
self.assertIsNone(rest["next_cursor"])
def test_default_page_size(self):
for i in range(51):
self.client.message(self.alice, self.chat, f"Сообщение {i}")
page = self.client.call("GET", self.path + "/messages", actor=self.alice, schema="MessagePage")["json"]
self.assertEqual(len(page["items"]), 50)
self.assertIsNotNone(page["next_cursor"])
def test_chat_pagination_and_cursor_owner(self):
for i in range(4):
self.client.call("POST", "/api/v1/chats", 201, actor=self.alice,
body={"title": f"Чат {i}", "member_ids": [self.alice["id"], self.bob["id"]]})
chats = self.read_all("/api/v1/chats", self.alice, "ChatPage", limit=2)
self.assertEqual(len(chats), 5)
self.assertEqual(len({chat["id"] for chat in chats}), 5)
self.assertEqual(chats, sorted(chats, key=lambda item: (item["created_at"], item["id"])))
first = self.client.call("GET", "/api/v1/chats?limit=1", actor=self.alice, schema="ChatPage")["json"]
query = urlencode({"cursor": first["next_cursor"]})
self.assert_error("GET", "/api/v1/chats?" + query, 400, "invalid_request", actor=self.bob)
def test_invalid_limits_and_cursors(self):
bad_queries = [{"limit": value} for value in ("0", "101", "-1", "1.5", "1.0", "abc", "")]
bad_queries += [{"cursor": value} for value in ("", "not-base64!", "e30=", "W10=")]
for path in ("/api/v1/chats", self.path + "/messages"):
for query in bad_queries:
with self.subTest(path=path, query=query):
self.assert_error("GET", path + "?" + urlencode(query), 400, "invalid_request", actor=self.alice)
def test_cursor_cannot_be_used_for_another_chat_or_changed(self):
for i in range(2):
self.client.message(self.alice, self.chat, f"Сообщение {i}")
first = self.client.call("GET", self.path + "/messages?limit=1", actor=self.alice, schema="MessagePage")["json"]
cursor = first["next_cursor"]
other = self.client.call("POST", "/api/v1/chats", 201, actor=self.alice, schema="Chat",
body={"title": "Другой чат", "member_ids": [self.alice["id"]]})["json"]
path = "/api/v1/chats/" + other["id"] + "/messages?" + urlencode({"cursor": cursor})
self.assert_error("GET", path, 400, "invalid_request", actor=self.alice)
data = json.loads(base64.urlsafe_b64decode(cursor))
data["id"] = str(uuid4())
changed = base64.urlsafe_b64encode(json.dumps(data).encode()).decode()
self.assert_error("GET", self.path + "/messages?" + urlencode({"cursor": changed}),
400, "invalid_request", actor=self.alice)
def test_framework_errors_and_request_ids(self):
first = self.assert_error("GET", "/unknown", 404, "not_found")
second = self.assert_error("GET", "/unknown", 404, "not_found")
self.assertNotEqual(first["request_id"], second["request_id"])
self.assert_error("POST", "/health/live", 405, "invalid_request")
+135
View File
@@ -0,0 +1,135 @@
import hashlib
import http.client
import io
import json
import struct
from urllib.parse import urlencode, urlsplit
from uuid import uuid4
import zlib
from PIL import Image
from helpers import ApiTestCase, ROOT
class AttachmentTests(ApiTestCase):
def upload(self, data=None, filename="photo.png", content_type="image/png", expected=202, actor=None):
if data is None:
data = (ROOT / "tests/fixtures/sample.png").read_bytes()
return self.client.call("POST", self.path + "/attachments?" + urlencode({"filename": filename}),
expected, actor=actor or self.alice, raw=data,
headers={"Content-Type": content_type}, schema="Attachment" if expected == 202 else None)
def test_png_and_jpeg_originals(self):
jpeg = io.BytesIO()
Image.new("RGB", (100, 60), "orange").save(jpeg, format="JPEG")
for data, mime, filename in (((ROOT / "tests/fixtures/sample.png").read_bytes(), "image/png", "Фото 👋.png"),
(jpeg.getvalue(), "image/jpeg", "photo.jpeg")):
with self.subTest(mime=mime):
attachment = self.upload(data, filename, mime)["json"]
self.assertEqual(attachment["filename"], filename)
self.assertEqual(attachment["status"], "queued")
attachment = self.client.wait_ready(self.bob, attachment)
self.assertEqual({v["name"] for v in attachment["variants"]}, {"thumbnail", "crop", "optimized"})
self.assertIsNone(attachment["error_code"])
self.assertEqual(attachment["sha256"], hashlib.sha256(data).hexdigest())
self.assertEqual(attachment["size_bytes"], len(data))
self.assertEqual(self.client.call("GET", "/api/v1/attachments/" + attachment["id"],
actor=self.bob, schema="Attachment")["json"], attachment)
result = self.client.call("GET", "/api/v1/attachments/" + attachment["id"] + "/content", actor=self.bob)
self.assertEqual(result["bytes"], data)
self.assertEqual(result["headers"].get_content_type(), mime)
self.assertEqual(result["headers"]["X-Content-Type-Options"], "nosniff")
def test_corruption_and_mime_spoof(self):
png = (ROOT / "tests/fixtures/sample.png").read_bytes()
for data, mime in ((png, "image/jpeg"), (png[:50], "image/png"),
(b"not an image", "image/png"), (b"", "image/png"),
(b"GIF89a", "image/png"), (png, "application/octet-stream")):
with self.subTest(size=len(data), mime=mime):
result = self.upload(data, content_type=mime, expected=415)
self.assertEqual(result["json"]["error"]["code"], "unsupported_media_type")
def test_filename_rejected_before_storage(self):
for filename in ("", " ", "../a.png", "a/b.png", "a\\b.png", "a\x00.png", "a\r\n.png", "a\x7f.png", "a" * 256):
with self.subTest(filename=repr(filename)):
result = self.upload(filename=filename, expected=400)
self.assertEqual(result["json"]["error"]["code"], "invalid_request")
self.client.call("POST", self.path + "/attachments", 400, actor=self.alice, raw=b"x",
headers={"Content-Type": "image/png"})
def test_content_length_limit_before_body(self):
self.client.call("POST", self.path + "/attachments?filename=a.png", 413, actor=self.alice,
raw=b"x", headers={"Content-Type": "image/png", "Content-Length": str(10485761)})
def test_chunked_limit_without_content_length(self):
target = urlsplit(self.client.base)
connection = http.client.HTTPConnection(target.hostname, target.port, timeout=15)
try:
connection.request("POST", self.path + "/attachments?filename=large.png",
body=iter([b"x" * 65536] * 160 + [b"x"]),
headers={"Authorization": "Bearer " + self.alice["token"], "Content-Type": "image/png"},
encode_chunked=True)
response = connection.getresponse()
self.assertEqual(response.status, 413)
self.assertEqual(json.loads(response.read())["error"]["code"], "payload_too_large")
finally:
connection.close()
def test_pixel_limit_before_decode(self):
def chunk(kind, data):
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data))
# Размеры в корректном IHDR превышают лимит; pixel data вообще не выделяется.
data = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", 10000, 4001, 8, 2, 0, 0, 0))
data += chunk(b"IDAT", b"") + chunk(b"IEND", b"")
self.upload(data, expected=413)
def test_access_and_authentication(self):
attachment = self.upload()["json"]
for suffix in ("", "/content"):
path = "/api/v1/attachments/" + attachment["id"] + suffix
self.assert_error("GET", path, 401, "unauthorized")
self.assert_error("GET", path, 404, "not_found", actor=self.eve)
self.assert_error("GET", "/api/v1/attachments/" + str(uuid4()) + suffix,
404, "not_found", actor=self.eve)
self.upload(expected=404, actor=self.eve)
self.client.call("POST", self.path + "/attachments?filename=../bad", 401,
raw=b"x", headers={"Content-Type": "image/png"})
self.client.wait_ready(self.alice, attachment)
self.assert_error("GET", "/api/v1/attachments/" + attachment["id"] + "/content?variant=missing",
404, "not_found", actor=self.alice)
def test_attachment_only_message_and_other_member(self):
attachment = self.upload()["json"]
message = self.client.message(self.bob, self.chat, "", attachments=[attachment["id"]])["json"]
self.assertEqual(message["attachment_ids"], [attachment["id"]])
self.assertEqual(message["sender_id"], self.bob["id"])
self.assertEqual(self.read_all(self.path + "/messages", self.alice, "MessagePage"), [message])
def test_foreign_and_unknown_attachment_ids(self):
attachment = self.upload()["json"]
other = self.client.call("POST", "/api/v1/chats", 201, actor=self.alice, schema="Chat",
body={"title": "Другой чат", "member_ids": [self.alice["id"]]})["json"]
for chat_id, ids in ((self.chat["id"], [str(uuid4())]), (other["id"], [attachment["id"]])):
self.assert_error("POST", "/api/v1/chats/" + chat_id + "/messages", 404, "not_found", actor=self.alice,
body={"text": "", "attachment_ids": ids})
def test_invalid_attachment_lists(self):
attachment = self.upload()["json"]
for ids in ([attachment["id"], attachment["id"].upper()], [str(uuid4()) for _ in range(11)],
["not-a-uuid"], [True], None, "uuid"):
self.assert_error("POST", self.path + "/messages", 400, "invalid_request", actor=self.alice,
body={"text": "Текст", "attachment_ids": ids})
def test_idempotency_includes_ordered_attachment_ids(self):
first, second = self.upload()["json"], self.upload()["json"]
key = uuid4().hex
ids = [first["id"], second["id"]]
saved = self.client.message(self.alice, self.chat, "", key=key, attachments=ids)["json"]
self.assertEqual(self.client.message(self.alice, self.chat, "", key=key, attachments=ids)["json"], saved)
for changed in ([second["id"], first["id"]], [first["id"]]):
self.assert_error("POST", self.path + "/messages", 409, "conflict", actor=self.alice,
body={"text": "", "attachment_ids": changed}, headers={"Idempotency-Key": key})
key = uuid4().hex
saved = self.client.message(self.alice, self.chat, "Без файла", key=key)["json"]
self.assertEqual(self.client.message(self.alice, self.chat, "Без файла", key=key, attachments=[])["json"], saved)
+47
View File
@@ -0,0 +1,47 @@
from concurrent.futures import ThreadPoolExecutor
import threading
from uuid import uuid4
from helpers import ApiTestCase, Client
class ConcurrencyTests(ApiTestCase):
def test_ten_clients_send_one_hundred_messages(self):
barrier = threading.Barrier(10)
def send_messages(worker):
client = Client()
actor = self.alice if worker % 2 == 0 else self.bob
barrier.wait(timeout=10)
sent = []
for index in range(10):
message = client.message(actor, self.chat, f"parallel-{worker}-{index}")["json"]
self.assertEqual(message["sender_id"], actor["id"])
sent.append(message)
return sent
with ThreadPoolExecutor(max_workers=10) as pool:
batches = list(pool.map(send_messages, range(10)))
sent = [message for batch in batches for message in batch]
history = self.read_all(self.path + "/messages", self.alice, "MessagePage", limit=17)
self.assertEqual(len(history), 100)
self.assertEqual(len({message["id"] for message in history}), 100)
self.assertEqual(history, sorted(sent, key=lambda item: (item["created_at"], item["id"])))
self.assertEqual({message["text"] for message in history},
{f"parallel-{worker}-{index}" for worker in range(10) for index in range(10)})
print("PASS: 10 clients sent 100 messages; history contains exactly 100 unique messages.")
def test_simultaneous_registration_of_one_username(self):
username = "race_" + uuid4().hex[:20]
barrier = threading.Barrier(10)
def register(worker):
client = Client()
barrier.wait(timeout=10)
return client.call("POST", "/api/v1/users", [201, 409],
body={"username": username, "display_name": f"Клиент {worker}", "password": "Synthetic-password-123"})["status"]
with ThreadPoolExecutor(max_workers=10) as pool:
statuses = list(pool.map(register, range(10)))
self.assertEqual(statuses.count(201), 1)
self.assertEqual(statuses.count(409), 9)
+62
View File
@@ -0,0 +1,62 @@
from concurrent.futures import ThreadPoolExecutor
import json
import threading
from uuid import uuid4
from helpers import ApiTestCase, Client
class IdempotencyTests(ApiTestCase):
def test_parallel_replay_across_replicas(self):
key = uuid4().hex
barrier = threading.Barrier(20)
def send(_):
client = Client()
barrier.wait(timeout=10)
return client.message(self.alice, self.chat, "Одно сообщение 👋", key=key)
with ThreadPoolExecutor(max_workers=20) as pool:
responses = list(pool.map(send, range(20)))
self.assertGreaterEqual(len({r["headers"]["X-Instance-Id"] for r in responses}), 2)
self.assertTrue(all(r["json"] == responses[0]["json"] for r in responses))
self.assertEqual(self.read_all(self.path + "/messages", self.bob, "MessagePage"), [responses[0]["json"]])
def test_key_format_and_missing_key(self):
for key in (None, "", " ", "a b", "a/b", "a" * 129):
with self.subTest(key=key):
headers = {} if key is None else {"Idempotency-Key": key}
self.client.call("POST", self.path + "/messages", 400, actor=self.alice,
body={"text": "Текст"}, headers=headers)
for key in ("A", "a" * 128, "ABCdef012._:-"):
self.client.message(self.alice, self.chat, key, key=key)
def test_conflict_and_semantic_json_replay(self):
key = uuid4().hex
first = self.client.message(self.alice, self.chat, "Текст 👋", key=key)["json"]
replay = self.client.call("POST", self.path + "/messages", 201, actor=self.alice,
raw=json.dumps({"text": "Текст 👋"}, ensure_ascii=True, indent=2).encode(),
headers={"Content-Type": "application/json", "Idempotency-Key": key},
schema="Message")["json"]
self.assertEqual(first, replay)
self.assert_error("POST", self.path + "/messages", 409, "conflict", actor=self.alice,
body={"text": "Другой"}, headers={"Idempotency-Key": key})
self.assertEqual(self.read_all(self.path + "/messages", self.bob, "MessagePage"), [first])
def test_scope_is_user_and_chat(self):
key = uuid4().hex
first = self.client.message(self.alice, self.chat, "Алиса", key=key)["json"]
second = self.client.message(self.bob, self.chat, "Боб", key=key)["json"]
other = self.client.call("POST", "/api/v1/chats", 201, actor=self.alice, schema="Chat",
body={"title": "Другой чат", "member_ids": [self.alice["id"]]})["json"]
third = self.client.message(self.alice, other, "Другой чат", key=key)["json"]
self.assertEqual(len({first["id"], second["id"], third["id"]}), 3)
def test_replay_rechecks_session_and_access(self):
key = uuid4().hex
self.client.message(self.alice, self.chat, "Текст", key=key)
self.client.call("POST", self.path + "/messages", 404, actor=self.eve,
body={"text": "Текст"}, headers={"Idempotency-Key": key})
self.client.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=self.alice)
self.client.call("POST", self.path + "/messages", 401, actor=self.alice,
body={"text": "Текст"}, headers={"Idempotency-Key": key})
+51
View File
@@ -0,0 +1,51 @@
import base64
from uuid import uuid4
from helpers import ApiTestCase
class SessionTests(ApiTestCase):
def basic(self, username, password):
value = base64.b64encode((username + ":" + password).encode()).decode()
return {"Authorization": "Basic " + value}
def test_wrong_password_and_basic_only_for_login(self):
registration = self.alice["registration"]
self.assert_error("POST", "/api/v1/auth/sessions", 401, "unauthorized",
headers=self.basic(registration["username"], "wrong-password"))
self.assert_error("POST", "/api/v1/auth/sessions", 401, "unauthorized")
self.assert_error("POST", "/api/v1/auth/sessions", 401, "unauthorized",
headers={"Authorization": "Basic not-base64!"})
self.assert_error("GET", "/api/v1/users/me", 401, "unauthorized",
headers=self.basic(registration["username"], registration["password"]))
def test_logout_revokes_only_one_session(self):
registration = self.alice["registration"]
second = self.client.call("POST", "/api/v1/auth/sessions", 201, schema="Session",
headers=self.basic(registration["username"], registration["password"]))["json"]
self.client.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=self.alice)
self.assert_error("GET", "/api/v1/users/me", 401, "unauthorized", actor=self.alice)
self.assert_error("DELETE", "/api/v1/auth/sessions/current", 401, "unauthorized", actor=self.alice)
self.client.call("GET", "/api/v1/users/me", schema="User", headers={"Authorization": "Bearer " + second["token"]})
def test_password_validation(self):
for password in ("short", "x" * 129, 123, None, " " * 12):
body = {"username": "pw_" + uuid4().hex[:20], "display_name": "Пароль", "password": password}
self.assert_error("POST", "/api/v1/users", 400, "invalid_request", body=body)
def test_unicode_password_with_colon_and_private_response(self):
username = "pw_" + uuid4().hex[:20]
password = "Пароль:с:двоеточием-123"
user = self.client.call("POST", "/api/v1/users", 201, schema="User",
body={"username": username, "display_name": "Пароль", "password": password})["json"]
session = self.client.call("POST", "/api/v1/auth/sessions", 201, schema="Session",
headers=self.basic(username, password))["json"]
self.assertEqual(session["user"], user)
self.assertEqual(set(user), {"id", "username", "display_name", "created_at"})
self.assertGreaterEqual(len(session["token"]), 32)
def test_sql_like_message_is_plain_text(self):
text = "'; DROP TABLE messages; -- Привет"
message = self.client.message(self.alice, self.chat, text)["json"]
self.assertEqual(message["text"], text)
self.assertEqual(self.read_all(self.path + "/messages", self.bob, "MessagePage"), [message])
+36
View File
@@ -0,0 +1,36 @@
"""Публичный persistence + доказательство реального restart каждого постоянного сервиса."""
from datetime import datetime, timezone
import json
import os
from pathlib import Path
import subprocess
import sys
ROOT = Path(__file__).resolve().parents[1]
def verify(env):
def run(*args):
return subprocess.check_output(args, cwd=ROOT, env=env, text=True, timeout=180).strip()
def snapshot():
ids = run('docker', 'compose', 'ps', '-q').split()
infos = json.loads(run('docker', 'inspect', *ids))
return {info['Id']: {'service': info['Config']['Labels']['com.docker.compose.service'],
'started_at': info['State']['StartedAt'],
'volumes': sorted(m['Name'] for m in info['Mounts'] if m['Type'] == 'volume')}
for info in infos}
before = snapshot()
print(run('make', 'test-persistence', 'PYTHON=' + sys.executable, 'ACTION_SCRIPT=scripts/restart.sh'), flush=True)
after = snapshot()
assert before.keys() == after.keys()
assert all(before[key]['started_at'] != after[key]['started_at'] for key in before)
assert all(before[key]['volumes'] == after[key]['volumes'] for key in before)
required = {'api', 'lb', 'postgres', 'valkey', 'broker', 's3', 's3-storage', 'cleanup', 'publisher', 'worker'}
assert required == {value['service'] for value in after.values()}
return {'passed': True, 'before': before, 'after': after, 'same_containers_and_volumes': True}
if __name__ == '__main__':
result = {'utc': datetime.now(timezone.utc).isoformat(), 'command': '.venv/bin/python student-tests/verify_restart.py', **verify(dict(os.environ))}
(ROOT / 'evidence/lab5-restart.json').write_text(json.dumps(result, indent=2) + '\n')
print('PASS: all persistent services actually restarted; container IDs and volumes preserved')