forked from mtusi2026/mtusi2026lab2
Реализовать лабораторную 2
This commit is contained in:
@@ -0,0 +1,96 @@
|
||||
import base64
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client, Failure, check
|
||||
|
||||
|
||||
def compose(*args):
|
||||
subprocess.run(["docker", "compose", *args], check=True, timeout=45,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
|
||||
|
||||
def ready(client):
|
||||
deadline = time.monotonic() + 30
|
||||
while True:
|
||||
try:
|
||||
client.call("GET", "/health/ready", schema="Health")
|
||||
return
|
||||
except Failure:
|
||||
if time.monotonic() >= deadline:
|
||||
raise
|
||||
time.sleep(0.25)
|
||||
|
||||
|
||||
def main():
|
||||
client = Client(timeout=4)
|
||||
actor = client.user("deps")
|
||||
path = "/api/v1/users/me"
|
||||
client.call("GET", path, actor=actor, schema="User")
|
||||
deadline = time.monotonic() + 5
|
||||
while True:
|
||||
cached = subprocess.check_output(
|
||||
["docker", "compose", "exec", "-T", "cache", "redis-cli",
|
||||
"EXISTS", f"user:v1:{actor['id']}"],
|
||||
text=True, timeout=5,
|
||||
).strip()
|
||||
if cached == "1":
|
||||
break
|
||||
check(time.monotonic() < deadline, "profile was not cached")
|
||||
time.sleep(0.1)
|
||||
print("PASS: Redis contains the profile entry", flush=True)
|
||||
wrong = base64.b64encode((actor["user"]["username"] + ":wrong-password").encode()).decode()
|
||||
client.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": "Basic " + wrong})
|
||||
client.call("GET", path, 401, headers={"X-User-Id": actor["id"]})
|
||||
body = {**actor["registration"], "username": "race_" + uuid.uuid4().hex[:16]}
|
||||
|
||||
def register(_):
|
||||
return Client().call("POST", "/api/v1/users", [201, 409], body=body)["status"]
|
||||
|
||||
with ThreadPoolExecutor(max_workers=4) as pool:
|
||||
results = list(pool.map(register, range(4)))
|
||||
check(sorted(results) == [201, 409, 409, 409], f"registration race: {results}")
|
||||
before = client.call("GET", "/api/v1/chats", actor=actor, schema="ChatPage")["json"]
|
||||
client.call("POST", "/api/v1/chats", 400, actor=actor, body={
|
||||
"title": "Rollback", "member_ids": [actor["id"], str(uuid.uuid4())],
|
||||
})
|
||||
after = client.call("GET", "/api/v1/chats", actor=actor, schema="ChatPage")["json"]
|
||||
check(before == after, "partial chat survived rollback")
|
||||
print("PASS: wrong password, X-User-Id rejected, concurrent registration, chat rollback", flush=True)
|
||||
|
||||
for service, status in (("cache", 200), ("db", 503)):
|
||||
compose("stop", service)
|
||||
try:
|
||||
client.call("GET", path, status, actor=actor, schema="User" if status == 200 else None)
|
||||
client.call("GET", path, 401)
|
||||
finally:
|
||||
compose("start", service)
|
||||
ready(client)
|
||||
print(f"PASS: {service} stopped, authenticated GET returned {status}", flush=True)
|
||||
|
||||
client.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=actor)
|
||||
client.call("GET", path, 401, actor=actor)
|
||||
|
||||
env = dict(os.environ, SESSION_TTL_SECONDS="2")
|
||||
command = ["docker", "compose", "up", "-d", "--no-deps", "--force-recreate", "api"]
|
||||
subprocess.run(command, env=env, check=True, timeout=45, stdout=subprocess.DEVNULL)
|
||||
try:
|
||||
ready(client)
|
||||
short_session = client.user("expiry")
|
||||
client.call("GET", path, actor=short_session, schema="User")
|
||||
time.sleep(2.2)
|
||||
client.call("GET", path, 401, actor=short_session)
|
||||
finally:
|
||||
compose("up", "-d", "--no-deps", "--force-recreate", "api")
|
||||
ready(client)
|
||||
print("PASS: logout and 2-second session expiry")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,18 @@
|
||||
\set ON_ERROR_STOP on
|
||||
BEGIN;
|
||||
INSERT INTO users (username,display_name,password_hash)
|
||||
VALUES ('plan_' || substring(gen_random_uuid()::text,1,8),'Plan',decode('00','hex'))
|
||||
RETURNING id AS actor_id \gset
|
||||
INSERT INTO chats (title) VALUES ('Plan') RETURNING id AS chat_id \gset
|
||||
INSERT INTO members (chat_id,user_id,position) VALUES (:'chat_id',:'actor_id',0);
|
||||
INSERT INTO messages (chat_id,sender_id,text,created_at)
|
||||
SELECT :'chat_id', :'actor_id', 'Synthetic history', now() + n * interval '1 millisecond'
|
||||
FROM generate_series(1,12000) AS n;
|
||||
ANALYZE messages;
|
||||
SELECT created_at AS cursor_at, id AS cursor_id
|
||||
FROM messages WHERE chat_id=:'chat_id' ORDER BY created_at,id OFFSET 9000 LIMIT 1 \gset
|
||||
EXPLAIN (ANALYZE, BUFFERS)
|
||||
SELECT id,chat_id,sender_id,text,created_at FROM messages
|
||||
WHERE chat_id=:'chat_id' AND (created_at,id) > (:'cursor_at'::timestamptz,:'cursor_id'::uuid)
|
||||
ORDER BY created_at,id LIMIT 51;
|
||||
ROLLBACK;
|
||||
Reference in New Issue
Block a user