forked from mtusi2026/mtusi2026lab2
Implement lab2 PostgreSQL authentication and Redis sessions
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
"""Create synthetic 10k-message history and print query plan. Execute inside api container.
|
||||
Only generates isolated synthetic UUID user/chat; never truncates real data.
|
||||
"""
|
||||
import os
|
||||
import uuid
|
||||
import psycopg
|
||||
|
||||
|
||||
def main():
|
||||
uid, cid = uuid.uuid4(), uuid.uuid4()
|
||||
with psycopg.connect(os.environ['DATABASE_URL']) as conn:
|
||||
conn.execute("INSERT INTO users(id,username,display_name,password_hash) VALUES (%s,%s,%s,%s)",
|
||||
(uid, 'ex_' + uuid.uuid4().hex[:12], b'EXPLAIN fixture', 'synthetic-not-for-login'))
|
||||
conn.execute("INSERT INTO chats(id,title) VALUES (%s,%s)", (cid,b'EXPLAIN synthetic history'))
|
||||
conn.execute("INSERT INTO chat_members(chat_id,user_id,position) VALUES (%s,%s,0)", (cid,uid))
|
||||
conn.execute("""
|
||||
INSERT INTO messages(id,chat_id,sender_id,text,created_at)
|
||||
SELECT gen_random_uuid(), %s, %s, convert_to('synthetic-' || n::text, 'UTF8'),
|
||||
clock_timestamp() + (n * interval '1 microsecond')
|
||||
FROM generate_series(1, 10000) AS n
|
||||
""", (cid,uid))
|
||||
middle = conn.execute("""
|
||||
SELECT created_at,id FROM messages WHERE chat_id=%s
|
||||
ORDER BY created_at,id OFFSET 5000 LIMIT 1
|
||||
""", (cid,)).fetchone()
|
||||
conn.execute('ANALYZE messages')
|
||||
count = conn.execute('SELECT count(*) FROM messages WHERE chat_id=%s', (cid,)).fetchone()[0]
|
||||
assert count==10000
|
||||
plan = conn.execute("""
|
||||
EXPLAIN (ANALYZE,BUFFERS)
|
||||
SELECT id,chat_id,sender_id,text,created_at
|
||||
FROM messages WHERE chat_id=%s AND (created_at,id)>(%s,%s)
|
||||
ORDER BY created_at,id LIMIT 50
|
||||
""", (cid,*middle)).fetchall()
|
||||
print('Fixture chat_id:', cid, '; history size:', count)
|
||||
print('\n'.join(row[0] for row in plan))
|
||||
print('Index intended: idx_messages_chat_history (chat_id,created_at,id)')
|
||||
print('Fixture retained to reproduce measurements; clean only in isolated test volume.')
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,35 @@
|
||||
@echo off
|
||||
setlocal EnableExtensions
|
||||
cd /d "%~dp0.."
|
||||
if errorlevel 1 goto :fail
|
||||
|
||||
echo [restart] Stopping API...
|
||||
docker compose --env-file .env stop api
|
||||
if errorlevel 1 goto :fail
|
||||
|
||||
echo [restart] Stopping Redis...
|
||||
docker compose --env-file .env stop redis
|
||||
if errorlevel 1 goto :fail
|
||||
|
||||
echo [restart] Stopping PostgreSQL...
|
||||
docker compose --env-file .env stop postgres
|
||||
if errorlevel 1 goto :fail
|
||||
|
||||
echo [restart] Starting storage services and waiting for healthchecks...
|
||||
docker compose --env-file .env up -d --no-deps --wait --wait-timeout 45 postgres redis
|
||||
if errorlevel 1 goto :fail
|
||||
|
||||
echo [restart] Starting API...
|
||||
docker compose --env-file .env up -d --no-deps api
|
||||
if errorlevel 1 goto :fail
|
||||
|
||||
echo [restart] Waiting for API readiness (PostgreSQL + Redis)...
|
||||
powershell.exe -NoProfile -NonInteractive -Command "$deadline=(Get-Date).AddSeconds(30); while((Get-Date) -lt $deadline) { try { $r=Invoke-WebRequest -UseBasicParsing -Uri 'http://127.0.0.1:8080/health/ready' -TimeoutSec 2 -ErrorAction Stop; if($r.StatusCode -eq 200) { exit 0 } } catch {} ; Start-Sleep -Seconds 1 }; exit 1"
|
||||
if errorlevel 1 goto :fail
|
||||
|
||||
echo [restart] OK: all runtime services restarted; API ready.
|
||||
exit /b 0
|
||||
|
||||
:fail
|
||||
echo [restart] FAILED. Inspect docker compose ps and logs. 1>&2
|
||||
exit /b 1
|
||||
Executable
+37
@@ -0,0 +1,37 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
compose() {
|
||||
docker compose --env-file .env "$@"
|
||||
}
|
||||
|
||||
printf '%s\n' '[restart] Stopping API...'
|
||||
compose stop api
|
||||
|
||||
printf '%s\n' '[restart] Stopping Redis...'
|
||||
compose stop redis
|
||||
|
||||
printf '%s\n' '[restart] Stopping PostgreSQL...'
|
||||
compose stop postgres
|
||||
|
||||
printf '%s\n' '[restart] Starting PostgreSQL and Redis; waiting for healthchecks...'
|
||||
compose up -d --no-deps --wait --wait-timeout 60 postgres redis
|
||||
|
||||
printf '%s\n' '[restart] Starting API...'
|
||||
compose up -d --no-deps api
|
||||
|
||||
printf '%s\n' '[restart] Waiting for API readiness...'
|
||||
i=0
|
||||
while [ "$i" -lt 60 ]; do
|
||||
if compose exec -T api python -c 'import urllib.request; urllib.request.urlopen("http://127.0.0.1:8080/health/ready", timeout=2)' >/dev/null 2>&1; then
|
||||
printf '%s\n' '[restart] OK: all runtime services restarted; API ready.'
|
||||
exit 0
|
||||
fi
|
||||
i=$((i + 1))
|
||||
sleep 1
|
||||
done
|
||||
|
||||
printf '%s\n' '[restart] FAILED: API did not become ready within 60 seconds; inspect docker compose ps/logs.' >&2
|
||||
exit 1
|
||||
@@ -0,0 +1,31 @@
|
||||
"""Show PostgreSQL rollback after partial composite operation, without modifying API code.
|
||||
Same two-table transaction pattern used by POST /chats, inject a FK failure midway.
|
||||
"""
|
||||
import os
|
||||
import uuid
|
||||
import psycopg
|
||||
from psycopg.errors import ForeignKeyViolation
|
||||
|
||||
|
||||
def main():
|
||||
with psycopg.connect(os.environ['DATABASE_URL']) as conn:
|
||||
uid = conn.execute('SELECT id FROM users LIMIT 1').fetchone()
|
||||
if uid is None:
|
||||
print('Create a user with make test first')
|
||||
raise SystemExit(1)
|
||||
cid = uuid.uuid4()
|
||||
try:
|
||||
with conn.transaction():
|
||||
conn.execute('INSERT INTO chats(id,title) VALUES (%s,%s)', (cid, b'Rollback test'))
|
||||
conn.execute('INSERT INTO chat_members(chat_id,user_id,position) VALUES (%s,%s,0)', (cid, uid[0]))
|
||||
conn.execute('INSERT INTO chat_members(chat_id,user_id,position) VALUES (%s,%s,1)', (cid, uuid.uuid4()))
|
||||
raise AssertionError('FK should have failed')
|
||||
except ForeignKeyViolation:
|
||||
pass
|
||||
# Connection still usable because transaction block rolled back.
|
||||
orphan = conn.execute('SELECT 1 FROM chats WHERE id=%s', (cid,)).fetchone()
|
||||
assert orphan is None, 'partial chat remained after rollback'
|
||||
print('PASS: composite chat insert was fully rolled back after FK failure')
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user