Перенес основы lab3 в lab4
This commit is contained in:
@@ -0,0 +1,95 @@
|
||||
"""Additional Lab3 contract checks against the running stack.
|
||||
|
||||
Only synthetic data are used. --database-checks additionally expires one key
|
||||
created by this test using local Compose psql, to avoid waiting 24 hours.
|
||||
"""
|
||||
import argparse
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, check
|
||||
|
||||
|
||||
def sql(statement):
|
||||
return subprocess.run([
|
||||
"docker", "compose", "exec", "-T", "postgres", "psql", "-X", "-A", "-t",
|
||||
"-v", "ON_ERROR_STOP=1", "-U", "messenger", "-d", "messenger", "-c", statement,
|
||||
], cwd=ROOT, check=True, capture_output=True, text=True).stdout.strip()
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--base-url", default="http://127.0.0.1:8084")
|
||||
parser.add_argument("--database-checks", action="store_true")
|
||||
args = parser.parse_args()
|
||||
c = Client(args.base_url)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages"
|
||||
key = uuid.uuid4().hex
|
||||
text = "Привет, мир"
|
||||
first = c.message(alice, chat, text, key=key)["json"]
|
||||
raw = (" " + json.dumps({"text": text}, ensure_ascii=True, indent=2) + "\n").encode()
|
||||
replay = c.call("POST", path, 201, actor=alice, raw=raw,
|
||||
headers={"Content-Type": "application/json", "Idempotency-Key": key},
|
||||
schema="Message")["json"]
|
||||
check(first == replay, "Equivalent JSON changed replay result")
|
||||
for invalid in ["", "a b", "\xe9", "a" * 129]:
|
||||
c.call("POST", path, 400, actor=alice, body={"text": text},
|
||||
headers={"Idempotency-Key": invalid})
|
||||
c.message(alice, chat, "Maximum length key", key="a" * 128)
|
||||
print("PASS: decoded JSON equality; invalid keys -> 400; 128-character key accepted")
|
||||
|
||||
by_bob = c.message(bob, chat, text, key=key)["json"]
|
||||
check(by_bob["id"] != first["id"], "Different users share an idempotency result")
|
||||
other_chat = c.call("POST", "/api/v1/chats", 201, actor=alice,
|
||||
body={"title": "Scope test", "member_ids": [alice["id"]]},
|
||||
schema="Chat")["json"]
|
||||
by_chat = c.message(alice, other_chat, text, key=key)["json"]
|
||||
check(by_chat["id"] != first["id"], "Different chats share an idempotency result")
|
||||
c.call("POST", path, 404, actor=eve, body={"text": text}, headers={"Idempotency-Key": key})
|
||||
print("PASS: key scope is per user/chat; unauthorized chat replay -> 404")
|
||||
|
||||
race_key = uuid.uuid4().hex
|
||||
def conflicting(index):
|
||||
local = Client(args.base_url)
|
||||
return local.call("POST", path, [201, 409], actor=alice,
|
||||
body={"text": "race-" + str(index % 2)},
|
||||
headers={"Idempotency-Key": race_key}, schema=None)
|
||||
with ThreadPoolExecutor(max_workers=8) as pool:
|
||||
results = list(pool.map(conflicting, range(16)))
|
||||
check(sum(item["status"] == 201 for item in results) == 8, "Wrong number of winning replays")
|
||||
check(sum(item["status"] == 409 for item in results) == 8, "Wrong number of conflicts")
|
||||
check(len({item["headers"]["X-Instance-Id"] for item in results}) >= 2,
|
||||
"Conflicting race did not span replicas")
|
||||
history = c.call("GET", path + "?limit=100", actor=alice, schema="MessagePage")["json"]["items"]
|
||||
check(sum(item["text"].startswith("race-") for item in history) == 1, "Conflicting race created duplicates")
|
||||
print("PASS: concurrent different bodies -> eight 201 and eight 409; one new message")
|
||||
|
||||
if args.database_checks:
|
||||
# UUID conversion prevents server-returned IDs from becoming SQL syntax.
|
||||
actor_id = str(uuid.UUID(alice["id"]))
|
||||
chat_id = str(uuid.UUID(chat["id"]))
|
||||
where = f"user_id='{actor_id}' AND chat_id='{chat_id}' AND key='{key}'"
|
||||
check(sql("SELECT count(*) FROM message_keys WHERE " + where +
|
||||
" AND expires_at>clock_timestamp()+INTERVAL '23 hours'") == "1", "Key TTL too short")
|
||||
sql("UPDATE message_keys SET expires_at=clock_timestamp()-INTERVAL '1 second' WHERE " + where)
|
||||
after_expiry = c.message(alice, chat, "New operation after expiry", key=key)["json"]
|
||||
check(after_expiry["id"] != first["id"], "Expired key was not reusable")
|
||||
check(c.message(alice, chat, "New operation after expiry", key=key)["json"] == after_expiry,
|
||||
"New key cycle is not idempotent")
|
||||
check(sql("SELECT count(*) FROM message_keys WHERE " + where) == "1", "Key replacement duplicated row")
|
||||
print("PASS: TTL persisted; simulated expiry permits a new idempotent operation")
|
||||
|
||||
c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=alice)
|
||||
c.call("POST", path, 401, actor=alice, body={"text": text}, headers={"Idempotency-Key": key})
|
||||
print("PASS: revoked session cannot replay a previous operation")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Verify shared-store failures or short session TTL; restores stopped stores."""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, check
|
||||
|
||||
|
||||
def docker(*args):
|
||||
return subprocess.run(["docker", *args], cwd=ROOT, check=True,
|
||||
capture_output=True, text=True).stdout.strip()
|
||||
|
||||
|
||||
def status(url):
|
||||
try:
|
||||
response = urllib.request.urlopen(url, timeout=5)
|
||||
except urllib.error.HTTPError as error:
|
||||
response = error
|
||||
with response:
|
||||
return response.status
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--base-url", default="http://127.0.0.1:8084")
|
||||
parser.add_argument("--expiry", action="store_true",
|
||||
help="Requires API SESSION_TTL_SECONDS=2, configured by the operator")
|
||||
args = parser.parse_args()
|
||||
client = Client(args.base_url)
|
||||
actor = client.user("dependencies")
|
||||
client.call("GET", "/api/v1/users/me", actor=actor, schema="User")
|
||||
if args.expiry:
|
||||
time.sleep(2.3)
|
||||
aliases = set()
|
||||
for _ in range(12):
|
||||
response = client.call("GET", "/api/v1/users/me", 401, actor=actor)
|
||||
aliases.add(response["headers"]["X-Instance-Id"])
|
||||
check(len(aliases) >= 2, "Expiry not observed through two replicas")
|
||||
print("PASS: TTL=2 session rejected by both replicas without re-login")
|
||||
return
|
||||
|
||||
try:
|
||||
docker("compose", "stop", "redis")
|
||||
client.call("GET", "/api/v1/users/me", actor=actor, schema="User")
|
||||
client.call("GET", "/health/ready", schema="Health")
|
||||
print("PASS: Redis stopped; profile and readiness still return 200 via LB")
|
||||
finally:
|
||||
docker("compose", "up", "-d", "--wait", "--wait-timeout", "60", "redis")
|
||||
|
||||
try:
|
||||
docker("compose", "stop", "postgres")
|
||||
check(status(args.base_url + "/health/ready") == 503, "PostgreSQL failure did not disable readiness")
|
||||
# LB may exclude all APIs, so inspect liveness inside the Docker network.
|
||||
live = docker("compose", "exec", "-T", "redis", "wget", "-q", "-O", "-", "http://api:8080/health/live")
|
||||
check(json.loads(live) == {"status": "ok"}, "API process liveness failed")
|
||||
print("PASS: PostgreSQL stopped; LB readiness=503, API process liveness=200")
|
||||
finally:
|
||||
docker("compose", "up", "-d", "--wait", "--wait-timeout", "60")
|
||||
client.call("GET", "/api/v1/users/me", actor=actor, schema="User")
|
||||
print("PASS: PostgreSQL restored; original session still valid")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,192 @@
|
||||
"""Run the unchanged public load generator during explicit API operations.
|
||||
|
||||
Usage: python -X utf8 student-tests/operations_load.py baseline|stop1|stop2|rolling
|
||||
Only synthetic HTTP data are created. Volumes and shared stores are preserved.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
BASE = "http://127.0.0.1:8084"
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure
|
||||
|
||||
|
||||
def docker(*args):
|
||||
return subprocess.run(["docker", *args], cwd=ROOT, check=True,
|
||||
text=True, capture_output=True).stdout.strip()
|
||||
|
||||
|
||||
def containers():
|
||||
ids = docker("compose", "ps", "-q", "api").split()
|
||||
return sorted(ids, key=lambda item: docker("inspect", "--format", "{{.Name}}", item))
|
||||
|
||||
|
||||
def wait_visible(container):
|
||||
deadline = time.monotonic() + 40
|
||||
alias = None
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
if alias is None:
|
||||
alias = docker("exec", container, "/server", "instance-id")
|
||||
with urllib.request.urlopen(BASE + "/health/ready", timeout=2) as response:
|
||||
if response.headers.get("X-Instance-Id") == alias:
|
||||
return alias
|
||||
except (subprocess.CalledProcessError, urllib.error.URLError, TimeoutError):
|
||||
pass
|
||||
time.sleep(0.2)
|
||||
raise RuntimeError("API did not become visible through LB within 40 seconds")
|
||||
|
||||
|
||||
def check_data(client, actor, chat, confirmed, action_started):
|
||||
"""Verify real history reads and writes after stop, not just health."""
|
||||
deadline = action_started + 10
|
||||
key = uuid.uuid4().hex
|
||||
first_read = first_write = None
|
||||
message = None
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
history = client.call("GET", "/api/v1/chats/" + chat["id"] + "/messages?limit=100",
|
||||
actor=actor, schema="MessagePage")["json"]["items"]
|
||||
if any(item not in history for item in confirmed):
|
||||
raise RuntimeError("Confirmed probe message lost")
|
||||
if first_read is None:
|
||||
first_read = time.monotonic() - action_started
|
||||
except Failure:
|
||||
pass
|
||||
if message is None:
|
||||
try:
|
||||
message = client.message(actor, chat, "operation-probe-" + key, key=key)["json"]
|
||||
first_write = time.monotonic() - action_started
|
||||
except Failure:
|
||||
pass
|
||||
if first_read is not None and message is not None:
|
||||
confirmed.append(message)
|
||||
return {"read_recovery_seconds": round(first_read, 3),
|
||||
"write_recovery_seconds": round(first_write, 3)}
|
||||
time.sleep(0.1)
|
||||
raise RuntimeError("History/read or message/write did not recover within 10 seconds")
|
||||
|
||||
|
||||
def main():
|
||||
global BASE
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("mode", choices=["baseline", "stop1", "stop2", "rolling"])
|
||||
parser.add_argument("--base-url", default=BASE)
|
||||
parser.add_argument("--output-dir", default="evidence")
|
||||
parser.add_argument("--force-address-change", action="store_true",
|
||||
help="During rolling, briefly reserve the removed IP to verify Docker DNS updates")
|
||||
args = parser.parse_args()
|
||||
mode = args.mode
|
||||
BASE = args.base_url.rstrip("/")
|
||||
evidence_dir = ROOT / args.output_dir
|
||||
evidence_dir.mkdir(parents=True, exist_ok=True)
|
||||
original = containers()
|
||||
if len(original) != 2:
|
||||
raise RuntimeError("Exactly two running APIs required")
|
||||
for container in original:
|
||||
wait_visible(container)
|
||||
probe = Client(BASE, timeout=1)
|
||||
actor, _, _, probe_chat = probe.bootstrap()
|
||||
confirmed = [probe.message(actor, probe_chat, "confirmed-before-operation")["json"]]
|
||||
duration = 50 if mode == "rolling" else 25
|
||||
output = evidence_dir / ("load-" + mode + ".json")
|
||||
log = evidence_dir / ("load-" + mode + ".txt")
|
||||
operations = []
|
||||
# Capture timestamps independently of load.py, whose elapsed interval starts
|
||||
# after its own bootstrap. These are separate timing domains.
|
||||
started = time.monotonic()
|
||||
with log.open("w", encoding="utf-8") as stream:
|
||||
process = subprocess.Popen([
|
||||
sys.executable, "-X", "utf8", "tests/load.py", "--base-url", BASE,
|
||||
"--duration", str(duration), "--concurrency", "4", "--output", str(output),
|
||||
], cwd=ROOT, stdout=stream, stderr=subprocess.STDOUT)
|
||||
try:
|
||||
time.sleep(5)
|
||||
if process.poll() is not None:
|
||||
raise RuntimeError("Load generator stopped before operation")
|
||||
if mode.startswith("stop"):
|
||||
target = original[int(mode[-1]) - 1]
|
||||
action_started = time.monotonic()
|
||||
docker("stop", "--time", "1", target)
|
||||
recovery = check_data(probe, actor, probe_chat, confirmed, action_started)
|
||||
# Probe API availability after Docker has confirmed the stop.
|
||||
survivor = next(item for item in original if item != target)
|
||||
wait_visible(survivor)
|
||||
operations.append({"action": "stop", "container": target,
|
||||
"offset_seconds": round(action_started - started, 3),
|
||||
"stop_and_ready_seconds": round(time.monotonic() - action_started, 3),
|
||||
**recovery})
|
||||
elif mode == "rolling":
|
||||
for target in original:
|
||||
survivor = next(item for item in containers() if item != target)
|
||||
networks = json.loads(docker("inspect", "--format", "{{json .NetworkSettings.Networks}}", target))
|
||||
network_name, network = next(iter(networks.items()))
|
||||
old_ip = network["IPAddress"]
|
||||
action_started = time.monotonic()
|
||||
docker("stop", "--time", "15", target)
|
||||
recovery = check_data(probe, actor, probe_chat, confirmed, action_started)
|
||||
docker("rm", target)
|
||||
holder = None
|
||||
try:
|
||||
if args.force_address_change:
|
||||
holder = docker("run", "--rm", "-d", "--network", network_name,
|
||||
"--ip", old_ip, "--cpus", "0.05", "--memory", "16m",
|
||||
"--entrypoint", "/bin/sh", "redis:7.4.11-alpine", "-c", "sleep 120")
|
||||
# Keep the survivor intact, create only the missing replica.
|
||||
docker("compose", "up", "-d", "--no-deps", "--no-recreate", "--scale", "api=2", "api")
|
||||
current = containers()
|
||||
if survivor not in current or target in current or len(current) != 2:
|
||||
raise RuntimeError("Replacement changed survivor or did not replace target")
|
||||
replacement = next(item for item in current if item != survivor)
|
||||
new_networks = json.loads(docker("inspect", "--format", "{{json .NetworkSettings.Networks}}", replacement))
|
||||
new_ip = new_networks[network_name]["IPAddress"]
|
||||
if args.force_address_change and new_ip == old_ip:
|
||||
raise RuntimeError("Replacement did not change IP")
|
||||
alias = wait_visible(replacement)
|
||||
finally:
|
||||
if holder is not None:
|
||||
docker("rm", "-f", holder)
|
||||
operations.append({"action": "replace", "old_container": target,
|
||||
"new_container": replacement, "new_instance_alias": alias,
|
||||
"survivor_container": survivor,
|
||||
"old_ip": old_ip, "new_ip": new_ip,
|
||||
"offset_seconds": round(action_started - started, 3),
|
||||
"replacement_ready_seconds": round(time.monotonic() - action_started, 3),
|
||||
**recovery})
|
||||
if process.poll() is not None:
|
||||
raise RuntimeError("Load did not span both replacements")
|
||||
time.sleep(3)
|
||||
code = process.wait(timeout=duration + 20)
|
||||
if code != 0:
|
||||
raise RuntimeError("Load failed; inspect " + str(log))
|
||||
history = probe.call("GET", "/api/v1/chats/" + probe_chat["id"] + "/messages?limit=100",
|
||||
actor=actor, schema="MessagePage")["json"]["items"]
|
||||
if len(history) != len(confirmed) or any(item not in history for item in confirmed):
|
||||
raise RuntimeError("Final probe history lost messages or contains duplicates")
|
||||
finally:
|
||||
if process.poll() is None:
|
||||
process.terminate()
|
||||
process.wait(timeout=10)
|
||||
docker("compose", "up", "-d", "--wait", "--wait-timeout", "60")
|
||||
metadata = {
|
||||
"mode": mode, "operations": operations,
|
||||
"docker": json.loads(docker("info", "--format", '{"cpus":{{.NCPU}},"memory_bytes":{{.MemTotal}},"version":"{{.ServerVersion}}"}')),
|
||||
"confirmed_probe_messages": len(confirmed),
|
||||
"forced_address_change": args.force_address_change,
|
||||
"note": "One run per mode, concurrency 4, shared load chat, no load POST retries; separate history/write probes retry with a stable key and validate confirmed data. Replacement uses the same image and no migrations.",
|
||||
}
|
||||
(evidence_dir / ("operations-" + mode + ".json")).write_text(
|
||||
json.dumps(metadata, indent=2) + "\n", encoding="utf-8")
|
||||
print(mode + ": PASS; metrics in " + str(output.relative_to(ROOT)), flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,77 @@
|
||||
"""Check shared sessions and concurrent idempotency through the public LB only.
|
||||
|
||||
Creates synthetic data; never prints credentials or tokens.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import concurrent.futures
|
||||
import json
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
BASE = "http://127.0.0.1:8084"
|
||||
|
||||
|
||||
def request(method, path, body=None, token=None, key=None, basic=None):
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if token:
|
||||
headers["Authorization"] = "Bearer " + token
|
||||
if basic:
|
||||
headers["Authorization"] = "Basic " + base64.b64encode(basic.encode()).decode()
|
||||
if key is not None:
|
||||
headers["Idempotency-Key"] = key
|
||||
raw = None if body is None else json.dumps(body).encode()
|
||||
req = urllib.request.Request(BASE + path, data=raw, headers=headers, method=method)
|
||||
try:
|
||||
response = urllib.request.urlopen(req, timeout=15)
|
||||
except urllib.error.HTTPError as error:
|
||||
response = error
|
||||
with response:
|
||||
return response.status, json.load(response), response.headers.get("X-Instance-Id")
|
||||
|
||||
|
||||
def main():
|
||||
global BASE
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--base-url", default=BASE)
|
||||
BASE = parser.parse_args().base_url.rstrip("/")
|
||||
username = "r_" + uuid.uuid4().hex[:20]
|
||||
password = uuid.uuid4().hex
|
||||
status, user, _ = request("POST", "/api/v1/users", {
|
||||
"username": username, "display_name": "Replica test", "password": password,
|
||||
})
|
||||
assert status == 201, status
|
||||
status, session, _ = request("POST", "/api/v1/auth/sessions", basic=username + ":" + password)
|
||||
assert status == 201, status
|
||||
token = session["token"]
|
||||
instances = set()
|
||||
for _ in range(20):
|
||||
status, current, instance = request("GET", "/api/v1/users/me", token=token)
|
||||
assert status == 200 and current["id"] == user["id"]
|
||||
assert instance
|
||||
instances.add(instance)
|
||||
assert len(instances) >= 2, "Fewer than two API instances observed"
|
||||
print("PASS: one session accepted by", len(instances), "API instances")
|
||||
|
||||
status, chat, _ = request("POST", "/api/v1/chats", {
|
||||
"title": "Concurrent retries", "member_ids": [user["id"]],
|
||||
}, token=token)
|
||||
assert status == 201, status
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages"
|
||||
key = uuid.uuid4().hex
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:
|
||||
results = list(pool.map(lambda _: request("POST", path, {"text": "hello"}, token, key), range(16)))
|
||||
original = results[0][1]
|
||||
assert all(status == 201 and body == original for status, body, _ in results)
|
||||
assert len({instance for _, _, instance in results}) >= 2
|
||||
assert request("POST", path, {"text": "different"}, token, key)[0] == 409
|
||||
assert request("POST", path, {"text": "hello"}, token)[0] == 400
|
||||
status, history, _ = request("GET", path, token=token)
|
||||
assert status == 200 and history["items"] == [original]
|
||||
print("PASS: 16 parallel retries across replicas returned the same Message; history has one item")
|
||||
print("PASS: changed text -> 409; missing key -> 400")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user