Implement lab 2 PostgreSQL sessions and Redis profile cache

This commit is contained in:
2026-11-19 10:47:21 +03:00
parent 65003b6119
commit 370d947132
31 changed files with 1381 additions and 19 deletions
+21
View File
@@ -0,0 +1,21 @@
"""Create local synthetic secrets once; never overwrite existing credentials."""
import secrets
from pathlib import Path
root = Path(__file__).resolve().parents[1]
directory = root / 'secrets'
directory.mkdir(exist_ok=True)
password_file = directory / 'db_password'
if not password_file.exists():
with password_file.open('x', encoding='utf-8') as file:
file.write(secrets.token_urlsafe(32))
password = password_file.read_text(encoding='utf-8').strip()
url_file = directory / 'database_url'
if not url_file.exists():
with url_file.open('x', encoding='utf-8') as file:
file.write('postgresql://messenger:' + password + '@db:5432/messenger')
env = root / '.env'
if not env.exists():
with env.open('x', encoding='utf-8') as file:
file.write('SESSION_TTL_SECONDS=3600\n')
print('Local configuration ready; credentials are not printed.')
+30
View File
@@ -0,0 +1,30 @@
"""Real query-plan experiment with 12,000 messages; transaction rolls back fixtures."""
import json
import sys
import uuid
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from src.db import make_pool
pool = make_pool()
with pool.connection() as conn:
user_id, chat_id = uuid.uuid4(), uuid.uuid4()
conn.execute('INSERT INTO users(id,username,display_name,password_hash) VALUES (%s,%s,%s,%s)',
(user_id, 'plan_' + uuid.uuid4().hex[:20], 'Synthetic EXPLAIN', 'no-login'))
conn.execute('INSERT INTO chats(id,title) VALUES (%s,%s)', (chat_id, 'EXPLAIN dataset'))
conn.execute('INSERT INTO members VALUES (%s,%s)', (chat_id, user_id))
conn.execute("INSERT INTO messages(id,chat_id,sender_id,text,created_at) "
"SELECT gen_random_uuid(),%s,%s,'message ' || n, "
"'2026-01-01'::timestamptz + n * interval '1 microsecond' "
"FROM generate_series(1,12000) n", (chat_id, user_id))
conn.execute('ANALYZE messages')
pivot = conn.execute('SELECT created_at,id FROM messages WHERE chat_id=%s '
'ORDER BY created_at,id OFFSET 10000 LIMIT 1', (chat_id,)).fetchone()
plan = conn.execute('EXPLAIN (ANALYZE,BUFFERS,FORMAT JSON) SELECT * FROM messages '
'WHERE chat_id=%s AND (created_at,id)>(%s,%s) '
'ORDER BY created_at,id LIMIT 51',
(chat_id, pivot['created_at'], pivot['id'])).fetchone()['QUERY PLAN']
print(json.dumps({'dataset_messages': 12000, 'cursor_position': 10001,
'page_size_with_lookahead': 51, 'plan': plan}, indent=2, default=str))
conn.rollback()
pool.close()
+3
View File
@@ -0,0 +1,3 @@
@echo off
cd /d "%~dp0.."
docker compose restart api db redis
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
docker compose restart api db redis
+77
View File
@@ -0,0 +1,77 @@
"""Run acceptance evidence on the local Compose stack; no secrets in artifacts."""
import json
import os
import platform
import subprocess
import sys
import time
from datetime import datetime, timezone
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
EVIDENCE = ROOT / 'evidence'
ENV = {**os.environ, 'PYTHONUTF8': '1',
'BASE_URL': os.environ.get('BASE_URL', 'http://127.0.0.1:8080')}
def run(args, artifact=None):
result = subprocess.run(args, cwd=ROOT, text=True, encoding='utf-8', errors='replace',
capture_output=True, env=ENV)
output = result.stdout + result.stderr
print(output, end='', flush=True)
if artifact:
(EVIDENCE / artifact).write_text(output, encoding='utf-8')
if result.returncode:
raise SystemExit(result.returncode)
return result.stdout
def containers():
ids = run(['docker', 'compose', 'ps', '-q']).split()
result = subprocess.run(['docker', 'inspect', *ids], cwd=ROOT, text=True,
capture_output=True, check=True)
return [{'name': item['Name'], 'id': item['Id'],
'started_at': item['State']['StartedAt'], 'image': item['Config']['Image']}
for item in json.loads(result.stdout)]
def main():
run([sys.executable, 'scripts/check_contract.py'], 'contract.txt')
run([sys.executable, 'tests/smoke.py'], 'smoke.txt')
before = containers()
hook = 'scripts/restart.cmd' if os.name == 'nt' else 'scripts/restart.sh'
run([sys.executable, 'tests/resilience.py', '--mode', 'persistence',
'--action-script', hook], 'persistence.txt')
after = containers()
prior = {item['id']: item for item in before}
assert len(after) == 3 and all(item['id'] in prior and
item['started_at'] != prior[item['id']]['started_at']
for item in after), 'All three containers must really restart'
(EVIDENCE / 'restart.json').write_text(json.dumps({'before': before, 'after': after}, indent=2), encoding='utf-8')
run([sys.executable, 'student-tests/acceptance.py'], 'student-tests.txt')
run(['docker', 'compose', 'exec', '-T', 'api', 'python', 'scripts/explain.py'], 'query-plan.json')
process = subprocess.Popen([sys.executable, 'tests/load.py', '--duration', '30', '--concurrency', '4',
'--output', 'evidence/load.json'], cwd=ROOT,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
text=True, encoding='utf-8', env=ENV)
ids = [item['id'] for item in after]
samples = []
while process.poll() is None:
stats = subprocess.run(['docker', 'stats', '--no-stream', '--format',
'{{.Name}}: CPU={{.CPUPerc}} RAM={{.MemUsage}}', *ids],
capture_output=True, text=True, check=True)
samples.append({'at': datetime.now(timezone.utc).isoformat(), 'stats': stats.stdout.strip()})
time.sleep(2)
output = process.communicate()[0]
print(output, end='', flush=True)
(EVIDENCE / 'load.txt').write_text(output, encoding='utf-8')
(EVIDENCE / 'resources.json').write_text(json.dumps(samples, indent=2), encoding='utf-8')
if process.returncode:
raise SystemExit(process.returncode)
system = {'observed_at': datetime.now(timezone.utc).isoformat(), 'platform': platform.platform(),
'cpu': platform.processor(), 'logical_cpus': os.cpu_count(), 'python': platform.python_version()}
(EVIDENCE / 'environment.json').write_text(json.dumps(system, indent=2), encoding='utf-8')
if __name__ == '__main__':
main()