Реализовать PostgreSQL, Redis-сессии и backup-трек для сдачи lab2 на 5.
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
import json
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
BASE = "http://127.0.0.1:8080"
|
||||
|
||||
|
||||
def call(method, path, body=None, headers=None, timeout=30):
|
||||
hdrs = {"Accept": "application/json"}
|
||||
data = None
|
||||
if body is not None:
|
||||
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
||||
hdrs["Content-Type"] = "application/json"
|
||||
if headers:
|
||||
hdrs.update(headers)
|
||||
req = urllib.request.Request(BASE + path, data=data, headers=hdrs, method=method)
|
||||
try:
|
||||
response = urllib.request.urlopen(req, timeout=timeout)
|
||||
except urllib.error.HTTPError as error:
|
||||
response = error
|
||||
raw = response.read()
|
||||
payload = None
|
||||
if raw:
|
||||
payload = json.loads(raw.decode("utf-8"))
|
||||
return response.status, response.headers, payload
|
||||
|
||||
|
||||
def bearer(token):
|
||||
return {"Authorization": "Bearer " + token}
|
||||
|
||||
|
||||
def basic(username, password):
|
||||
import base64
|
||||
|
||||
raw = base64.b64encode((username + ":" + password).encode("utf-8")).decode("ascii")
|
||||
return {"Authorization": "Basic " + raw}
|
||||
@@ -0,0 +1,336 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Проверки контракта и уровня 4, которым не нужно останавливать Redis/PostgreSQL."""
|
||||
import json
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
from httpapi import basic, bearer, call
|
||||
from sql import compose, psql
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
EVIDENCE = ROOT / "evidence" / "student_checks.txt"
|
||||
LINES = []
|
||||
|
||||
|
||||
def log(text):
|
||||
print(text)
|
||||
LINES.append(text)
|
||||
|
||||
|
||||
def check(cond, message):
|
||||
if not cond:
|
||||
log("FAIL: " + message)
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
def register(username, display_name, password):
|
||||
status, _, payload = call(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
{"username": username, "display_name": display_name, "password": password},
|
||||
)
|
||||
check(status == 201, "register {} -> {}".format(username, status))
|
||||
check("password" not in payload and "password_hash" not in payload, "password leaked")
|
||||
return payload
|
||||
|
||||
|
||||
def login(username, password):
|
||||
status, headers, payload = call("POST", "/api/v1/auth/sessions", headers=basic(username, password))
|
||||
check(status == 201, "login -> {}".format(status))
|
||||
check(headers.get("X-Request-Id"), "no request id")
|
||||
check(payload["token_type"] == "Bearer", "token type")
|
||||
check(len(payload["token"]) >= 43, "token entropy/length")
|
||||
check(username not in payload["token"], "token contains username")
|
||||
return payload
|
||||
|
||||
|
||||
def main():
|
||||
suffix = uuid.uuid4().hex[:8]
|
||||
req = urllib.request.Request(
|
||||
"http://127.0.0.1:8080/api/v1/users",
|
||||
data=b"{not-json",
|
||||
headers={"Content-Type": "application/json", "Accept": "application/json"},
|
||||
method="POST",
|
||||
)
|
||||
try:
|
||||
urllib.request.urlopen(req, timeout=30)
|
||||
check(False, "bad json accepted")
|
||||
except urllib.error.HTTPError as error:
|
||||
body = json.loads(error.read().decode("utf-8"))
|
||||
check(error.code == 400 and body["error"]["code"] == "invalid_request", "bad json")
|
||||
check(body["error"]["request_id"] == error.headers["X-Request-Id"], "request id")
|
||||
|
||||
status, _, _ = call(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
{"username": "abc", "display_name": "Имя", "password": "short-pass", "extra": 1},
|
||||
)
|
||||
check(status == 400, "extra field {}".format(status))
|
||||
status, _, _ = call(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
{"username": "ab", "display_name": "Имя", "password": "long-enough-pw"},
|
||||
)
|
||||
check(status == 400, "short username")
|
||||
status, _, _ = call(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
{"username": "ok_" + suffix[:4], "display_name": "Имя", "password": "short"},
|
||||
)
|
||||
check(status == 400, "short password")
|
||||
|
||||
password = "pw-" + suffix + "-ok"
|
||||
alice = register("alice_" + suffix, "Алиса", password)
|
||||
again, _, _ = call(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
{"username": alice["username"], "display_name": "Другая", "password": password + "-x"},
|
||||
)
|
||||
check(again == 409, "duplicate username {}".format(again))
|
||||
|
||||
session = login(alice["username"], password)
|
||||
token = session["token"]
|
||||
check(session["user"] == alice, "session user differs")
|
||||
|
||||
status, headers, payload = call(
|
||||
"POST",
|
||||
"/api/v1/auth/sessions",
|
||||
headers=basic(alice["username"], "wrong-password-1"),
|
||||
)
|
||||
check(status == 401 and payload["error"]["code"] == "unauthorized", "wrong password")
|
||||
check(headers.get("WWW-Authenticate", "").startswith("Basic"), "basic challenge")
|
||||
status, _, payload_unknown = call(
|
||||
"POST",
|
||||
"/api/v1/auth/sessions",
|
||||
headers=basic("missing_" + suffix, "wrong-password-1"),
|
||||
)
|
||||
check(status == 401 and payload_unknown["error"]["code"] == payload["error"]["code"], "user enum")
|
||||
|
||||
status, headers, _ = call("GET", "/api/v1/users/me", headers=basic(alice["username"], password))
|
||||
check(status == 401 and headers.get("WWW-Authenticate", "").startswith("Bearer"), "basic on business")
|
||||
status, _, _ = call("GET", "/api/v1/users/me", headers={"X-User-Id": alice["id"]})
|
||||
check(status == 401, "x-user-id alone")
|
||||
status, _, me = call(
|
||||
"GET",
|
||||
"/api/v1/users/me",
|
||||
headers={**bearer(token), "X-User-Id": str(uuid.uuid4())},
|
||||
)
|
||||
check(status == 200 and me["id"] == alice["id"], "x-user-id overrode bearer")
|
||||
|
||||
colon_pw = "secret:part-" + suffix
|
||||
colon_user = register("colon_" + suffix, "Двоеточие", colon_pw)
|
||||
colon_session = login(colon_user["username"], colon_pw)
|
||||
check(colon_session["user"]["id"] == colon_user["id"], "colon password")
|
||||
|
||||
uni_pw = "пароль-тест-" + suffix
|
||||
uni_user = register("uni_" + suffix, "Юникод", uni_pw)
|
||||
login(uni_user["username"], uni_pw)
|
||||
|
||||
bob = register("bob_" + suffix, "Боб", password)
|
||||
eve = register("eve_" + suffix, "Ева", password)
|
||||
bob_token = login(bob["username"], password)["token"]
|
||||
eve_token = login(eve["username"], password)["token"]
|
||||
status, _, chat = call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
{"title": "Проверка", "member_ids": [alice["id"], bob["id"]]},
|
||||
bearer(token),
|
||||
)
|
||||
check(status == 201, "chat {}".format(status))
|
||||
check(set(chat["member_ids"]) == {alice["id"], bob["id"]}, "members")
|
||||
|
||||
status, _, _ = call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
{"title": "Без себя", "member_ids": [bob["id"]]},
|
||||
bearer(token),
|
||||
)
|
||||
check(status == 400, "caller not in chat")
|
||||
missing = str(uuid.uuid4())
|
||||
before = int(psql("SELECT count(*) FROM chats;"))
|
||||
status, _, _ = call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
{"title": "Битый участник", "member_ids": [alice["id"], missing]},
|
||||
bearer(token),
|
||||
)
|
||||
after = int(psql("SELECT count(*) FROM chats;"))
|
||||
check(status == 400 and before == after, "chat rollback left a row {} {}".format(before, after))
|
||||
|
||||
psql("DELETE FROM chats WHERE title = 'rollback-probe';")
|
||||
broken = compose(
|
||||
"exec",
|
||||
"-T",
|
||||
"postgres",
|
||||
"psql",
|
||||
"-U",
|
||||
"messenger",
|
||||
"-d",
|
||||
"messenger",
|
||||
"-v",
|
||||
"ON_ERROR_STOP=1",
|
||||
"-q",
|
||||
input_bytes=b"""
|
||||
BEGIN;
|
||||
INSERT INTO chats (id, title, created_at)
|
||||
VALUES ('aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaa1', 'rollback-probe', now());
|
||||
INSERT INTO chat_members (chat_id, user_id, ordinal)
|
||||
VALUES ('aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaa1', 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaa2', 0);
|
||||
COMMIT;
|
||||
""",
|
||||
check=False,
|
||||
)
|
||||
check(broken.returncode != 0, "fk insert unexpectedly committed")
|
||||
left = int(psql("SELECT count(*) FROM chats WHERE title = 'rollback-probe';"))
|
||||
check(left == 0, "sql rollback probe left a chat")
|
||||
log("rollback: api count {} -> {}, sql probe rows {}".format(before, after, left))
|
||||
|
||||
status, _, _ = call("GET", "/api/v1/chats/" + chat["id"], headers=bearer(eve_token))
|
||||
check(status == 404, "foreign chat")
|
||||
status, _, _ = call(
|
||||
"POST",
|
||||
"/api/v1/chats/" + chat["id"] + "/messages",
|
||||
{"text": "чужое"},
|
||||
bearer(eve_token),
|
||||
)
|
||||
check(status == 404, "foreign message")
|
||||
status, _, listed = call("GET", "/api/v1/chats?limit=100", headers=bearer(eve_token))
|
||||
check(status == 200 and all(item["id"] != chat["id"] for item in listed["items"]), "chat leak")
|
||||
|
||||
sent = []
|
||||
for index in range(5):
|
||||
actor = token if index % 2 == 0 else bob_token
|
||||
status, _, message = call(
|
||||
"POST",
|
||||
"/api/v1/chats/" + chat["id"] + "/messages",
|
||||
{"text": "сообщение {}".format(index)},
|
||||
bearer(actor),
|
||||
)
|
||||
check(status == 201, "message {}".format(status))
|
||||
sent.append(message["id"])
|
||||
status, _, _ = call(
|
||||
"POST",
|
||||
"/api/v1/chats/" + chat["id"] + "/messages",
|
||||
{"text": " "},
|
||||
bearer(token),
|
||||
)
|
||||
check(status == 400, "blank message")
|
||||
collected = []
|
||||
cursor = None
|
||||
pages = 0
|
||||
while True:
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages?limit=2"
|
||||
if cursor:
|
||||
path += "&cursor=" + quote(cursor, safe="")
|
||||
status, _, page = call("GET", path, headers=bearer(bob_token))
|
||||
check(status == 200, "page")
|
||||
collected.extend(item["id"] for item in page["items"])
|
||||
pages += 1
|
||||
if page["next_cursor"] is None:
|
||||
break
|
||||
cursor = page["next_cursor"]
|
||||
check(pages < 10, "cursor loop")
|
||||
check(pages >= 3 and collected == sent, "pagination {} {}".format(pages, collected))
|
||||
other_status, _, other = call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
{"title": "Второй", "member_ids": [alice["id"], bob["id"]]},
|
||||
bearer(token),
|
||||
)
|
||||
check(other_status == 201, "second chat")
|
||||
call(
|
||||
"POST",
|
||||
"/api/v1/chats/" + chat["id"] + "/messages",
|
||||
{"text": "для курсора"},
|
||||
bearer(token),
|
||||
)
|
||||
call(
|
||||
"POST",
|
||||
"/api/v1/chats/" + chat["id"] + "/messages",
|
||||
{"text": "ещё"},
|
||||
bearer(bob_token),
|
||||
)
|
||||
_, _, first_page = call(
|
||||
"GET",
|
||||
"/api/v1/chats/" + chat["id"] + "/messages?limit=1",
|
||||
headers=bearer(token),
|
||||
)
|
||||
stolen, _, _ = call(
|
||||
"GET",
|
||||
"/api/v1/chats/" + other["id"] + "/messages?limit=1&cursor=" + quote(first_page["next_cursor"], safe=""),
|
||||
headers=bearer(token),
|
||||
)
|
||||
check(stolen == 400, "foreign cursor {}".format(stolen))
|
||||
|
||||
race_name = "race_" + suffix
|
||||
race_password = "race-password-" + suffix
|
||||
|
||||
def once(_n):
|
||||
return call(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
{"username": race_name, "display_name": "Гонка", "password": race_password},
|
||||
)[0]
|
||||
|
||||
with ThreadPoolExecutor(max_workers=12) as pool:
|
||||
codes = list(pool.map(once, range(12)))
|
||||
winners = codes.count(201)
|
||||
conflicts = codes.count(409)
|
||||
rows = int(psql("SELECT count(*) FROM users WHERE username = '{}';".format(race_name)))
|
||||
check(winners == 1 and conflicts == 11 and rows == 1, "race {} rows {}".format(codes, rows))
|
||||
log("username race: one 201, eleven 409, one row")
|
||||
|
||||
status, _, _ = call("DELETE", "/api/v1/auth/sessions/current", headers=bearer(token))
|
||||
check(status == 204, "logout {}".format(status))
|
||||
status, _, _ = call("GET", "/api/v1/users/me", headers=bearer(token))
|
||||
check(status == 401, "revoked token")
|
||||
status, _, _ = call("DELETE", "/api/v1/auth/sessions/current", headers=bearer(token))
|
||||
check(status == 401, "second logout")
|
||||
|
||||
users_before = psql("SELECT count(*) FROM users;")
|
||||
versions_before = psql("SELECT version FROM schema_migrations ORDER BY version;")
|
||||
compose("restart", "api")
|
||||
deadline = time.time() + 60
|
||||
while True:
|
||||
try:
|
||||
ready, _, _ = call("GET", "/health/ready", timeout=3)
|
||||
except Exception:
|
||||
ready = 0
|
||||
if ready == 200:
|
||||
break
|
||||
if time.time() > deadline:
|
||||
raise SystemExit("FAIL: api did not come back after migration restart")
|
||||
time.sleep(0.5)
|
||||
users_after = psql("SELECT count(*) FROM users;")
|
||||
versions_after = psql("SELECT version FROM schema_migrations ORDER BY version;")
|
||||
check(users_before == users_after and versions_before == versions_after, "migration duplicated data")
|
||||
log("migrations reapplied, users {} -> {}, versions {}".format(users_before, users_after, versions_after))
|
||||
|
||||
redis_info = compose("exec", "-T", "redis", "redis-cli", "INFO", "persistence").stdout.decode("utf-8", "replace")
|
||||
interesting = [
|
||||
line.strip()
|
||||
for line in redis_info.splitlines()
|
||||
if line.startswith(("aof_enabled", "aof_last_write_status", "aof_current_size", "rdb_last_bgsave_status"))
|
||||
]
|
||||
log("redis persistence: " + ", ".join(interesting))
|
||||
check(any(line == "aof_enabled:1" for line in interesting), "aof is off")
|
||||
log("PASS student checks")
|
||||
EVIDENCE.write_text("\n".join(LINES) + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except SystemExit:
|
||||
if LINES:
|
||||
EVIDENCE.write_text("\n".join(LINES) + "\n", encoding="utf-8")
|
||||
raise
|
||||
except Exception as exc:
|
||||
log("FAIL: {}: {}".format(type(exc).__name__, exc))
|
||||
EVIDENCE.write_text("\n".join(LINES) + "\n", encoding="utf-8")
|
||||
raise SystemExit(1)
|
||||
@@ -0,0 +1,150 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Отказ Redis/PostgreSQL и короткий TTL. В конце стенд возвращается к SESSION_TTL_SECONDS=3600."""
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
from httpapi import basic, bearer, call
|
||||
from sql import ROOT, compose
|
||||
|
||||
EVIDENCE = ROOT / "evidence" / "failures.txt"
|
||||
LINES = []
|
||||
|
||||
|
||||
def log(text):
|
||||
print(text)
|
||||
LINES.append(text)
|
||||
|
||||
|
||||
def check(cond, message):
|
||||
if not cond:
|
||||
log("FAIL: " + message)
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
def wait_ready(timeout=60):
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
status, _, _ = call("GET", "/health/ready", timeout=8)
|
||||
except Exception:
|
||||
status = 0
|
||||
if status == 200:
|
||||
return
|
||||
time.sleep(0.5)
|
||||
raise SystemExit("FAIL: ready timeout")
|
||||
|
||||
|
||||
def limited(payload):
|
||||
text = "" if payload is None else str(payload).lower()
|
||||
for word in ("redis", "postgres", "traceback", "select ", "password", "argon"):
|
||||
check(word not in text, "error leaked " + word)
|
||||
|
||||
|
||||
def recreate_api(ttl):
|
||||
env = os.environ.copy()
|
||||
env["SESSION_TTL_SECONDS"] = str(ttl)
|
||||
proc = __import__("subprocess").run(
|
||||
["docker", "compose", "--env-file", ".env", "up", "-d", "--force-recreate", "--no-deps", "--wait", "api"],
|
||||
cwd=ROOT,
|
||||
env=env,
|
||||
stdout=__import__("subprocess").PIPE,
|
||||
stderr=__import__("subprocess").PIPE,
|
||||
timeout=180,
|
||||
check=False,
|
||||
)
|
||||
if proc.returncode != 0:
|
||||
err = proc.stderr.decode("utf-8", "replace")[-500:]
|
||||
raise SystemExit("FAIL: recreate api\n" + err)
|
||||
wait_ready()
|
||||
|
||||
|
||||
def main():
|
||||
suffix = uuid.uuid4().hex[:8]
|
||||
password = "fail-password-" + suffix
|
||||
username = "fail_" + suffix
|
||||
status, _, user = call(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
{"username": username, "display_name": "Отказ", "password": password},
|
||||
)
|
||||
check(status == 201, "register")
|
||||
status, _, session = call("POST", "/api/v1/auth/sessions", headers=basic(username, password))
|
||||
check(status == 201, "login")
|
||||
token = session["token"]
|
||||
|
||||
log("stop redis")
|
||||
compose("stop", "redis")
|
||||
try:
|
||||
live, _, _ = call("GET", "/health/live", timeout=8)
|
||||
ready, _, ready_body = call("GET", "/health/ready", timeout=15)
|
||||
anon, anon_headers, anon_body = call("GET", "/api/v1/users/me", timeout=15)
|
||||
xid, _, _ = call("GET", "/api/v1/users/me", headers={"X-User-Id": user["id"]}, timeout=15)
|
||||
authed, _, authed_body = call("GET", "/api/v1/users/me", headers=bearer(token), timeout=15)
|
||||
check(live == 200, "live during redis stop {}".format(live))
|
||||
check(ready == 503, "ready during redis stop {}".format(ready))
|
||||
check(anon == 401 and anon_headers.get("WWW-Authenticate", "").startswith("Bearer"), "anon {}".format(anon))
|
||||
check(xid == 401, "x-user-id during redis stop {}".format(xid))
|
||||
check(authed == 503, "bearer during redis stop {}".format(authed))
|
||||
limited(ready_body)
|
||||
limited(anon_body)
|
||||
limited(authed_body)
|
||||
log("redis down: live 200, ready 503, anon/x-user-id 401, bearer 503")
|
||||
finally:
|
||||
compose("start", "redis")
|
||||
wait_ready()
|
||||
|
||||
log("stop postgres")
|
||||
compose("stop", "postgres")
|
||||
try:
|
||||
live, _, _ = call("GET", "/health/live", timeout=8)
|
||||
ready, _, _ = call("GET", "/health/ready", timeout=15)
|
||||
anon, _, _ = call("GET", "/api/v1/users/me", timeout=15)
|
||||
authed, _, authed_body = call("GET", "/api/v1/users/me", headers=bearer(token), timeout=15)
|
||||
check(live == 200, "live during postgres stop {}".format(live))
|
||||
check(ready == 503, "ready during postgres stop {}".format(ready))
|
||||
check(anon == 401, "anon during postgres stop {}".format(anon))
|
||||
check(authed == 503, "bearer during postgres stop {}".format(authed))
|
||||
limited(authed_body)
|
||||
log("postgres down: live 200, ready 503, anon 401, bearer 503")
|
||||
finally:
|
||||
compose("start", "postgres")
|
||||
wait_ready()
|
||||
|
||||
log("session ttl 2s")
|
||||
recreate_api(2)
|
||||
try:
|
||||
status, _, short = call("POST", "/api/v1/auth/sessions", headers=basic(username, password))
|
||||
check(status == 201, "short login")
|
||||
expires = datetime.fromisoformat(short["expires_at"].replace("Z", "+00:00"))
|
||||
delta = (expires - datetime.now(timezone.utc)).total_seconds()
|
||||
check(1 <= delta <= 4, "ttl delta {}".format(delta))
|
||||
time.sleep(delta + 1.2)
|
||||
status, headers, _ = call("GET", "/api/v1/users/me", headers=bearer(short["token"]), timeout=15)
|
||||
check(status == 401 and headers.get("WWW-Authenticate", "").startswith("Bearer"), "expired {}".format(status))
|
||||
log("expired session -> 401, delta was {:.2f}s".format(delta))
|
||||
finally:
|
||||
recreate_api(3600)
|
||||
status, _, restored = call("POST", "/api/v1/auth/sessions", headers=basic(username, password))
|
||||
check(status == 201, "ttl restored login")
|
||||
expires = datetime.fromisoformat(restored["expires_at"].replace("Z", "+00:00"))
|
||||
delta = (expires - datetime.now(timezone.utc)).total_seconds()
|
||||
check(delta > 300, "ttl not restored {}".format(delta))
|
||||
log("ttl restored, expires in {:.0f}s".format(delta))
|
||||
|
||||
log("PASS failure checks")
|
||||
EVIDENCE.write_text("\n".join(LINES) + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except SystemExit:
|
||||
EVIDENCE.write_text("\n".join(LINES) + "\n", encoding="utf-8")
|
||||
raise
|
||||
except Exception as exc:
|
||||
log("FAIL: {}: {}".format(type(exc).__name__, exc))
|
||||
EVIDENCE.write_text("\n".join(LINES) + "\n", encoding="utf-8")
|
||||
raise SystemExit(1)
|
||||
@@ -0,0 +1,447 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Трек 2: план keyset-запроса на неравномерной истории и backup в новый volume."""
|
||||
import json
|
||||
import re
|
||||
import statistics
|
||||
import subprocess
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
from httpapi import bearer, call
|
||||
from sql import ROOT, compose, psql, psql_file
|
||||
|
||||
EVIDENCE = ROOT / "evidence"
|
||||
BACKUPS = ROOT / "backups"
|
||||
RESTORE_NAME = "mtusi-lab2-restore"
|
||||
RESTORE_VOLUME = "mtusi-lab2-restore-data"
|
||||
INSERT_ROWS = 20000
|
||||
REPEATS = 3
|
||||
|
||||
|
||||
def log(text):
|
||||
print(text, flush=True)
|
||||
|
||||
|
||||
def check(cond, message):
|
||||
if not cond:
|
||||
raise SystemExit("FAIL: " + message)
|
||||
|
||||
|
||||
def postgres_image():
|
||||
text = (ROOT / "compose.yaml").read_text(encoding="utf-8")
|
||||
match = re.search(r"image:\s*(postgres:\S+)", text)
|
||||
check(match is not None, "postgres image tag")
|
||||
return match.group(1)
|
||||
|
||||
|
||||
def median(values):
|
||||
return statistics.median(values)
|
||||
|
||||
|
||||
def execution_ms(plan):
|
||||
found = re.findall(r"Execution Time:\s+([0-9.]+)\s+ms", plan)
|
||||
check(found, "no execution time in plan")
|
||||
return float(found[-1])
|
||||
|
||||
|
||||
def planning_ms(plan):
|
||||
found = re.findall(r"Planning Time:\s+([0-9.]+)\s+ms", plan)
|
||||
return float(found[-1]) if found else None
|
||||
|
||||
|
||||
def first_buffers(plan):
|
||||
found = re.findall(r"Buffers:.*", plan)
|
||||
return found[0].strip() if found else ""
|
||||
|
||||
|
||||
def run_insert(label):
|
||||
sql = """
|
||||
EXPLAIN (ANALYZE, BUFFERS)
|
||||
INSERT INTO track2_write (id, chat_id, sender_id, body, created_at)
|
||||
SELECT gen_random_uuid(),
|
||||
'00000000-0000-4000-8000-000000000001'::uuid,
|
||||
'00000000-0000-4000-8000-000000000002'::uuid,
|
||||
'w',
|
||||
timestamptz '2025-01-01 00:00:00+00' + (n || ' microseconds')::interval
|
||||
FROM generate_series(1, {rows}) AS n;
|
||||
""".format(rows=INSERT_ROWS)
|
||||
samples = []
|
||||
psql("TRUNCATE track2_write;")
|
||||
psql_file(sql)
|
||||
for _ in range(REPEATS):
|
||||
psql("TRUNCATE track2_write;")
|
||||
samples.append(execution_ms(psql_file(sql)))
|
||||
result = {"label": label, "rows": INSERT_ROWS, "repeats": samples, "median_ms": median(samples)}
|
||||
log("{} median {:.1f} ms {}".format(label, result["median_ms"], ["{:.1f}".format(x) for x in samples]))
|
||||
return result
|
||||
|
||||
|
||||
def psql_on(container, sql):
|
||||
proc = subprocess.run(
|
||||
["docker", "exec", "-i", container, "psql", "-U", "messenger", "-d", "messenger", "-v", "ON_ERROR_STOP=1", "-q", "-t", "-A"],
|
||||
input=sql.encode("utf-8"),
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
check=False,
|
||||
)
|
||||
if proc.returncode != 0:
|
||||
raise RuntimeError(proc.stderr.decode("utf-8", "replace")[-500:])
|
||||
return proc.stdout.decode("utf-8").strip()
|
||||
|
||||
|
||||
def main():
|
||||
EVIDENCE.mkdir(exist_ok=True)
|
||||
BACKUPS.mkdir(exist_ok=True)
|
||||
source = (ROOT / "src" / "store.py").read_text(encoding="utf-8")
|
||||
check("AND (created_at, id) > (%s, %s)" in source, "app query changed")
|
||||
|
||||
password = "track2-" + uuid.uuid4().hex
|
||||
username = "track2_sender"
|
||||
psql(
|
||||
"""
|
||||
DELETE FROM messages
|
||||
WHERE sender_id IN (SELECT id FROM users WHERE username = 'track2_sender')
|
||||
OR chat_id IN (SELECT id FROM chats WHERE title LIKE 'track2:%');
|
||||
DELETE FROM chat_members
|
||||
WHERE user_id IN (SELECT id FROM users WHERE username = 'track2_sender')
|
||||
OR chat_id IN (SELECT id FROM chats WHERE title LIKE 'track2:%');
|
||||
DELETE FROM chats WHERE title LIKE 'track2:%';
|
||||
DELETE FROM users WHERE username = 'track2_sender';
|
||||
DROP TABLE IF EXISTS track2_write;
|
||||
"""
|
||||
)
|
||||
status, _, user = call(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
{"username": username, "display_name": "Трек 2", "password": password},
|
||||
)
|
||||
check(status == 201, "register track2 {}".format(status))
|
||||
status, _, session = call(
|
||||
"POST",
|
||||
"/api/v1/auth/sessions",
|
||||
headers=__import__("httpapi").basic(username, password),
|
||||
)
|
||||
check(status == 201, "login track2")
|
||||
user_id = user["id"]
|
||||
|
||||
specs = [("track2:big", 70000, 0), ("track2:mid", 20000, 1)]
|
||||
for index in range(10):
|
||||
specs.append(("track2:m{:02d}".format(index), 1000, 2 + index))
|
||||
for index in range(100):
|
||||
specs.append(("track2:s{:02d}".format(index), 10, 12 + index))
|
||||
check(sum(item[1] for item in specs) == 101000, "distribution")
|
||||
|
||||
chat_rows = []
|
||||
for title, _count, _idx in specs:
|
||||
chat_rows.append(
|
||||
"('{}', '{}', timestamptz '2024-06-01 00:00:00+00')".format(str(uuid.uuid4()), title)
|
||||
)
|
||||
psql("INSERT INTO chats (id, title, created_at) VALUES\n" + ",\n".join(chat_rows) + ";")
|
||||
psql(
|
||||
"""
|
||||
INSERT INTO chat_members (chat_id, user_id, ordinal)
|
||||
SELECT id, '{}'::uuid, 0 FROM chats WHERE title LIKE 'track2:%';
|
||||
""".format(user_id)
|
||||
)
|
||||
|
||||
statements = ["BEGIN;"]
|
||||
for title, count, index in specs:
|
||||
statements.append(
|
||||
"""
|
||||
INSERT INTO messages (id, chat_id, sender_id, body, created_at)
|
||||
SELECT gen_random_uuid(),
|
||||
c.id,
|
||||
'{user}'::uuid,
|
||||
't2-' || n::text,
|
||||
timestamptz '2024-06-01 00:00:00+00'
|
||||
+ ((n * 1000 + {index}) || ' microseconds')::interval
|
||||
FROM chats c
|
||||
CROSS JOIN generate_series(1, {count}) AS n
|
||||
WHERE c.title = '{title}';
|
||||
""".format(user=user_id, index=index, count=count, title=title)
|
||||
)
|
||||
statements.append("COMMIT;")
|
||||
log("loading 101000 messages")
|
||||
started = time.perf_counter()
|
||||
psql("\n".join(statements), timeout=300)
|
||||
load_seconds = time.perf_counter() - started
|
||||
psql("ANALYZE messages; ANALYZE chats; ANALYZE chat_members;")
|
||||
total = int(psql("SELECT count(*) FROM messages WHERE chat_id IN (SELECT id FROM chats WHERE title LIKE 'track2:%');"))
|
||||
check(total == 101000, "loaded {}".format(total))
|
||||
log("loaded in {:.1f}s".format(load_seconds))
|
||||
|
||||
big_id = psql("SELECT id FROM chats WHERE title = 'track2:big';")
|
||||
small_id = psql("SELECT id FROM chats WHERE title = 'track2:s00';")
|
||||
cursor = psql(
|
||||
"""
|
||||
SELECT created_at::text || '|' || id::text
|
||||
FROM messages
|
||||
WHERE chat_id = '{chat}' AND body = 't2-5';
|
||||
""".format(chat=big_id)
|
||||
)
|
||||
created_at, message_id = cursor.split("|", 1)
|
||||
check(re.fullmatch(r"[0-9a-f-]{36}", message_id), "cursor id")
|
||||
|
||||
def keyset_sql():
|
||||
return """
|
||||
EXPLAIN (ANALYZE, BUFFERS)
|
||||
SELECT id, chat_id, sender_id, body AS text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = '{chat}'::uuid
|
||||
AND (created_at, id) > (timestamptz '{ts}', '{mid}'::uuid)
|
||||
ORDER BY created_at, id
|
||||
LIMIT 51;
|
||||
""".format(chat=big_id, ts=created_at, mid=message_id)
|
||||
|
||||
psql_file(keyset_sql())
|
||||
good_plan = psql_file(keyset_sql())
|
||||
(EVIDENCE / "explain_history_index.txt").write_text(good_plan, encoding="utf-8")
|
||||
check("messages_history_idx" in good_plan, "history index was not used")
|
||||
|
||||
first_plan = psql_file(
|
||||
"""
|
||||
EXPLAIN (ANALYZE, BUFFERS)
|
||||
SELECT id, chat_id, sender_id, body AS text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = '{chat}'::uuid
|
||||
ORDER BY created_at, id
|
||||
LIMIT 51;
|
||||
""".format(chat=big_id)
|
||||
)
|
||||
(EVIDENCE / "explain_history_first_page.txt").write_text(first_plan, encoding="utf-8")
|
||||
|
||||
offset_plan = psql_file(
|
||||
"""
|
||||
EXPLAIN (ANALYZE, BUFFERS)
|
||||
SELECT id, chat_id, sender_id, body AS text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = '{chat}'::uuid
|
||||
ORDER BY created_at, id
|
||||
OFFSET 5000
|
||||
LIMIT 50;
|
||||
""".format(chat=big_id)
|
||||
)
|
||||
(EVIDENCE / "explain_offset.txt").write_text(offset_plan, encoding="utf-8")
|
||||
|
||||
weak_script = """
|
||||
BEGIN;
|
||||
DROP INDEX messages_history_idx;
|
||||
CREATE INDEX messages_created_idx ON messages (created_at);
|
||||
ANALYZE messages;
|
||||
{explain}
|
||||
ROLLBACK;
|
||||
""".format(explain=keyset_sql())
|
||||
weak_plan = psql_file(weak_script)
|
||||
(EVIDENCE / "explain_created_at_index.txt").write_text(weak_plan, encoding="utf-8")
|
||||
still = psql("SELECT indexdef FROM pg_indexes WHERE indexname = 'messages_history_idx';")
|
||||
check("chat_id, created_at, id" in still, "history index missing after rollback")
|
||||
check(psql("SELECT count(*) FROM pg_indexes WHERE indexname = 'messages_created_idx';") == "0", "weak index left behind")
|
||||
|
||||
status, _, page = call(
|
||||
"GET",
|
||||
"/api/v1/chats/" + big_id + "/messages?limit=2",
|
||||
headers=bearer(session["token"]),
|
||||
)
|
||||
check(status == 200 and len(page["items"]) == 2, "api page")
|
||||
sql_first = psql(
|
||||
"""
|
||||
SELECT body FROM messages
|
||||
WHERE chat_id = '{chat}'
|
||||
ORDER BY created_at, id
|
||||
LIMIT 2;
|
||||
""".format(chat=big_id)
|
||||
).splitlines()
|
||||
check([item["text"] for item in page["items"]] == sql_first, "api order != sql")
|
||||
|
||||
log("write cost")
|
||||
psql(
|
||||
"""
|
||||
CREATE TABLE track2_write (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL,
|
||||
sender_id uuid NOT NULL,
|
||||
body text NOT NULL,
|
||||
created_at timestamptz NOT NULL
|
||||
);
|
||||
"""
|
||||
)
|
||||
try:
|
||||
pk_only = run_insert("pk_only")
|
||||
psql("CREATE INDEX track2_write_hist ON track2_write (chat_id, created_at, id);")
|
||||
with_hist = run_insert("pk_and_history")
|
||||
psql("CREATE INDEX track2_write_body ON track2_write (chat_id, body);")
|
||||
with_body = run_insert("pk_history_and_body")
|
||||
finally:
|
||||
psql("DROP TABLE IF EXISTS track2_write;")
|
||||
|
||||
log("backup")
|
||||
dump_started = time.perf_counter()
|
||||
dump = compose(
|
||||
"exec",
|
||||
"-T",
|
||||
"postgres",
|
||||
"pg_dump",
|
||||
"-U",
|
||||
"messenger",
|
||||
"-d",
|
||||
"messenger",
|
||||
"-Fc",
|
||||
"--no-owner",
|
||||
"--no-acl",
|
||||
timeout=300,
|
||||
)
|
||||
dump_seconds = time.perf_counter() - dump_started
|
||||
dump_path = BACKUPS / "track2.dump"
|
||||
dump_path.write_bytes(dump.stdout)
|
||||
log("dump {:.2f}s, {} bytes".format(dump_seconds, len(dump.stdout)))
|
||||
|
||||
image = postgres_image()
|
||||
db_password = (ROOT / "secrets" / "postgres_password").read_text(encoding="utf-8").strip()
|
||||
subprocess.run(["docker", "rm", "-f", RESTORE_NAME], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False)
|
||||
subprocess.run(["docker", "volume", "rm", RESTORE_VOLUME], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False)
|
||||
subprocess.run(["docker", "volume", "create", RESTORE_VOLUME], check=True, stdout=subprocess.PIPE)
|
||||
started_container = subprocess.run(
|
||||
[
|
||||
"docker", "run", "-d",
|
||||
"--name", RESTORE_NAME,
|
||||
"--network", "mtusi-lab2-net",
|
||||
"-e", "POSTGRES_USER=messenger",
|
||||
"-e", "POSTGRES_PASSWORD=" + db_password,
|
||||
"-e", "POSTGRES_DB=messenger",
|
||||
"-v", RESTORE_VOLUME + ":/var/lib/postgresql/data",
|
||||
image,
|
||||
],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
check=False,
|
||||
)
|
||||
check(started_container.returncode == 0, "restore container")
|
||||
try:
|
||||
deadline = time.time() + 60
|
||||
while time.time() < deadline:
|
||||
probe = subprocess.run(
|
||||
["docker", "exec", RESTORE_NAME, "pg_isready", "-U", "messenger", "-d", "messenger"],
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
check=False,
|
||||
)
|
||||
if probe.returncode == 0:
|
||||
break
|
||||
time.sleep(0.5)
|
||||
else:
|
||||
raise SystemExit("FAIL: restore postgres not ready")
|
||||
restore_started = time.perf_counter()
|
||||
restored = subprocess.run(
|
||||
[
|
||||
"docker", "exec", "-i", RESTORE_NAME,
|
||||
"pg_restore", "-U", "messenger", "-d", "messenger",
|
||||
"--no-owner", "--no-acl", "--exit-on-error",
|
||||
],
|
||||
input=dump.stdout,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
check=False,
|
||||
)
|
||||
restore_seconds = time.perf_counter() - restore_started
|
||||
if restored.returncode != 0:
|
||||
err = restored.stderr.decode("utf-8", "replace")
|
||||
err = err.replace(db_password, "***")
|
||||
raise SystemExit("FAIL: pg_restore\n" + err[-800:])
|
||||
log("restore {:.2f}s".format(restore_seconds))
|
||||
|
||||
def counts(sql):
|
||||
return {
|
||||
"messages": int(sql("SELECT count(*) FROM messages;")),
|
||||
"users": int(sql("SELECT count(*) FROM users;")),
|
||||
"chats": int(sql("SELECT count(*) FROM chats;")),
|
||||
"members": int(sql("SELECT count(*) FROM chat_members;")),
|
||||
"big": int(sql("SELECT count(*) FROM messages WHERE chat_id = '{}'::uuid;".format(big_id))),
|
||||
"small": int(sql("SELECT count(*) FROM messages WHERE chat_id = '{}'::uuid;".format(small_id))),
|
||||
"small_bodies": sql(
|
||||
"""
|
||||
SELECT string_agg(body, ',' ORDER BY created_at, id)
|
||||
FROM messages WHERE chat_id = '{}'::uuid;
|
||||
""".format(small_id)
|
||||
),
|
||||
"markers": sql(
|
||||
"""
|
||||
SELECT string_agg(body, ',' ORDER BY created_at, id)
|
||||
FROM messages
|
||||
WHERE chat_id = '{}'::uuid AND body IN ('t2-1', 't2-500', 't2-70000');
|
||||
""".format(big_id)
|
||||
),
|
||||
}
|
||||
|
||||
src_counts = counts(psql)
|
||||
dst_counts = counts(lambda sql: psql_on(RESTORE_NAME, sql))
|
||||
check(src_counts == dst_counts, "restore mismatch {} {}".format(src_counts, dst_counts))
|
||||
log("counts match {}".format({k: src_counts[k] for k in ("messages", "users", "chats", "members", "big", "small")}))
|
||||
finally:
|
||||
subprocess.run(["docker", "rm", "-f", RESTORE_NAME], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False)
|
||||
subprocess.run(["docker", "volume", "rm", RESTORE_VOLUME], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False)
|
||||
if dump_path.exists():
|
||||
dump_path.unlink()
|
||||
|
||||
settings = psql(
|
||||
"""
|
||||
SELECT name || '=' || setting
|
||||
FROM pg_settings
|
||||
WHERE name IN ('fsync', 'synchronous_commit', 'full_page_writes', 'wal_level')
|
||||
ORDER BY name;
|
||||
"""
|
||||
)
|
||||
version = psql("SELECT version();")
|
||||
size = psql("SELECT pg_size_pretty(pg_total_relation_size('messages'));")
|
||||
info = subprocess.run(
|
||||
["docker", "info", "--format", "{{.NCPU}}|{{.MemTotal}}|{{.OperatingSystem}}"],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
check=False,
|
||||
text=True,
|
||||
)
|
||||
summary = {
|
||||
"loaded_messages": total,
|
||||
"load_seconds": round(load_seconds, 2),
|
||||
"distribution": {
|
||||
"big": 70000,
|
||||
"mid": 20000,
|
||||
"medium_10x1000": 10000,
|
||||
"small_100x10": 1000,
|
||||
},
|
||||
"messages_relation_size": size,
|
||||
"history_index_deep": {
|
||||
"execution_ms": execution_ms(good_plan),
|
||||
"planning_ms": planning_ms(good_plan),
|
||||
"buffers": first_buffers(good_plan),
|
||||
},
|
||||
"history_index_first_page": {
|
||||
"execution_ms": execution_ms(first_plan),
|
||||
"buffers": first_buffers(first_plan),
|
||||
},
|
||||
"offset_5000": {
|
||||
"execution_ms": execution_ms(offset_plan),
|
||||
"buffers": first_buffers(offset_plan),
|
||||
},
|
||||
"created_at_index_deep": {
|
||||
"execution_ms": execution_ms(weak_plan),
|
||||
"buffers": first_buffers(weak_plan),
|
||||
},
|
||||
"write_cost": [pk_only, with_hist, with_body],
|
||||
"dump_seconds": round(dump_seconds, 3),
|
||||
"restore_seconds": round(restore_seconds, 3),
|
||||
"counts": src_counts,
|
||||
"postgres": version,
|
||||
"durability": settings.splitlines(),
|
||||
"docker_info": info.stdout.strip(),
|
||||
"api_first_page_matches_sql": True,
|
||||
}
|
||||
(EVIDENCE / "track2_summary.json").write_text(
|
||||
json.dumps(summary, ensure_ascii=False, indent=2) + "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
log("PASS track2")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,61 @@
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def compose(*args, check=True, input_bytes=None, timeout=180):
|
||||
proc = subprocess.run(
|
||||
["docker", "compose", "--env-file", ".env", *args],
|
||||
cwd=ROOT,
|
||||
input=input_bytes,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
timeout=timeout,
|
||||
check=False,
|
||||
)
|
||||
if check and proc.returncode != 0:
|
||||
err = proc.stderr.decode("utf-8", "replace")[-800:]
|
||||
raise RuntimeError(err or "docker compose failed")
|
||||
return proc
|
||||
|
||||
|
||||
def psql(sql, timeout=180):
|
||||
proc = compose(
|
||||
"exec",
|
||||
"-T",
|
||||
"postgres",
|
||||
"psql",
|
||||
"-U",
|
||||
"messenger",
|
||||
"-d",
|
||||
"messenger",
|
||||
"-v",
|
||||
"ON_ERROR_STOP=1",
|
||||
"-q",
|
||||
"-t",
|
||||
"-A",
|
||||
input_bytes=sql.encode("utf-8"),
|
||||
timeout=timeout,
|
||||
)
|
||||
return proc.stdout.decode("utf-8").strip()
|
||||
|
||||
|
||||
def psql_file(sql, timeout=180):
|
||||
"""Текст плана, без -t, чтобы EXPLAIN остался читаемым."""
|
||||
proc = compose(
|
||||
"exec",
|
||||
"-T",
|
||||
"postgres",
|
||||
"psql",
|
||||
"-U",
|
||||
"messenger",
|
||||
"-d",
|
||||
"messenger",
|
||||
"-v",
|
||||
"ON_ERROR_STOP=1",
|
||||
"-X",
|
||||
input_bytes=sql.encode("utf-8"),
|
||||
timeout=timeout,
|
||||
)
|
||||
return proc.stdout.decode("utf-8")
|
||||
Reference in New Issue
Block a user