Implement lab4 S3 attachments and reliability checks

This commit is contained in:
Polusikkkk
2026-11-05 18:42:22 +03:00
parent ec540a1a72
commit 0f6615dbb9
51 changed files with 6018 additions and 23 deletions
+308
View File
@@ -0,0 +1,308 @@
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
import json
from pathlib import Path
import sys
import threading
import time
import uuid
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, arguments, check, run
from resilience import history
WORKERS = 12
ROUNDS = 3
def main():
args = arguments("Concurrent cross-replica idempotency")
control = Client(
args.base_url,
args.ca_file,
timeout=10,
)
alice, bob, eve, chat = control.bootstrap()
path = f"/api/v1/chats/{chat['id']}/messages"
check(
history(control, alice, chat) == [],
"fresh test chat is not empty",
)
clients = [
Client(args.base_url, args.ca_file, timeout=10)
for _ in range(WORKERS)
]
saved_messages = []
round_results = []
first_key = None
for round_number in range(1, ROUNDS + 1):
key = uuid.uuid4().hex
text = f"Один ключ — одно сообщение: {round_number} {key}"
if first_key is None:
first_key = key
barrier = threading.Barrier(WORKERS)
def send(index):
if index % 3 == 0:
body = {"text": text}
elif index % 3 == 1:
body = {
"attachment_ids": [],
"text": text,
}
else:
body = {
"text": text,
"attachment_ids": [],
}
raw = json.dumps(
body,
ensure_ascii=False,
indent=2 if index % 2 else None,
).encode("utf-8")
barrier.wait(timeout=15)
return clients[index].call(
"POST",
path,
expected=201,
actor=alice,
raw=raw,
headers={
"Content-Type": "application/json",
"Idempotency-Key": key,
},
schema="Message",
)
started = time.monotonic()
with ThreadPoolExecutor(max_workers=WORKERS) as executor:
responses = list(executor.map(send, range(WORKERS)))
elapsed = time.monotonic() - started
original = responses[0]["json"]
check(
all(
response["json"] == original
for response in responses
),
"same key returned different Message objects",
)
instances = Counter(
response["headers"]["X-Instance-Id"]
for response in responses
)
check(
len(instances) >= 2,
"concurrent requests did not reach two replicas",
)
messages = history(control, bob, chat)
same_text = [
message
for message in messages
if message["text"] == text
]
check(
same_text == [original],
"concurrent repeats created zero or multiple messages",
)
check(
len(messages) == round_number,
"unexpected message count after concurrent round",
)
saved_messages.append(original)
result = {
"round": round_number,
"requests": WORKERS,
"responses_201": len(responses),
"observed_instances": len(instances),
"responses_by_instance": dict(instances),
"unique_message_ids": len(
{
response["json"]["id"]
for response in responses
}
),
"matching_history_messages": len(same_text),
"duration_seconds": round(elapsed, 3),
}
round_results.append(result)
print(json.dumps(result, ensure_ascii=False))
conflict = control.call(
"POST",
path,
expected=409,
actor=alice,
body={"text": "Другой текст с прежним ключом"},
headers={"Idempotency-Key": first_key},
)
check(
conflict["json"]["error"]["code"] == "conflict",
"wrong error code for body conflict",
)
control.call(
"POST",
path,
expected=400,
actor=alice,
body={"text": "Без ключа"},
)
for invalid_key in ("bad key", "x" * 129):
control.call(
"POST",
path,
expected=400,
actor=alice,
body={"text": "Некорректный ключ"},
headers={"Idempotency-Key": invalid_key},
)
control.call(
"POST",
path,
expected=404,
actor=eve,
body={"text": saved_messages[0]["text"]},
headers={"Idempotency-Key": first_key},
)
bob_message = control.message(
bob,
chat,
"Тот же ключ другого пользователя",
key=first_key,
)["json"]
check(
bob_message["sender_id"] == bob["id"],
"wrong sender for another user's scope",
)
check(
bob_message["id"] != saved_messages[0]["id"],
"key incorrectly shared between users",
)
second_chat = control.call(
"POST",
"/api/v1/chats",
expected=201,
actor=alice,
body={
"title": "Другой чат для области ключа",
"member_ids": [alice["id"], bob["id"]],
},
schema="Chat",
)["json"]
other_chat_message = control.message(
alice,
second_chat,
"Тот же ключ в другом чате",
key=first_key,
)["json"]
check(
other_chat_message["chat_id"] == second_chat["id"],
"wrong chat in scoped result",
)
check(
other_chat_message["id"] != saved_messages[0]["id"],
"key incorrectly shared between chats",
)
replay = control.message(
alice,
chat,
saved_messages[0]["text"],
key=first_key,
)["json"]
check(
replay == saved_messages[0],
"original result changed after scope tests",
)
messages = history(control, bob, chat)
expected = saved_messages + [bob_message]
check(
len(messages) == len(expected),
"unexpected final message count",
)
check(
{message["id"] for message in messages}
== {message["id"] for message in expected},
"missing or extra messages in first chat",
)
check(
history(control, bob, second_chat) == [other_chat_message],
"unexpected history in second chat",
)
control.call(
"DELETE",
"/api/v1/auth/sessions/current",
expected=204,
actor=alice,
)
control.call(
"POST",
path,
expected=401,
actor=alice,
body={"text": saved_messages[0]["text"]},
headers={"Idempotency-Key": first_key},
)
print(
json.dumps(
{
"rounds": ROUNDS,
"concurrent_requests_per_round": WORKERS,
"concurrent_requests_total": WORKERS * ROUNDS,
"body_conflict_409": True,
"missing_and_invalid_key_400": True,
"foreign_user_404": True,
"user_scope_independent": True,
"chat_scope_independent": True,
"replay_preserved": True,
"revoked_session_401": True,
"unexpected_messages": 0,
},
ensure_ascii=False,
)
)
print(
"PASS: concurrent cross-replica idempotency, "
"scope, validation and authorization checks."
)
if __name__ == "__main__":
run(main)
+284
View File
@@ -0,0 +1,284 @@
import json
from pathlib import Path
import subprocess
import sys
import time
from datetime import datetime, timezone
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, arguments, check, run
PROJECT = "mtusi2026lab3"
def timestamp():
return datetime.now(timezone.utc).isoformat()
def command(*args):
return subprocess.check_output(
list(args),
cwd=ROOT,
text=True,
timeout=45,
).strip()
def compose(*args):
return command(
"docker",
"compose",
"-p",
PROJECT,
*args,
)
def inspect(container, template):
return command(
"docker",
"inspect",
"--format",
template,
container,
)
def api_ids():
ids = compose("ps", "-q", "api").split()
return {
inspect(container, "{{.Id}}")
for container in ids
}
def healthy(container):
return inspect(
container,
"{{.State.Running}} {{.State.Health.Status}}",
) == "true healthy"
def instance_id(container):
code = (
"import urllib.request; "
"r=urllib.request.urlopen("
"'http://127.0.0.1:8080/health/live', timeout=2); "
"print(r.headers.get('X-Instance-Id', '')); "
"r.close()"
)
return command(
"docker",
"exec",
container,
"python",
"-c",
code,
)
def main():
args = arguments("Sequential API container replacement")
client = Client(
args.base_url,
args.ca_file,
timeout=2,
)
alice, bob, eve, chat = client.bootstrap()
import uuid
key = uuid.uuid4().hex
text = "Сохранить при замене " + key
original_message = client.message(
alice,
chat,
text,
key=key,
)["json"]
original_ids = sorted(api_ids())
check(len(original_ids) == 2, "expected exactly two API containers")
for container in original_ids:
check(healthy(container), "both API containers must be healthy")
print(
json.dumps(
{
"event": "replacement_started",
"utc": timestamp(),
"original_container_ids": original_ids,
},
ensure_ascii=False,
),
flush=True,
)
replacements = []
for old in original_ids:
current = api_ids()
check(len(current) == 2, "expected two APIs before replacement")
check(old in current, "original target container is missing")
other = next(container for container in current if container != old)
check(healthy(other), "remaining API is not healthy")
other_started = inspect(other, "{{.State.StartedAt}}")
old_instance = instance_id(old)
step_started = time.monotonic()
print(
json.dumps(
{
"event": "replacing",
"utc": timestamp(),
"old_container_id": old,
"old_instance": old_instance,
"remaining_container_id": other,
},
ensure_ascii=False,
),
flush=True,
)
command("docker", "stop", "--time", "10", old)
command("docker", "rm", old)
compose(
"up",
"-d",
"--no-deps",
"--no-recreate",
"--no-build",
"--scale",
"api=2",
"api",
)
deadline = time.monotonic() + 30
replacement = None
while time.monotonic() < deadline:
current = api_ids()
candidates = current - {other}
if (
len(current) == 2
and len(candidates) == 1
and other in current
):
candidate = next(iter(candidates))
if candidate != old and healthy(candidate):
replacement = candidate
break
time.sleep(0.5)
check(replacement is not None, "replacement did not become healthy")
new_instance = instance_id(replacement)
check(new_instance != old_instance, "instance did not change")
seen_through_lb = False
deadline = time.monotonic() + 20
while time.monotonic() < deadline:
try:
response = client.call(
"GET",
"/api/v1/users/me",
actor=alice,
schema="User",
)
except Failure:
time.sleep(0.2)
continue
if response["headers"]["X-Instance-Id"] == new_instance:
seen_through_lb = True
break
time.sleep(0.2)
check(
seen_through_lb,
"new API was not observed through LB with existing session",
)
check(healthy(other), "remaining API became unhealthy")
check(
inspect(other, "{{.State.StartedAt}}") == other_started,
"the other API was restarted unexpectedly",
)
replay = client.message(
alice,
chat,
text,
key=key,
)["json"]
check(
replay == original_message,
"confirmed message or idempotency result changed",
)
result = {
"event": "replacement_ready",
"utc": timestamp(),
"old_container_id": old,
"new_container_id": replacement,
"old_instance": old_instance,
"new_instance": new_instance,
"step_seconds": round(
time.monotonic() - step_started, 3
),
"other_api_not_restarted": True,
"existing_session_works": True,
"replay_preserved": True,
}
replacements.append(result)
print(json.dumps(result, ensure_ascii=False), flush=True)
time.sleep(3)
final_ids = api_ids()
check(len(final_ids) == 2, "expected two APIs after replacement")
check(
not final_ids.intersection(original_ids),
"some original API containers were not replaced",
)
for container in final_ids:
check(healthy(container), "final API is not healthy")
print(
json.dumps(
{
"event": "replacement_finished",
"utc": timestamp(),
"replacements": len(replacements),
"final_container_ids": sorted(final_ids),
},
ensure_ascii=False,
),
flush=True,
)
print(
"PASS: both API containers replaced sequentially; "
"existing session and confirmed message preserved.",
flush=True,
)
if __name__ == "__main__":
run(main)
+318
View File
@@ -0,0 +1,318 @@
#!/usr/bin/env python3
"""Targeted API failure test. Uses synthetic data; leaves target stopped."""
import json
import os
from pathlib import Path
import subprocess
import sys
import time
import uuid
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, arguments, check, run
from resilience import history
PROJECT = "mtusi2026lab3"
def docker_output(*args):
return subprocess.check_output(
["docker", *args],
cwd=ROOT,
text=True,
).strip()
def target_instance(container):
labels = json.loads(
docker_output(
"inspect",
"--format",
"{{json .Config.Labels}}",
container,
)
)
check(
labels.get("com.docker.compose.project") == PROJECT,
"target belongs to another Compose project",
)
check(
labels.get("com.docker.compose.service") == "api",
"target is not an API container",
)
check(
docker_output(
"inspect",
"--format",
"{{.State.Running}}",
container,
) == "true",
"target container is not running",
)
code = (
"import urllib.request; "
"r=urllib.request.urlopen("
"'http://127.0.0.1:8080/health/live', timeout=2); "
"print(r.headers.get('X-Instance-Id', '')); "
"r.close()"
)
instance = docker_output(
"exec", container, "python", "-c", code
)
check(bool(instance), "target has no X-Instance-Id")
return instance
def main():
def configure(parser):
parser.add_argument(
"--target-container",
required=True,
)
args = arguments(
"Targeted API failover through the load balancer",
configure,
)
script = ROOT / "scripts" / "stop-one.sh"
check(
script.is_file() and os.access(script, os.X_OK),
"stop-one.sh must exist and be executable",
)
target = target_instance(args.target_container)
client = Client(args.base_url, args.ca_file, timeout=2)
alice, bob, eve, chat = client.bootstrap()
original_key = uuid.uuid4().hex
original_text = "Подтверждено до отказа " + original_key
original = client.message(
alice,
chat,
original_text,
key=original_key,
)["json"]
observed = set()
for _ in range(40):
response = client.call(
"GET",
"/api/v1/users/me",
actor=alice,
schema="User",
)
observed.add(response["headers"]["X-Instance-Id"])
check(len(observed) >= 2, "less than two API instances")
check(target in observed, "target is not observed through LB")
env = dict(os.environ)
env["TARGET_INSTANCE_ID"] = target
print(
"Target container:",
args.target_container,
"| instance:",
target,
flush=True,
)
started = time.monotonic()
proc = subprocess.Popen(
[str(script)],
cwd=ROOT,
env=env,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
successes = []
write_failures = 0
read_successes = 0
read_failures = 0
after_instances = []
first_recovery = None
attempts = 0
key = uuid.uuid4().hex
text = "Во время отказа " + key
try:
while time.monotonic() - started < 15:
code = proc.poll()
elapsed = time.monotonic() - started
check(
code is None or code == 0,
"stop-one hook failed",
)
check(
code is not None or elapsed < 10,
"stop-one hook exceeded 10 seconds",
)
attempts += 1
try:
response = client.message(
alice,
chat,
text,
key=key,
)
except Failure:
write_failures += 1
# Keep the same key and text after uncertain POST.
else:
successes.append(response["json"])
if proc.poll() == 0:
if first_recovery is None:
first_recovery = time.monotonic() - started
after_instances.append(
response["headers"]["X-Instance-Id"]
)
key = uuid.uuid4().hex
text = "Во время отказа " + key
if attempts % 5 == 0:
try:
page = client.call(
"GET",
(
"/api/v1/chats/"
+ chat["id"]
+ "/messages?limit=100"
),
actor=bob,
schema="MessagePage",
)["json"]
except Failure:
read_failures += 1
else:
check(
any(
message == original
for message in page["items"]
),
"confirmed message absent during read",
)
read_successes += 1
time.sleep(0.1)
elapsed = time.monotonic() - started
check(proc.poll() == 0, "stop-one hook did not finish")
check(
first_recovery is not None and first_recovery <= 10,
"writes did not recover within 10 seconds",
)
check(
len(after_instances) >= 5,
"too few writes after stop",
)
check(
target not in after_instances[-5:],
"stopped instance still serves requests",
)
check(read_successes > 0, "no successful history reads")
check(
docker_output(
"inspect",
"--format",
"{{.State.Running}}",
args.target_container,
) == "false",
"target container is still running",
)
replay = client.message(
alice,
chat,
original_text,
key=original_key,
)["json"]
check(
replay == original,
"replay after failure returned another message",
)
messages = history(client, bob, chat)
by_id = {message["id"]: message for message in messages}
check(
len(by_id) == len(messages),
"duplicate message IDs",
)
check(
by_id.get(original["id"]) == original,
"pre-failure message lost or altered",
)
for message in successes:
check(
by_id.get(message["id"]) == message,
"confirmed in-flight message lost or altered",
)
texts = [message["text"] for message in messages]
check(
len(texts) == len(set(texts)),
"retry created duplicate message text",
)
print(
json.dumps(
{
"target_container": args.target_container,
"target_instance": target,
"observed_instances_before": len(observed),
"duration_seconds": round(elapsed, 3),
"successful_writes": len(successes),
"failed_write_attempts": write_failures,
"successful_reads": read_successes,
"failed_read_attempts": read_failures,
"successful_write_rps": round(
len(successes) / elapsed, 3
),
"first_recovery_seconds": round(
first_recovery, 3
),
"replay_preserved": True,
"target_stopped": True,
},
ensure_ascii=False,
)
)
print(
"PASS: targeted failover; session, messages "
"and replay preserved. Target remains stopped."
)
finally:
if proc.poll() is None:
proc.terminate()
try:
proc.wait(timeout=5)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait()
if __name__ == "__main__":
run(main)