Lab2: PostgreSQL, Bearer sessions and Redis for grade 4

This commit is contained in:
2026-10-29 01:25:40 +03:00
parent 65003b6119
commit 3c5af42f24
35 changed files with 2126 additions and 25 deletions
+65
View File
@@ -0,0 +1,65 @@
#!/usr/bin/env python3
"""Seed ≥10k messages and print EXPLAIN (ANALYZE, BUFFERS) for keyset page query."""
from __future__ import annotations
import os
import sys
import uuid
from pathlib import Path
# Allow running against a live API + direct DB for EXPLAIN.
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from app.config import settings # noqa: E402
from app.db import Database # noqa: E402
from app.models import Chat, Message, User # noqa: E402
from app.password import hash_password # noqa: E402
from app.timefmt import now_utc # noqa: E402
def main() -> int:
count = int(os.environ.get("EXPLAIN_MESSAGES", "10000"))
db = Database()
db.open()
user = User(
id=str(uuid.uuid4()),
username="explain_" + uuid.uuid4().hex[:10],
display_name="Explain",
created_at=now_utc(),
password_hash=hash_password("Explain-password-12"),
)
db.add_user(user)
chat = Chat(
id=str(uuid.uuid4()),
title="EXPLAIN chat",
member_ids=[user.id],
created_at=now_utc(),
)
db.add_chat(chat)
for i in range(count):
db.add_message(
Message(
id=str(uuid.uuid4()),
chat_id=chat.id,
sender_id=user.id,
text="bulk-%d" % i,
created_at=now_utc(),
)
)
if (i + 1) % 2000 == 0:
print("inserted", i + 1, flush=True)
plan = db.explain_messages_page(chat.id, limit=50)
out = ROOT / "evidence" / "explain.txt"
out.write_text(
"chat_id=%s messages=%d\n\n%s\n" % (chat.id, count, plan),
encoding="utf-8",
)
print(plan)
print("wrote", out)
db.close()
return 0
if __name__ == "__main__":
raise SystemExit(main())
+13
View File
@@ -0,0 +1,13 @@
# Creates local synthetic secrets for compose (never commit secrets/).
$ErrorActionPreference = "Stop"
$root = Split-Path -Parent $PSScriptRoot
$secrets = Join-Path $root "secrets"
New-Item -ItemType Directory -Force -Path $secrets | Out-Null
$password = "lab2-pg-pass-" + [guid]::NewGuid().ToString("N").Substring(0, 12)
Set-Content -Path (Join-Path $secrets "postgres_password") -Value $password -NoNewline
# URL for the API container (service DNS name "postgres" / "redis").
$dbUrl = "postgresql://messenger:${password}@postgres:5432/messenger"
Set-Content -Path (Join-Path $secrets "database_url") -Value $dbUrl -NoNewline
Set-Content -Path (Join-Path $secrets "cache_url") -Value "redis://redis:6379/0" -NoNewline
Write-Host "Wrote secrets/postgres_password, secrets/database_url, secrets/cache_url"
+9
View File
@@ -0,0 +1,9 @@
#!/bin/sh
set -eu
ROOT="$(CDPATH= cd -- "$(dirname "$0")/.." && pwd)"
mkdir -p "$ROOT/secrets"
PASSWORD="lab2-pg-pass-$(openssl rand -hex 6)"
printf '%s' "$PASSWORD" > "$ROOT/secrets/postgres_password"
printf '%s' "postgresql://messenger:${PASSWORD}@postgres:5432/messenger" > "$ROOT/secrets/database_url"
printf '%s' "redis://redis:6379/0" > "$ROOT/secrets/cache_url"
echo "Wrote secrets/postgres_password, secrets/database_url, secrets/cache_url"
+5
View File
@@ -0,0 +1,5 @@
@echo off
REM Restart API and all state stores without removing volumes (Windows host).
cd /d "%~dp0.."
docker compose --env-file .env restart
exit /b %ERRORLEVEL%
+6
View File
@@ -0,0 +1,6 @@
#!/bin/sh
set -eu
# Restart API and all state stores (postgres, redis) without removing volumes.
cd "$(dirname "$0")/.."
docker compose --env-file .env restart
exit 0
+56
View File
@@ -0,0 +1,56 @@
#!/usr/bin/env python3
"""Raw expiry check without OpenAPI schema validation overhead."""
import base64
import json
import time
import urllib.error
import urllib.request
import uuid
base = "http://127.0.0.1:8080"
username = "u_raw_" + uuid.uuid4().hex[:10]
password = "T3st-" + uuid.uuid4().hex
body = json.dumps(
{"username": username, "display_name": "Raw", "password": password}
).encode()
req = urllib.request.Request(
base + "/api/v1/users",
data=body,
headers={"Content-Type": "application/json", "Accept": "application/json"},
method="POST",
)
with urllib.request.urlopen(req, timeout=30) as r:
user = json.loads(r.read())
print("user", user["id"])
cred = base64.b64encode((username + ":" + password).encode()).decode()
req = urllib.request.Request(
base + "/api/v1/auth/sessions",
data=b"",
headers={"Authorization": "Basic " + cred, "Accept": "application/json"},
method="POST",
)
with urllib.request.urlopen(req, timeout=30) as r:
session = json.loads(r.read())
print("token_prefix", session["token"][:16], "exp", session["expires_at"])
req = urllib.request.Request(
base + "/api/v1/users/me",
headers={"Authorization": "Bearer " + session["token"], "Accept": "application/json"},
)
with urllib.request.urlopen(req, timeout=10) as r:
print("me", json.loads(r.read())["id"])
time.sleep(6)
req = urllib.request.Request(
base + "/api/v1/users/me",
headers={"Authorization": "Bearer " + session["token"], "Accept": "application/json"},
)
try:
urllib.request.urlopen(req, timeout=10)
raise SystemExit("FAIL still valid")
except urllib.error.HTTPError as exc:
print("after wait status", exc.code)
if exc.code != 401:
raise SystemExit("expected 401")
print("PASS: session expired after short TTL")