forked from mtusi2026/mtusi2026lab2
90 lines
2.5 KiB
Python
90 lines
2.5 KiB
Python
"""Populate a chat with 10000 messages and run EXPLAIN (ANALYZE, BUFFERS).
|
|
|
|
Saves the plan to evidence/explain.txt for the report.
|
|
"""
|
|
import base64
|
|
import time
|
|
import uuid
|
|
from pathlib import Path
|
|
|
|
import httpx
|
|
|
|
BASE = "http://localhost:8080"
|
|
EVIDENCE = Path(__file__).resolve().parent.parent / "evidence" / "explain.txt"
|
|
|
|
|
|
def register_and_login(client: httpx.Client) -> dict:
|
|
username = "explain_" + uuid.uuid4().hex[:10]
|
|
password = "Test-password-1234"
|
|
r = client.post(
|
|
f"{BASE}/api/v1/users",
|
|
json={
|
|
"username": username,
|
|
"display_name": "Explain",
|
|
"password": password,
|
|
},
|
|
)
|
|
assert r.status_code == 201, r.text
|
|
user = r.json()
|
|
|
|
credential = base64.b64encode(
|
|
(username + ":" + password).encode("utf-8")
|
|
).decode("ascii")
|
|
r = client.post(
|
|
f"{BASE}/api/v1/auth/sessions",
|
|
headers={"Authorization": "Basic " + credential},
|
|
)
|
|
assert r.status_code == 201, r.text
|
|
session = r.json()
|
|
return {"id": user["id"], "token": session["token"]}
|
|
|
|
|
|
def auth(actor: dict) -> dict:
|
|
return {"Authorization": "Bearer " + actor["token"]}
|
|
|
|
|
|
def main():
|
|
total = 10000
|
|
print(f"Setting up {total} messages...")
|
|
|
|
with httpx.Client(timeout=120) as c:
|
|
alice = register_and_login(c)
|
|
bob = register_and_login(c)
|
|
chat = c.post(
|
|
f"{BASE}/api/v1/chats",
|
|
json={"title": "explain", "member_ids": [alice["id"], bob["id"]]},
|
|
headers=auth(alice),
|
|
).json()
|
|
|
|
print(f"chat_id = {chat['id']}")
|
|
|
|
batch = 200
|
|
started = time.monotonic()
|
|
for i in range(0, total, batch):
|
|
for j in range(batch):
|
|
c.post(
|
|
f"{BASE}/api/v1/chats/{chat['id']}/messages",
|
|
json={"text": f"msg-{i+j:05d}"},
|
|
headers=auth(alice),
|
|
)
|
|
if (i + batch) % 2000 == 0:
|
|
elapsed = time.monotonic() - started
|
|
print(f" {i+batch}/{total} messages, {elapsed:.1f}s")
|
|
|
|
print(f"Setup done in {time.monotonic() - started:.1f}s")
|
|
print(f"chat_id: {chat['id']}")
|
|
|
|
print("Run in psql:")
|
|
print(f"""
|
|
EXPLAIN (ANALYZE, BUFFERS)
|
|
SELECT id, chat_id, sender_id, text, created_at
|
|
FROM messages
|
|
WHERE chat_id = '{chat['id']}'
|
|
AND (created_at, id) > ('2026-01-01T00:00:00Z'::timestamptz, '00000000-0000-0000-0000-000000000000'::uuid)
|
|
ORDER BY created_at, id
|
|
LIMIT 51;
|
|
""")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main() |