feat: PostgreSQL, Bearer-сессии (Valkey/PostgreSQL), Argon2id, миграции, compose

- схема и миграции (migrations/0001_init.sql, python -m messenger.migrate);
- регистрация с паролем (Argon2id), вход по Basic, opaque Bearer, logout, expiry;
- сессии: SESSION_STORE=valkey (AOF, appendfsync always) или postgres;
- пул соединений, statement/lock timeout и клиентский дедлайн: отказ БД = 503;
- keyset-пагинация по индексу (chat_id, created_at, id), два запроса без OR;
- compose.yaml с закреплёнными образами, secrets, restart.sh.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alexey Bodanyuk
2026-10-12 19:24:11 +03:00
co-authored by Claude Opus 5.5
parent 893beaa79a
commit 01524165dd
28 changed files with 1710 additions and 249 deletions
+47
View File
@@ -0,0 +1,47 @@
#!/usr/bin/env python3
"""Create local synthetic credentials for the stand in ./secrets (ignored by Git).
python scripts/init_secrets.py
Idempotent: existing files are kept, so re-running never changes passwords of a
database that already has data. Prints only file names, never values.
Delete ./secrets together with the volumes (`docker compose down -v`) to start over.
"""
from __future__ import annotations
import os
import secrets
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
SECRETS = ROOT / "secrets"
def write(name: str, value: str) -> None:
path = SECRETS / name
if path.exists():
print(f"keep secrets/{name}")
return
path.write_text(value + "\n", encoding="utf-8", newline="\n")
# Readable by the container users (postgres, valkey, app uid 10001) through the
# compose bind mount. Local synthetic lab credentials only.
os.chmod(path, 0o644)
print(f"created secrets/{name}")
def read(name: str) -> str:
return (SECRETS / name).read_text(encoding="utf-8").strip()
def main() -> int:
SECRETS.mkdir(exist_ok=True)
write("postgres_password", secrets.token_urlsafe(24)) # [A-Za-z0-9_-]: safe inside URLs
write("valkey_password", secrets.token_urlsafe(24))
write("database_url", f"postgresql://messenger:{read('postgres_password')}@postgres:5432/messenger")
write("cache_url", f"redis://:{read('valkey_password')}@valkey:6379/0")
return 0
if __name__ == "__main__":
sys.exit(main())
+6
View File
@@ -0,0 +1,6 @@
@echo off
rem Windows wrapper: tests/resilience.py starts the hook as a program, and Windows
rem cannot execute a .sh file directly. Runs the same scripts\restart.sh with Git Bash.
rem python tests/resilience.py --mode persistence --action-script scripts/restart.cmd
"%ProgramFiles%\Git\bin\bash.exe" "%~dp0restart.sh"
exit /b %ERRORLEVEL%
+15
View File
@@ -0,0 +1,15 @@
#!/bin/sh
# Restart hook for `make test-persistence ACTION_SCRIPT=scripts/restart.sh`.
# Restarts the API and ALL state stores (PostgreSQL, Valkey) of compose.yaml.
# Volumes, schema and data are preserved: no `down -v`, no FLUSH, no re-seed.
# Output is suppressed by the test; run it by hand to see the steps.
set -eu
cd "$(dirname "$0")/.."
# 1. API first: no request is served while the stores restart underneath it.
docker compose stop api
# 2. Stores: clean shutdown (PostgreSQL checkpoint, Valkey AOF fsync), then start again.
docker compose restart postgres valkey
# 3. API again; it waits for healthy stores via depends_on and reconnects its pool.
docker compose start api
echo "restart.sh: api, postgres and valkey restarted with volumes preserved"