forked from mtusi2026/mtusi2026lab2
ЛР 2: PostgreSQL, сессии, Redis и исследование
This commit is contained in:
@@ -0,0 +1,92 @@
|
||||
"""Registration race, genuine transaction rollback and observable Redis cache use."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import threading
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
from compose_helpers import redis, sql
|
||||
from client import Client, check, run
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
||||
args = parser.parse_args()
|
||||
client = Client(args.base_url, timeout=30)
|
||||
|
||||
username = "race_" + uuid.uuid4().hex[:16]
|
||||
registration = {"username": username, "display_name": "Гонка",
|
||||
"password": "Race-password-" + uuid.uuid4().hex}
|
||||
gate = threading.Barrier(4)
|
||||
|
||||
def register(_):
|
||||
own_client = Client(args.base_url, timeout=30)
|
||||
gate.wait(timeout=10)
|
||||
return own_client.call("POST", "/api/v1/users", [201, 409], body=registration)["status"]
|
||||
|
||||
with ThreadPoolExecutor(max_workers=4) as pool:
|
||||
results = list(pool.map(register, range(4)))
|
||||
check(results.count(201) == 1 and results.count(409) == 3, "registration race was not resolved by unique username")
|
||||
check(sql(f"SELECT count(*) FROM users WHERE username = '{username}';") == "1", "duplicate user rows")
|
||||
print("PASS: 4 concurrent registrations -> one 201, three 409, one PostgreSQL row")
|
||||
|
||||
alice, bob = client.user("rollback_a"), client.user("rollback_b")
|
||||
title = "rollback_" + uuid.uuid4().hex
|
||||
suffix = uuid.uuid4().hex[:12]
|
||||
trigger = "student_rollback_" + suffix
|
||||
function = "student_fail_member_" + suffix
|
||||
before = sql(f"SELECT count(*) FROM chat_members WHERE user_id IN ('{alice['id']}', '{bob['id']}');")
|
||||
try:
|
||||
# Failure on Bob's membership happens after the chat INSERT (and Alice's membership).
|
||||
# No fault-injection API or production code branch is added.
|
||||
sql(f"""
|
||||
CREATE FUNCTION {function}() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF NEW.user_id = '{bob['id']}'::uuid AND
|
||||
EXISTS (SELECT 1 FROM chats WHERE id = NEW.chat_id AND title = '{title}') THEN
|
||||
RAISE EXCEPTION 'synthetic membership failure';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
CREATE TRIGGER {trigger} BEFORE INSERT ON chat_members
|
||||
FOR EACH ROW EXECUTE FUNCTION {function}();
|
||||
""")
|
||||
response = client.call("POST", "/api/v1/chats", 503, actor=alice,
|
||||
body={"title": title, "member_ids": [alice["id"], bob["id"]]})
|
||||
check(response["json"]["error"]["code"] == "unavailable", "database failure leaked internals")
|
||||
check(sql(f"SELECT count(*) FROM chats WHERE title = '{title}';") == "0", "partially created chat survived")
|
||||
check(sql(f"SELECT count(*) FROM chat_members WHERE user_id IN ('{alice['id']}', '{bob['id']}');") == before,
|
||||
"partially created memberships survived")
|
||||
finally:
|
||||
sql(f"DROP TRIGGER IF EXISTS {trigger} ON chat_members; DROP FUNCTION IF EXISTS {function}();")
|
||||
client.call("POST", "/api/v1/chats", 201, actor=alice,
|
||||
body={"title": title, "member_ids": [alice["id"], bob["id"]]}, schema="Chat")
|
||||
print("PASS: injected membership failure rolled back chat and membership inserts; normal retry succeeds")
|
||||
|
||||
key = "messenger:session:" + hashlib.sha256(alice["token"].encode("ascii")).hexdigest()
|
||||
ttl_before = int(redis("PTTL", key))
|
||||
check(ttl_before > 0, "login did not populate Redis with TTL")
|
||||
check("password" not in redis("GET", key).lower(), "password material leaked into cache")
|
||||
hits_before = stats_hits()
|
||||
for _ in range(3):
|
||||
client.call("GET", "/api/v1/users/me", actor=alice, schema="User")
|
||||
hits_after = stats_hits()
|
||||
check(hits_after - hits_before >= 3, "authenticated requests did not read Redis")
|
||||
check(0 < int(redis("PTTL", key)) <= ttl_before, "cache access extended session TTL")
|
||||
redis("DEL", key)
|
||||
client.call("GET", "/api/v1/users/me", actor=alice, schema="User")
|
||||
check(int(redis("PTTL", key)) > 0, "cache miss did not refill from PostgreSQL")
|
||||
client.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=alice)
|
||||
check(redis("EXISTS", key) == "0", "logout did not invalidate cache")
|
||||
client.call("GET", "/api/v1/users/me", 401, actor=alice)
|
||||
print("PASS: Redis TTL, hits, miss refill and logout invalidation")
|
||||
|
||||
|
||||
def stats_hits():
|
||||
values = dict(line.split(":", 1) for line in redis("INFO", "stats").splitlines() if ":" in line)
|
||||
return int(values["keyspace_hits"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
Reference in New Issue
Block a user