ЛР4: S3-вложения (SeaweedFS), приватный bucket, компенсация/reconciler, тесты, отчёт

This commit is contained in:
2026-11-06 17:11:20 +03:00
parent ec540a1a72
commit b25600adcc
62 changed files with 4196 additions and 19 deletions
+79
View File
@@ -0,0 +1,79 @@
#!/usr/bin/env python3
"""Regression check: logout must not be bypassed while Valkey is unavailable.
Scenario (the one that used to fail):
1. login and warm any session cache;
2. pause Valkey;
3. logout -> 204 (session row removed from PostgreSQL);
4. resume Valkey;
5. after the cache circuit breaker window, the old token must still be 401 on
every replica, and it must not be able to send a message.
Requires the docker CLI and a running lab3 stack.
"""
import argparse
import os
import subprocess
import sys
import time
import uuid
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "tests"))
from client import Client # noqa: E402
def _docker(*args: str) -> None:
subprocess.run(["docker", *args], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--base-url", default=os.environ.get("BASE_URL", "http://localhost:8080"))
parser.add_argument("--valkey-container", default=os.environ.get("VALKEY_CONTAINER", "messenger-lab3-valkey-1"))
parser.add_argument("--wait", type=float, default=6.0, help="seconds to wait after resuming Valkey")
args = parser.parse_args()
c = Client(args.base_url)
alice, bob, eve, chat = c.bootstrap()
# Warm the cache on both replicas.
for _ in range(6):
c.call("GET", "/api/v1/users/me", actor=alice, schema="User")
c.message(alice, chat, "warm-up before revocation")
print("Pausing Valkey (%s) ..." % args.valkey_container)
_docker("pause", args.valkey_container)
try:
logout = c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=alice)
assert logout["status"] == 204, logout["status"]
print("Logout returned 204 while the cache was unavailable.")
finally:
_docker("unpause", args.valkey_container)
print("Valkey resumed; waiting %.1fs for the cache circuit breaker ..." % args.wait)
time.sleep(args.wait)
seen = set()
for _ in range(12):
response = c.call("GET", "/api/v1/users/me", 401, actor=alice, schema="Error")
seen.add(response["headers"].get("X-Instance-Id"))
assert len(seen) >= 1, "no replica observed"
blocked = c.call(
"POST",
"/api/v1/chats/" + chat["id"] + "/messages",
401,
actor=alice,
body={"text": "must not be written"},
headers={"Idempotency-Key": uuid.uuid4().hex},
schema="Error",
)
assert blocked["status"] == 401, blocked["status"]
print(
"PASS: revoked session stays 401 through %d replica(s) and cannot post after a "
"failed cache invalidation." % len(seen)
)
if __name__ == "__main__":
main()
+115
View File
@@ -0,0 +1,115 @@
#!/usr/bin/env python3
"""S3 outage probe (grade 4): losing object storage must degrade, not crash.
* stopping S3 -> /health/ready = 503 and upload/download = 503 (bounded);
* PostgreSQL data (users/chats/messages/metadata) stays intact;
* after S3 returns the API serves uploads again.
Run from the repository root where ``docker compose`` is available.
"""
from __future__ import annotations
import base64
import json
import os
import struct
import subprocess
import time
import urllib.error
import urllib.request
import uuid
import zlib
BASE = os.environ.get("BASE_URL", "http://localhost:8080").rstrip("/")
def _png_chunk(tag, data):
return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
def make_png(width=64, height=64):
pixels = os.urandom(width * height * 3)
raw = bytearray()
for row in range(height):
raw.append(0)
raw += pixels[row * width * 3 : (row + 1) * width * 3]
ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
return b"\x89PNG\r\n\x1a\n" + _png_chunk(b"IHDR", ihdr) + _png_chunk(b"IDAT", zlib.compress(bytes(raw), 0)) + _png_chunk(b"IEND", b"")
def call(method, path, token=None, body=None, raw=None, content_type=None):
headers = {"Accept": "application/json"}
data = raw
if body is not None:
data = json.dumps(body).encode()
headers["Content-Type"] = "application/json"
if content_type:
headers["Content-Type"] = content_type
if token:
headers["Authorization"] = "Bearer " + token
request = urllib.request.Request(BASE + path, data=data, headers=headers, method=method)
try:
with urllib.request.urlopen(request, timeout=15) as response:
return response.status, response.read()
except urllib.error.HTTPError as error:
return error.code, error.read()
except (urllib.error.URLError, TimeoutError, OSError):
return 0, b""
def compose(*args):
subprocess.run(["docker", "compose", *args], check=True, stdout=subprocess.DEVNULL)
def wait_ready(expected, timeout=180.0):
deadline = time.time() + timeout
while time.time() < deadline:
if call("GET", "/health/ready")[0] == expected:
return
time.sleep(2)
raise SystemExit(f"readiness did not reach {expected}")
def main() -> None:
wait_ready(200)
username = "s3out_" + uuid.uuid4().hex[:8]
password = "T3st-" + uuid.uuid4().hex
assert call("POST", "/api/v1/users", body={"username": username, "display_name": "S3", "password": password})[0] == 201
credential = base64.b64encode(f"{username}:{password}".encode()).decode()
request = urllib.request.Request(
BASE + "/api/v1/auth/sessions",
headers={"Authorization": "Basic " + credential, "Accept": "application/json"},
method="POST",
)
with urllib.request.urlopen(request, timeout=15) as response:
token = json.loads(response.read())["token"]
user_id = json.loads(call("GET", "/api/v1/users/me", token=token)[1])["id"]
chat = json.loads(call("POST", "/api/v1/chats", token=token, body={"title": "s3", "member_ids": [user_id]})[1])
assert call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=a.png", token=token,
raw=make_png(), content_type="image/png")[0] == 201
print("baseline: upload = 201")
print("stopping s3 ...")
compose("stop", "s3")
time.sleep(3)
ready = call("GET", "/health/ready")[0]
upload = call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=b.png", token=token,
raw=make_png(), content_type="image/png")[0]
assert ready == 503, f"readiness must be 503 without S3, got {ready}"
assert upload == 503, f"upload must be a bounded 503 without S3, got {upload}"
print("s3 down: /health/ready = 503, upload = 503 (bounded)")
# PostgreSQL-backed endpoints still work.
assert call("GET", "/api/v1/users/me", token=token)[0] == 200
print("s3 down: /users/me = 200 (metadata unaffected)")
compose("start", "s3")
wait_ready(200, timeout=240)
again = call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=c.png", token=token,
raw=make_png(), content_type="image/png")[0]
assert again == 201, f"upload must recover, got {again}"
print("s3 restored: upload = 201")
print("PASS: S3 outage degrades to bounded 503 and recovers")
if __name__ == "__main__":
main()
+159
View File
@@ -0,0 +1,159 @@
#!/usr/bin/env python3
"""Grade-4 load check: >=10 concurrent uploads, bounded API memory.
Uploads N large valid PNGs in parallel through the balancer while sampling the
memory of the API replicas, then prints the measured peak. Files are generated
with the standard library only (a valid PNG with stored, not deflated, pixels).
Run from the repository root (needs the docker CLI and a running lab4 stand):
python3 scripts/check-upload-load.py --uploads 12 --megabytes 6
"""
from __future__ import annotations
import argparse
import base64
import concurrent.futures
import json
import os
import struct
import subprocess
import threading
import time
import urllib.error
import urllib.request
import uuid
import zlib
def _png_chunk(tag: bytes, data: bytes) -> bytes:
return (
struct.pack(">I", len(data))
+ tag
+ data
+ struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
)
def make_png(width: int, height: int) -> bytes:
pixels = os.urandom(width * height * 3)
raw = bytearray()
stride = width * 3
for row in range(height):
raw.append(0) # filter type 0
raw += pixels[row * stride : (row + 1) * stride]
ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
return (
b"\x89PNG\r\n\x1a\n"
+ _png_chunk(b"IHDR", ihdr)
+ _png_chunk(b"IDAT", zlib.compress(bytes(raw), 0))
+ _png_chunk(b"IEND", b"")
)
def call(base, method, path, token=None, body=None, raw=None, content_type=None):
headers = {"Accept": "application/json"}
data = raw
if body is not None:
data = json.dumps(body).encode()
headers["Content-Type"] = "application/json"
if content_type:
headers["Content-Type"] = content_type
if token:
headers["Authorization"] = "Bearer " + token
request = urllib.request.Request(base + path, data=data, headers=headers, method=method)
try:
with urllib.request.urlopen(request, timeout=60) as response:
payload = response.read()
return response.status, payload
except urllib.error.HTTPError as error:
return error.code, error.read()
def current_api_memory_mb() -> float:
out = subprocess.run(
["docker", "stats", "--no-stream", "--format", "{{.Name}}|{{.MemUsage}}"],
capture_output=True, text=True,
).stdout
total = 0.0
for line in out.splitlines():
name, _, usage = line.partition("|")
if "api" not in name:
continue
value = usage.split("/")[0].strip()
number = "".join(ch for ch in value if ch.isdigit() or ch == ".")
if value.endswith("GiB"):
total += float(number) * 1024
elif value.endswith("MiB"):
total += float(number)
elif value.endswith("KiB"):
total += float(number) / 1024
return total
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--base-url", default=os.environ.get("BASE_URL", "http://localhost:8080"))
parser.add_argument("--uploads", type=int, default=12)
parser.add_argument("--megabytes", type=int, default=6)
args = parser.parse_args()
base = args.base_url.rstrip("/")
username = "load_" + uuid.uuid4().hex[:10]
password = "T3st-" + uuid.uuid4().hex
status, _ = call(base, "POST", "/api/v1/users", body={
"username": username, "display_name": "Load", "password": password})
assert status == 201, status
credential = base64.b64encode(f"{username}:{password}".encode()).decode()
request = urllib.request.Request(
base + "/api/v1/auth/sessions",
headers={"Authorization": "Basic " + credential, "Accept": "application/json"},
method="POST",
)
with urllib.request.urlopen(request, timeout=15) as response:
token = json.loads(response.read())["token"]
status, user = call(base, "GET", "/api/v1/users/me", token=token)
user_id = json.loads(user)["id"]
status, chat_bytes = call(base, "POST", "/api/v1/chats", token=token,
body={"title": "load", "member_ids": [user_id]})
assert status == 201, status
chat_id = json.loads(chat_bytes)["id"]
side = int((args.megabytes * 1024 * 1024 / 3) ** 0.5)
payload = make_png(side, side)
print(json.dumps({"file_bytes": len(payload), "uploads": args.uploads}))
peak = {"value": current_api_memory_mb()}
stop = threading.Event()
def sampler():
while not stop.is_set():
peak["value"] = max(peak["value"], current_api_memory_mb())
time.sleep(0.2)
thread = threading.Thread(target=sampler, daemon=True)
thread.start()
started = time.time()
results = []
def upload(_):
return call(base, "POST", f"/api/v1/chats/{chat_id}/attachments?filename=load.png",
token=token, raw=payload, content_type="image/png")
with concurrent.futures.ThreadPoolExecutor(max_workers=args.uploads) as pool:
for status_code, body in pool.map(upload, range(args.uploads)):
results.append(status_code)
stop.set()
thread.join(timeout=2)
elapsed = time.time() - started
print(json.dumps({
"ok": results.count(201),
"errors": [s for s in results if s != 201],
"seconds": round(elapsed, 2),
"api_peak_mem_mb": round(peak["value"], 1),
}, ensure_ascii=False))
if __name__ == "__main__":
main()
+48
View File
@@ -0,0 +1,48 @@
#!/bin/sh
set -eu
# Generate local (gitignored) compose secrets with random credentials.
# Writes database, cache and S3 credentials plus the SeaweedFS S3 config that
# declares the limited "messenger-api" identity (separate from root).
cd "$(dirname "$0")/.."
mkdir -p secrets
BUCKET="${S3_BUCKET:-messenger-attachments}"
rand() { head -c 24 /dev/urandom | od -An -tx1 | tr -d ' \n'; }
PASSWORD=$(rand)
ROOT_KEY="root$(rand)"
ROOT_SECRET=$(rand)
API_KEY="api$(rand)"
API_SECRET=$(rand)
printf '%s' "$PASSWORD" > secrets/database_password
printf '%s' "postgresql://messenger:${PASSWORD}@postgres:5432/messenger" > secrets/database_url
printf '%s' "redis://valkey:6379/0" > secrets/cache_url
printf '%s' "$ROOT_KEY" > secrets/s3_root_access_key_id
printf '%s' "$ROOT_SECRET" > secrets/s3_root_secret_access_key
printf '%s' "$API_KEY" > secrets/s3_access_key_id
printf '%s' "$API_SECRET" > secrets/s3_secret_access_key
# The API identity may only Read/Write/List THIS bucket; root (Admin) is used
# solely by the one-shot s3-init bootstrap.
cat > secrets/s3_config.json <<EOF
{
"identities": [
{
"name": "root",
"credentials": [{"accessKey": "${ROOT_KEY}", "secretKey": "${ROOT_SECRET}"}],
"actions": ["Admin", "Read", "Write", "List", "Tagging"]
},
{
"name": "messenger-api",
"credentials": [{"accessKey": "${API_KEY}", "secretKey": "${API_SECRET}"}],
"actions": ["Read:${BUCKET}", "Write:${BUCKET}", "List:${BUCKET}"]
}
]
}
EOF
chmod 600 secrets/* 2>/dev/null || true
echo "Wrote ./secrets/{database_password,database_url,cache_url,s3_*,s3_config.json} (not committed)."
+9
View File
@@ -0,0 +1,9 @@
#!/bin/sh
set -eu
# Restart the API replicas, the balancer and ALL state stores used by this stack
# (PostgreSQL, Valkey, S3). Volumes are preserved; schema, bucket and data are
# never dropped or re-seeded. Used by:
# make test-persistence ACTION_SCRIPT=scripts/restart.sh
cd "$(dirname "$0")/.."
docker compose restart api lb postgres valkey s3
exit 0
+7
View File
@@ -0,0 +1,7 @@
#!/bin/sh
set -eu
# Restore the API service to the desired replica count after a failover test.
# Stopped replicas are started again; volumes and data are untouched.
cd "$(dirname "$0")/.."
docker compose up -d --no-recreate api
exit 0
+38
View File
@@ -0,0 +1,38 @@
#!/bin/sh
set -eu
# Sequential (rolling) replacement of the API replicas under load.
#
# The image is rebuilt once, then each running replica is stopped (the balancer
# drains it and keeps serving from the peers) and recreated from the new image.
# Before the next replica is touched we wait until every running replica is
# healthy, so the balancer always has somewhere to send traffic.
cd "$(dirname "$0")/.."
N="${API_REPLICAS:-2}"
wait_healthy() {
for _ in $(seq 1 90); do
total=$(docker compose ps -q api | wc -l)
healthy=$(docker ps --filter label=com.docker.compose.service=api --filter health=healthy --format '{{.ID}}' | wc -l)
if [ "$total" -ge "$N" ] && [ "$healthy" -ge "$total" ]; then
return 0
fi
sleep 1
done
}
echo "Building new API image..."
docker compose build api
# Wait for the current generation to be healthy before starting.
wait_healthy
for id in $(docker compose ps -q api); do
echo "Replacing replica $id ..."
docker stop -t 10 "$id" >/dev/null
docker rm "$id" >/dev/null
docker compose up -d --no-recreate api >/dev/null
wait_healthy
done
echo "Rolling update complete; all replicas healthy."
+26
View File
@@ -0,0 +1,26 @@
#!/bin/sh
set -eu
# Stop exactly ONE API replica and leave it stopped.
#
# TARGET_INSTANCE_ID is the X-Instance-Id observed by the test, which equals the
# replica's container hostname (Docker's short container id). We map it to the
# running api container and stop it with a short grace period so the hook
# returns well within the 10 second budget. PostgreSQL, Valkey and the balancer
# are never touched.
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
cd "$(dirname "$0")/.."
target=""
for id in $(docker ps --filter "label=com.docker.compose.service=api" --format '{{.ID}}'); do
case "$id" in
"$TARGET_INSTANCE_ID"*) target="$id" ;;
esac
done
if [ -z "$target" ]; then
echo "no running API replica matches X-Instance-Id=$TARGET_INSTANCE_ID" >&2
exit 1
fi
docker stop -t 5 "$target" >/dev/null
exit 0