forked from mtusi2026/mtusi2026lab2
feat: persist messenger data and sessions in PostgreSQL
This commit is contained in:
@@ -0,0 +1,31 @@
|
||||
"""Checks the level-four database and cache failure paths on the isolated Compose project."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
import base64,os,subprocess,sys,time,uuid
|
||||
root=Path(__file__).resolve().parents[1];os.chdir(root);sys.path.insert(0,str(root/'tests'))
|
||||
from client import Client
|
||||
def compose(*args,env=None):subprocess.run(['docker','compose',*args],check=True,env=env,stdout=subprocess.DEVNULL)
|
||||
def ready(c):
|
||||
for i in range(60):
|
||||
try:c.call('GET','/health/ready',schema='Health');return
|
||||
except AssertionError:time.sleep(1)
|
||||
raise RuntimeError('readiness deadline')
|
||||
c=Client();a,b,_,chat=c.bootstrap()
|
||||
body={**a['registration'],'username':'race_'+uuid.uuid4().hex[:12]}
|
||||
with ThreadPoolExecutor(8) as pool:
|
||||
codes=list(pool.map(lambda _:Client().call('POST','/api/v1/users',(201,409),body=body)['status'],range(8)))
|
||||
assert sorted(codes)==[201]+[409]*7
|
||||
def count():
|
||||
return subprocess.check_output(['docker','compose','exec','-T','db','psql','-U','lab','-d','lab','-XAtc','SELECT count(*) FROM chats'],text=True)
|
||||
before=count();c.call('POST','/api/v1/chats',400,actor=a,body={'title':'rollback','member_ids':[a['id'],str(uuid.uuid4())]});assert count()==before
|
||||
try:
|
||||
compose('stop','cache');c.call('GET','/api/v1/users/me',actor=a,schema='User');c.call('GET','/api/v1/users/me',401)
|
||||
finally:compose('start','cache')
|
||||
try:
|
||||
compose('stop','db');c.call('GET','/health/live',schema='Health');c.call('GET','/health/ready',503);c.call('GET','/api/v1/users/me',503,actor=a)
|
||||
finally:compose('start','db');ready(c)
|
||||
try:
|
||||
compose('up','-d','--no-deps','api',env={**os.environ,'SESSION_TTL_SECONDS':'2'});ready(c)
|
||||
actor=c.user('expiry');time.sleep(3);c.call('GET','/api/v1/users/me',401,actor=actor)
|
||||
finally:compose('up','-d','--no-deps','api');ready(c)
|
||||
print('Concurrent registration, rollback, cache outage, DB outage and session expiry passed.')
|
||||
Executable
+10
@@ -0,0 +1,10 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
umask 077
|
||||
if [ -e .env ]; then echo 'Using existing .env'; exit 0; fi
|
||||
set -C
|
||||
{
|
||||
printf 'PG_PASS=%s\n' "$(openssl rand -hex 24)"
|
||||
printf 'CACHE_PASS=%s\n' "$(openssl rand -hex 24)"
|
||||
} > .env
|
||||
Executable
+42
@@ -0,0 +1,42 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
runid=$(date +%Y%m%d%H%M%S)
|
||||
out=evidence/plans-$runid
|
||||
mkdir -p "$out"
|
||||
src=bench_$runid; restored=restore_$runid
|
||||
pg=(docker compose exec -T db)
|
||||
"${pg[@]}" createdb -U lab "$src"
|
||||
"${pg[@]}" createdb -U lab "$restored"
|
||||
sql=("${pg[@]}" psql -X -U lab -v ON_ERROR_STOP=1 -d "$src")
|
||||
"${sql[@]}" < migrations/001.sql >/dev/null
|
||||
"${sql[@]}" > "$out/plans.txt" <<'SQL'
|
||||
\timing on
|
||||
INSERT INTO users(username,display_name,salt,hash) VALUES('bench','Bench','dummy','dummy');
|
||||
INSERT INTO chats(title) SELECT 'c'||g FROM generate_series(1,10) g;
|
||||
CREATE TEMP TABLE seed AS SELECT c.id chat_id,u.id sender_id,'sample '||g AS text FROM generate_series(1,100000) g JOIN chats c ON c.title='c'||CASE WHEN g<=90000 THEN 1 ELSE 2+g%9 END CROSS JOIN users u;
|
||||
DROP INDEX history_key;
|
||||
CREATE TABLE alternative (LIKE messages INCLUDING ALL);
|
||||
ALTER TABLE alternative ADD FOREIGN KEY(chat_id) REFERENCES chats, ADD FOREIGN KEY(sender_id) REFERENCES users;
|
||||
CREATE INDEX alt_chat ON alternative(chat_id);
|
||||
INSERT INTO alternative(chat_id,sender_id,text) SELECT * FROM seed;
|
||||
CREATE INDEX history_key ON messages(chat_id,created_at,id);
|
||||
INSERT INTO messages(chat_id,sender_id,text) SELECT * FROM seed;
|
||||
ANALYZE messages;
|
||||
ANALYZE alternative;
|
||||
SELECT id AS cid FROM chats WHERE title='c1' \gset
|
||||
EXPLAIN(ANALYZE,BUFFERS) SELECT * FROM alternative WHERE chat_id=:'cid' ORDER BY created_at DESC,id DESC LIMIT 51;
|
||||
EXPLAIN(ANALYZE,BUFFERS) SELECT * FROM messages WHERE chat_id=:'cid' ORDER BY created_at DESC,id DESC LIMIT 51;
|
||||
DROP TABLE alternative;
|
||||
SQL
|
||||
start=$SECONDS
|
||||
"${pg[@]}" pg_dump -Fc -U lab "$src" > "$out/benchmark.dump"
|
||||
echo "dump_seconds=$((SECONDS-start))" > "$out/recovery.txt"
|
||||
start=$SECONDS
|
||||
"${pg[@]}" pg_restore --exit-on-error -U lab -d "$restored" < "$out/benchmark.dump"
|
||||
echo "restore_seconds=$((SECONDS-start))" >> "$out/recovery.txt"
|
||||
for database in "$src" "$restored"; do
|
||||
"${pg[@]}" psql -XAt -U lab -d "$database" -c "SELECT count(*),md5(string_agg(id::text||chat_id::text||sender_id::text||text||created_at::text,'' ORDER BY id)) FROM messages" > "$out/$database.digest"
|
||||
done
|
||||
diff -u "$out/$src.digest" "$out/$restored.digest"
|
||||
echo "Databases retained: $src and $restored"
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose restart db cache api
|
||||
Reference in New Issue
Block a user