Выполнить лабораторную 3: балансировка, отказы и исследование масштабирования
This commit is contained in:
@@ -0,0 +1,157 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Research track: cache consistency and stale session protection for Valkey-backed sessions."""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import statistics
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
|
||||
BASE_URL = os.environ.get("BASE_URL", "http://localhost:8080")
|
||||
CACHER_URL = os.environ.get("CACHE_URL", "redis://localhost:6379/0")
|
||||
|
||||
|
||||
def http_json(method, path, *, expected=200, headers=None, body=None):
|
||||
req_headers = {"Accept": "application/json"}
|
||||
if headers:
|
||||
req_headers.update(headers)
|
||||
data = None if body is None else json.dumps(body, ensure_ascii=False).encode("utf-8")
|
||||
if data is not None:
|
||||
req_headers.setdefault("Content-Type", "application/json")
|
||||
request = urllib.request.Request(BASE_URL + path, data=data, headers=req_headers, method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=10) as resp:
|
||||
payload = resp.read()
|
||||
if not payload:
|
||||
return {"status": resp.status, "headers": dict(resp.headers), "body": None}
|
||||
if resp.status not in (expected if isinstance(expected, (list, tuple, set)) else [expected]):
|
||||
raise AssertionError(f"Expected {expected}, got {resp.status}")
|
||||
return {"status": resp.status, "headers": dict(resp.headers), "body": json.loads(payload.decode("utf-8"))}
|
||||
except urllib.error.HTTPError as exc:
|
||||
payload = exc.read()
|
||||
if payload:
|
||||
try:
|
||||
payload = json.loads(payload.decode("utf-8"))
|
||||
except Exception:
|
||||
payload = payload.decode("utf-8", errors="replace")
|
||||
if exc.code not in (expected if isinstance(expected, (list, tuple, set)) else [expected]):
|
||||
raise AssertionError(f"Expected status {expected}, got {exc.code} for {method} {path}: {payload}")
|
||||
return {"status": exc.code, "headers": dict(exc.headers), "body": payload}
|
||||
|
||||
|
||||
def call_with_latency(method, path, *, expected=200, headers=None, body=None):
|
||||
start = time.perf_counter()
|
||||
result = http_json(method, path, expected=expected, headers=headers, body=body)
|
||||
elapsed_ms = (time.perf_counter() - start) * 1000.0
|
||||
return result, elapsed_ms
|
||||
|
||||
|
||||
def main():
|
||||
import redis
|
||||
|
||||
r = redis.Redis.from_url(CACHER_URL, decode_responses=True, socket_connect_timeout=2, socket_timeout=2)
|
||||
|
||||
username = f"cache_{uuid.uuid4().hex[:12]}"
|
||||
password = "123456789012"
|
||||
body = {
|
||||
"username": username,
|
||||
"display_name": "Cache Consistency",
|
||||
"password": password,
|
||||
}
|
||||
registration = http_json("POST", "/api/v1/users", expected=201, body=body)
|
||||
assert registration["status"] == 201, registration
|
||||
|
||||
basic = "Basic " + base64.b64encode(f"{username}:{password}".encode()).decode()
|
||||
session = http_json("POST", "/api/v1/auth/sessions", expected=201, headers={"Authorization": basic})
|
||||
token = session["body"]["token"]
|
||||
assert token, session
|
||||
|
||||
key = f"session:{token}"
|
||||
assert r.get(key), "session was not populated in Valkey"
|
||||
ttl = r.ttl(key)
|
||||
assert ttl and ttl > 0, f"session TTL must be positive, got {ttl}"
|
||||
|
||||
latencies = []
|
||||
for _ in range(10):
|
||||
_, elapsed_ms = call_with_latency("GET", "/api/v1/users/me", expected=200, headers={"Authorization": "Bearer " + token})
|
||||
latencies.append(elapsed_ms)
|
||||
avg = sum(latencies) / len(latencies)
|
||||
p95 = sorted(latencies)[int(len(latencies) * 0.95) - 1]
|
||||
|
||||
stale_payload = {
|
||||
"token": token,
|
||||
"user_id": str(uuid.uuid4()),
|
||||
"expires_at": "2000-01-01T00:00:00Z",
|
||||
"revoked_at": None,
|
||||
"user": {"id": str(uuid.uuid4()), "username": "stale", "display_name": "stale", "created_at": "2020-01-01T00:00:00Z"},
|
||||
}
|
||||
r.setex(key, 120, json.dumps(stale_payload, separators=(",", ":"), ensure_ascii=False))
|
||||
stale_result = http_json("GET", "/api/v1/users/me", expected=200, headers={"Authorization": "Bearer " + token})
|
||||
assert stale_result["status"] == 200, stale_result
|
||||
assert stale_result["body"]["username"] == username, stale_result
|
||||
|
||||
# An unexpired payload must not be able to substitute another identity.
|
||||
stale_payload["expires_at"] = "2100-01-01T00:00:00Z"
|
||||
r.setex(key, 120, json.dumps(stale_payload))
|
||||
forged = http_json("GET", "/api/v1/users/me", headers={"Authorization": "Bearer " + token})
|
||||
assert forged["body"]["id"] == session["body"]["user"]["id"], forged
|
||||
assert forged["body"]["username"] == username, forged
|
||||
|
||||
r.setex(key, 120, json.dumps(stale_payload))
|
||||
def read_identity(_):
|
||||
return http_json("GET", "/api/v1/users/me", headers={"Authorization": "Bearer " + token})["body"]["id"]
|
||||
with ThreadPoolExecutor(max_workers=8) as executor:
|
||||
identities = list(executor.map(read_identity, range(8)))
|
||||
assert identities == [session["body"]["user"]["id"]] * 8, identities
|
||||
|
||||
# Syntactically valid JSON with missing fields must be treated as a miss.
|
||||
r.setex(key, 120, "{}")
|
||||
malformed = http_json("GET", "/api/v1/users/me", headers={"Authorization": "Bearer " + token})
|
||||
assert malformed["body"]["username"] == username, malformed
|
||||
|
||||
r.setex(key, 1, json.dumps({
|
||||
"token": token,
|
||||
"user_id": str(uuid.uuid4()),
|
||||
"expires_at": "2100-01-01T00:00:00Z",
|
||||
"revoked_at": None,
|
||||
"user": {"id": str(uuid.uuid4()), "username": "ttl-recovery", "display_name": "ttl-recovery", "created_at": "2020-01-01T00:00:00Z"},
|
||||
}, separators=(",", ":"), ensure_ascii=False))
|
||||
time.sleep(2)
|
||||
short_ttl = http_json("GET", "/api/v1/users/me", expected=200, headers={"Authorization": "Bearer " + token})
|
||||
assert short_ttl["status"] == 200, short_ttl
|
||||
assert short_ttl["body"]["username"] == username, short_ttl
|
||||
|
||||
revoke = http_json("DELETE", "/api/v1/auth/sessions/current", expected=204, headers={"Authorization": "Bearer " + token})
|
||||
assert revoke["status"] == 204, revoke
|
||||
assert not r.get(key), "revoked session key should be deleted from cache"
|
||||
|
||||
after_logout = http_json("GET", "/api/v1/users/me", expected=401, headers={"Authorization": "Bearer " + token})
|
||||
assert after_logout["status"] == 401, after_logout
|
||||
|
||||
# Simulate a writer repopulating the cache after logout's DELETE.
|
||||
stale_payload.update(session["body"])
|
||||
stale_payload["user_id"] = session["body"]["user"]["id"]
|
||||
stale_payload["revoked_at"] = None
|
||||
r.setex(key, 120, json.dumps(stale_payload))
|
||||
http_json("GET", "/api/v1/users/me", expected=401, headers={"Authorization": "Bearer " + token})
|
||||
assert not r.exists(key), "stale key after logout must be removed"
|
||||
|
||||
print("cache_key_exists=True")
|
||||
print(f"ttl_seconds={ttl}")
|
||||
print(f"avg_latency_ms={avg:.2f}")
|
||||
print(f"p95_latency_ms={p95:.2f}")
|
||||
print("stale_cache_rejected=True")
|
||||
print("forged_identity_rejected=True")
|
||||
print("concurrent_identity_checks=8/8")
|
||||
print("malformed_cache_recovers=True")
|
||||
print("repopulated_revoked_cache_rejected=True")
|
||||
print("short_ttl_recovers_from_db=True")
|
||||
print("logout_revokes_cache=True")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user