Выполнить лабораторную 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()
|
||||
@@ -0,0 +1,37 @@
|
||||
"""Concurrent shared-key requests through LB, real instance headers and history."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
import threading
|
||||
import uuid
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments(__doc__)
|
||||
c = Client(args.base_url)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
key = uuid.uuid4().hex
|
||||
barrier = threading.Barrier(16)
|
||||
|
||||
def worker(_):
|
||||
local = Client(args.base_url)
|
||||
barrier.wait()
|
||||
return local.message(alice, chat, ' concurrent body ', key=key)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=16) as pool:
|
||||
responses = list(pool.map(worker, range(16)))
|
||||
ids = {r['json']['id'] for r in responses}
|
||||
instances = {r['headers']['X-Instance-Id'] for r in responses}
|
||||
check(len(ids) == 1, 'concurrent duplicate messages')
|
||||
check(len(instances) >= 2, 'concurrent requests did not reach two replicas')
|
||||
path = '/api/v1/chats/' + chat['id'] + '/messages'
|
||||
c.call('POST', path, 409, actor=alice, body={'text': 'concurrent body'}, headers={'Idempotency-Key': key})
|
||||
again = c.call('POST', path, 201, actor=alice, body={'attachment_ids': [], 'text': ' concurrent body '}, headers={'Idempotency-Key': key}, schema='Message')
|
||||
check(again['json'] == responses[0]['json'], 'semantic replay differs')
|
||||
page = c.call('GET', path, actor=bob, schema='MessagePage')['json']
|
||||
check(len(page['items']) == 1, 'history contains duplicate effects')
|
||||
c.message(bob, chat, 'other user', key=key)
|
||||
print(json.dumps({'parallel_requests': 16, 'observed_instances': sorted(instances), 'unique_messages': len(ids), 'conflict': 409, 'semantic_replay': True, 'user_scope': True}))
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Stop every real API process in turn while reading/writing through LB."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import time
|
||||
import uuid
|
||||
from client import Client, Failure, arguments, check, run
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments(__doc__)
|
||||
c = Client(args.base_url, timeout=10)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
c.timeout = 2
|
||||
observed = {c.call('GET', '/api/v1/users/me', actor=alice, schema='User')['headers']['X-Instance-Id'] for _ in range(20)}
|
||||
check(len(observed) >= 2, 'need two replicas')
|
||||
rows = []
|
||||
for target in sorted(observed):
|
||||
before = c.message(alice, chat, 'before ' + target)['json']
|
||||
env = dict(os.environ, TARGET_INSTANCE_ID=target)
|
||||
started = time.monotonic()
|
||||
action = subprocess.Popen([str(ROOT / 'scripts/stop-one.sh')], env=env)
|
||||
successes, errors, first, confirmations = 0, 0, None, [before]
|
||||
key = uuid.uuid4().hex
|
||||
while time.monotonic() - started < 15:
|
||||
try:
|
||||
result = c.message(alice, chat, 'during ' + key, key=key)
|
||||
confirmations.append(result['json'])
|
||||
c.call('GET', '/api/v1/users/me', actor=alice, schema='User')
|
||||
successes += 1
|
||||
if action.poll() == 0 and first is None:
|
||||
first = time.monotonic() - started
|
||||
key = uuid.uuid4().hex
|
||||
except Failure:
|
||||
errors += 1
|
||||
time.sleep(.05)
|
||||
check(action.wait(timeout=5) == 0, 'stop hook failed')
|
||||
check(first is not None and first <= 10, 'recovery exceeded 10s')
|
||||
from resilience import history
|
||||
messages = history(c, bob, chat)
|
||||
check(all(m in messages for m in confirmations), 'confirmation lost')
|
||||
texts = [m['text'] for m in messages]
|
||||
check(len(texts) == len(set(texts)), 'duplicate effects')
|
||||
snapshots = subprocess.check_output([str(ROOT / 'scripts/compose.sh'), 'ps', '-a', '--format', 'json'], text=True)
|
||||
rows.append({'target': target, 'successful_read_write_pairs': successes, 'failed_attempts': errors, 'successful_pairs_rps': round(successes/(time.monotonic()-started), 3), 'first_recovery_seconds': round(first, 3), 'containers_after_stop': snapshots})
|
||||
subprocess.run([str(ROOT / 'scripts/compose.sh'), 'start', 'api'], check=True, stdout=subprocess.DEVNULL)
|
||||
deadline = time.monotonic()+45
|
||||
while True:
|
||||
try:
|
||||
seen = {c.call('GET', '/api/v1/users/me', actor=alice, schema='User')['headers']['X-Instance-Id'] for _ in range(12)}
|
||||
if observed <= seen:
|
||||
break
|
||||
except Failure:
|
||||
pass
|
||||
check(time.monotonic() < deadline, 'replica did not return')
|
||||
time.sleep(.5)
|
||||
(ROOT / 'evidence/replica-matrix.json').write_text(json.dumps(rows, indent=2)+'\n')
|
||||
print(json.dumps(rows, indent=2))
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,70 @@
|
||||
"""Read/write under actual rolling container replacement, safe retry and history."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import time
|
||||
import uuid
|
||||
from client import Client, Failure, arguments, check, run
|
||||
from resilience import history
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments(__doc__)
|
||||
c = Client(args.base_url, timeout=10)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
before = c.message(alice, chat, 'before rolling')['json']
|
||||
started = time.monotonic()
|
||||
proc = subprocess.Popen([str(ROOT / 'scripts/rolling-update.sh')], cwd=ROOT,
|
||||
env=dict(os.environ, BASE_URL=c.base))
|
||||
|
||||
def worker(index):
|
||||
local = Client(c.base, timeout=2)
|
||||
confirmations, failures, samples, instances = [], 0, [], set()
|
||||
key = uuid.uuid4().hex
|
||||
after_deadline = None
|
||||
while time.monotonic() - started < 120:
|
||||
if proc.poll() is not None and after_deadline is None:
|
||||
after_deadline = time.monotonic() + 3
|
||||
if after_deadline and time.monotonic() >= after_deadline:
|
||||
break
|
||||
at = time.monotonic()
|
||||
try:
|
||||
result = local.message(alice, chat, f'rolling-{index}-{key}', key=key)
|
||||
confirmations.append(result['json'])
|
||||
local.call('GET', '/api/v1/users/me', actor=alice, schema='User')
|
||||
instances.add(result['headers']['X-Instance-Id'])
|
||||
samples.append(round(1000*(time.monotonic()-at), 3))
|
||||
key = uuid.uuid4().hex
|
||||
except Failure:
|
||||
failures += 1
|
||||
time.sleep(.02)
|
||||
return confirmations, failures, samples, instances
|
||||
|
||||
with ThreadPoolExecutor(max_workers=4) as pool:
|
||||
results = list(pool.map(worker, range(4)))
|
||||
check(proc.wait(timeout=5) == 0, 'rolling hook failed')
|
||||
messages = history(c, bob, chat)
|
||||
check(before in messages, 'pre-update message lost')
|
||||
for confirmations, _, _, _ in results:
|
||||
check(all(m in messages for m in confirmations), 'confirmed message lost')
|
||||
texts = [m['text'] for m in messages]
|
||||
check(len(texts) == len(set(texts)), 'retry duplicated effects')
|
||||
meta = json.loads((ROOT / 'evidence/rolling-containers.json').read_text())
|
||||
check({c['image_id'] for c in meta['before']} != {c['image_id'] for c in meta['after']}, 'image was not updated')
|
||||
elapsed = time.monotonic() - started
|
||||
latencies = sorted(x for _, _, values, _ in results for x in values)
|
||||
report = {'status': 'PASS', 'concurrency': 4, 'elapsed_seconds': round(elapsed, 3),
|
||||
'successful_read_write_pairs': len(latencies), 'failed_attempts': sum(r[1] for r in results),
|
||||
'successful_pairs_rps': round(len(latencies)/elapsed, 3),
|
||||
'successful_pair_latency_ms': {f'p{p}': latencies[min(len(latencies)-1, int(len(latencies)*p/100))] for p in (50,95,99)},
|
||||
'observed_instances': sorted(set.union(*(r[3] for r in results))),
|
||||
'confirmed_data_preserved': True, 'duplicates': 0}
|
||||
(ROOT / 'evidence/rolling-load.json').write_text(json.dumps(report, indent=2)+'\n')
|
||||
print(json.dumps(report, indent=2))
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Reference in New Issue
Block a user