feat: add HAproxy and 2 api instances
This commit is contained in:
@@ -68,13 +68,15 @@ def main():
|
||||
token,
|
||||
)
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages"
|
||||
key = secrets.token_hex(16)
|
||||
body = {"text": "Перенос из лабораторной 2"}
|
||||
message = call(
|
||||
"POST",
|
||||
path,
|
||||
201,
|
||||
{"text": "Перенос из лабораторной 2"},
|
||||
body,
|
||||
token,
|
||||
{"Idempotency-Key": secrets.token_hex(16)},
|
||||
{"Idempotency-Key": key},
|
||||
)
|
||||
assert call("GET", path, token=bob_token)["items"] == [message]
|
||||
call("GET", "/api/v1/users/me", 401)
|
||||
@@ -84,11 +86,13 @@ def main():
|
||||
subprocess.run(["make", "app-up"], cwd=root, check=True)
|
||||
assert call("GET", "/api/v1/users/me", token=token) == alice
|
||||
assert call("GET", path, token=bob_token)["items"] == [message]
|
||||
assert call("POST", path, 201, body, token, {"Idempotency-Key": key}) == message
|
||||
assert call("GET", path, token=bob_token)["items"] == [message]
|
||||
call("DELETE", "/api/v1/auth/sessions/current", 204, token=token)
|
||||
call("GET", "/api/v1/users/me", 401, token=token)
|
||||
print(
|
||||
"PASS: transferred API, shared sessions, chat, message, logout"
|
||||
+ (", persistence across app-down/app-up" if args.restart else "")
|
||||
+ (", persistence and idempotent replay across app-down/app-up" if args.restart else "")
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
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
|
||||
|
||||
COMPOSE = ["docker", "compose", "--project-name", "highload-lab3", "--env-file", ".env", "-f", "compose.yml"]
|
||||
|
||||
|
||||
def inspect(container):
|
||||
# Deliberately inspect only public identity/state, not credentials or env.
|
||||
raw = subprocess.check_output(["docker", "inspect", "--format",
|
||||
'{{json .Config.Hostname}} {{json .State.Status}}', container], text=True)
|
||||
hostname, state = raw.strip().split()
|
||||
return json.loads(hostname), json.loads(state)
|
||||
|
||||
|
||||
def restore():
|
||||
subprocess.run(COMPOSE + ["up", "-d", "--wait", "--no-deps", "api"], cwd=ROOT, check=True)
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments(__doc__)
|
||||
c = Client(args.base_url, args.ca_file, timeout=2)
|
||||
containers = subprocess.check_output(COMPOSE + ["ps", "-q", "api"], cwd=ROOT, text=True).split()
|
||||
check(len(containers) >= 2, "need at least two running API containers")
|
||||
targets = [(container, inspect(container)[0]) for container in containers]
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
records = []
|
||||
for container, target in targets:
|
||||
# Read through the LB using one existing session until all replicas rejoin.
|
||||
seen = set()
|
||||
deadline = time.monotonic() + 10
|
||||
while len(seen) < len(targets) and time.monotonic() < deadline:
|
||||
seen.add(c.call("GET", "/api/v1/users/me", actor=alice, schema="User")["headers"]["X-Instance-Id"])
|
||||
time.sleep(0.05)
|
||||
check(target in seen and len(seen) >= 2, "restored replica is not serving through HAProxy")
|
||||
confirmed_key = uuid.uuid4().hex
|
||||
confirmed_text = "Before failure " + confirmed_key
|
||||
original = c.message(alice, chat, confirmed_text, key=confirmed_key)["json"]
|
||||
env = dict(os.environ, TARGET_INSTANCE_ID=target)
|
||||
started = time.monotonic()
|
||||
proc = subprocess.Popen([str(ROOT / "scripts" / "stop-one.sh")], cwd=ROOT, env=env,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
successes, last_instances = [], []
|
||||
write_errors = read_errors = reads = 0
|
||||
first_write = first_read = None
|
||||
key = uuid.uuid4().hex
|
||||
try:
|
||||
while time.monotonic() - started < 15:
|
||||
check(proc.poll() in (None, 0), "stop-one hook failed")
|
||||
try:
|
||||
result = c.message(alice, chat, "During failure " + key, key=key)
|
||||
successes.append(result["json"])
|
||||
if proc.poll() == 0:
|
||||
last_instances.append(result["headers"]["X-Instance-Id"])
|
||||
if first_write is None:
|
||||
first_write = time.monotonic() - started
|
||||
key = uuid.uuid4().hex
|
||||
except Failure:
|
||||
write_errors += 1 # Retry the SAME key and text on the next iteration.
|
||||
try:
|
||||
c.call("GET", "/api/v1/chats/" + chat["id"] + "/messages", actor=bob, schema="MessagePage")
|
||||
reads += 1
|
||||
if proc.poll() == 0 and first_read is None:
|
||||
first_read = time.monotonic() - started
|
||||
except Failure:
|
||||
read_errors += 1
|
||||
time.sleep(0.1)
|
||||
check(proc.poll() == 0, "stop-one hook did not finish")
|
||||
check(inspect(container)[1] == "exited", "target container did not stay stopped")
|
||||
check(first_write is not None and first_write <= 10, "writes did not recover within 10 seconds")
|
||||
check(first_read is not None and first_read <= 10, "reads did not recover within 10 seconds")
|
||||
check(len(last_instances) >= 5 and target not in last_instances[-5:], "stopped replica still serves responses")
|
||||
check(c.message(alice, chat, confirmed_text, key=confirmed_key)["json"] == original,
|
||||
"replay after switching replicas changed a confirmed message")
|
||||
messages = history(c, bob, chat)
|
||||
check(all(message in messages for message in [original] + successes), "confirmed message lost")
|
||||
texts = [message["text"] for message in messages]
|
||||
check(len(texts) == len(set(texts)), "uncertain retry created a duplicate")
|
||||
record = {"stopped_instance": target, "container_state": "exited", "successful_writes": len(successes),
|
||||
"successful_reads": reads, "write_errors": write_errors, "read_errors": read_errors,
|
||||
"first_write_seconds": round(first_write, 3), "first_read_seconds": round(first_read, 3)}
|
||||
records.append(record)
|
||||
print(json.dumps(record), flush=True)
|
||||
finally:
|
||||
if proc.poll() is None:
|
||||
proc.terminate()
|
||||
proc.wait(timeout=5)
|
||||
restore()
|
||||
print("PASS: each API replica stopped in turn; reads, writes, sessions and confirmed messages preserved")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,65 @@
|
||||
import json
|
||||
import sys
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
from threading import Barrier
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments(__doc__)
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages"
|
||||
observed = {
|
||||
c.call("GET", "/api/v1/users/me", actor=alice, schema="User")["headers"]["X-Instance-Id"]
|
||||
for _ in range(40)
|
||||
}
|
||||
check(len(observed) >= 2, "same session did not reach two API replicas")
|
||||
|
||||
key = uuid.uuid4().hex
|
||||
text = "Один ключ через разные реплики 👋"
|
||||
concurrency = 24
|
||||
start = Barrier(concurrency)
|
||||
|
||||
def send(_):
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
start.wait(timeout=15)
|
||||
return client.message(alice, chat, text, key=key)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=concurrency) as pool:
|
||||
replies = list(pool.map(send, range(concurrency)))
|
||||
original = replies[0]["json"]
|
||||
instances = {reply["headers"]["X-Instance-Id"] for reply in replies}
|
||||
check(len(instances) >= 2, "concurrent POST did not reach different API replicas")
|
||||
check(all(reply["json"] == original for reply in replies), "concurrent replay changed the response")
|
||||
history = c.call("GET", path, actor=bob, schema="MessagePage")["json"]["items"]
|
||||
check(history == [original], "concurrent POST created a duplicate")
|
||||
check(c.message(alice, chat, text, key=key, attachments=[])["json"] == original, "empty attachment_ids changed replay")
|
||||
reordered = c.call("POST", path, 201, actor=alice,
|
||||
raw=json.dumps({"attachment_ids": [], "text": text}, ensure_ascii=False).encode(),
|
||||
headers={"Content-Type": "application/json", "Idempotency-Key": key}, schema="Message")["json"]
|
||||
check(reordered == original, "JSON key order changed replay")
|
||||
c.call("POST", path, 409, actor=alice, body={"text": "другое тело"}, headers={"Idempotency-Key": key})
|
||||
c.call("POST", path, 400, actor=alice, body={"text": text})
|
||||
for invalid in ("bad key", "x" * 129, "invalid/key", ""):
|
||||
c.call("POST", path, 400, actor=alice, body={"text": text}, headers={"Idempotency-Key": invalid})
|
||||
c.call("POST", path, 400, actor=alice, body={"text": text, "extra": 1}, headers={"Idempotency-Key": key})
|
||||
c.call("POST", path, 404, actor=eve, body={"text": text}, headers={"Idempotency-Key": key})
|
||||
other_sender = c.message(bob, chat, text, key=key)["json"]
|
||||
check(other_sender["id"] != original["id"], "key scope does not include sender")
|
||||
other_chat = c.call("POST", "/api/v1/chats", 201, actor=alice,
|
||||
body={"title": "Other scope", "member_ids": [alice["id"]]}, schema="Chat")["json"]
|
||||
check(c.message(alice, other_chat, text, key=key)["json"]["id"] != original["id"], "key scope does not include chat")
|
||||
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(json.dumps({"concurrent_requests": concurrency, "observed_instances": sorted(instances),
|
||||
"messages_after_concurrent_repeat": len(history)}, ensure_ascii=False))
|
||||
print("PASS: shared session, concurrent replay across replicas, key/body validation, independent scopes, reauthentication on replay")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,16 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
: "${TARGET_INSTANCE_ID:?Set TARGET_INSTANCE_ID to the X-Instance-Id of an API replica}"
|
||||
for container in $(docker compose --project-name highload-lab3 --env-file .env -f compose.yml ps -q api); do
|
||||
hostname=$(docker inspect --format '{{.Config.Hostname}}' "$container")
|
||||
if [ "$hostname" = "$TARGET_INSTANCE_ID" ]; then
|
||||
# Only containers from this Compose project's api service are eligible.
|
||||
docker stop --timeout 8 "$container" >/dev/null
|
||||
printf 'Stopped API instance %s\n' "$hostname"
|
||||
exit 0
|
||||
fi
|
||||
done
|
||||
printf 'No running API replica matches TARGET_INSTANCE_ID\n' >&2
|
||||
exit 1
|
||||
Reference in New Issue
Block a user