Добавить PostgreSQL, постоянные сессии, кэш и проверки ЛР2

This commit is contained in:
2026-10-30 17:24:20 +03:00
parent 65003b6119
commit a39b4fea27
29 changed files with 2776 additions and 20 deletions
+30
View File
@@ -0,0 +1,30 @@
#!/usr/bin/env python3
"""Create a private local secret directory once; never rotate existing volumes implicitly."""
import os
import secrets
from pathlib import Path
root = Path(__file__).resolve().parents[1]
private = root / "secrets"
private.mkdir(mode=0o700, exist_ok=True)
os.chmod(private, 0o700)
password_file = private / "postgres_password"
if not password_file.exists():
password_file.write_text(secrets.token_urlsafe(32))
password = password_file.read_text().strip()
values = {
"database_url": "postgresql://messenger:" + password + "@postgres:5432/messenger",
"cache_url": "redis://cache:6379/0",
}
for name, value in values.items():
path = private / name
if not path.exists():
path.write_text(value)
# The parent directory is private on the host; files must be readable by non-root API
# through Compose's file-backed secret mount (uid/mode mapping is not portable).
for path in private.iterdir():
os.chmod(path, 0o644)
if not (root / ".env").exists():
(root / ".env").write_text("PUBLIC_PORT=8082\nSESSION_TTL_SECONDS=3600\n")
print("Local configuration ready; existing secret values preserved.")
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
docker compose restart postgres cache api
+198
View File
@@ -0,0 +1,198 @@
#!/usr/bin/env python3
"""Real PostgreSQL/cache faults, unchanged sessions, expiry, rollback and bounded SQL."""
import argparse
import json
import subprocess
import sys
import time
import uuid
from datetime import UTC, datetime
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure # noqa: E402
def compose(*args, timeout=60):
result = subprocess.run(
["docker", "compose", *args], cwd=ROOT, capture_output=True, text=True, timeout=timeout
)
if result.returncode:
raise RuntimeError("Compose action failed: " + args[0])
return result.stdout.strip()
def states():
ids = compose("ps", "-q", "api", "postgres", "cache").split()
data = json.loads(subprocess.check_output(["docker", "inspect", *ids], text=True))
return {
d["Config"]["Labels"]["com.docker.compose.service"]: {
"cid": d["Id"],
"pid": d["State"]["Pid"],
"started_at": d["State"]["StartedAt"],
}
for d in data
}
def wait(client):
deadline = time.monotonic() + 40
while True:
try:
client.call("GET", "/health/ready", schema="Health")
return
except Failure:
if time.monotonic() > deadline:
raise
time.sleep(0.3)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--base-url", default="http://127.0.0.1:8082")
parser.add_argument("--short-url", default="http://127.0.0.1:18082")
parser.add_argument("--output", default="evidence/lifecycle.json")
args = parser.parse_args()
output = ROOT / args.output
if output.exists():
raise SystemExit("Use a new evidence filename")
c = Client(args.base_url)
alice, bob, _, chat = c.bootstrap()
message = c.message(alice, chat, "Пережить реальный перезапуск")["json"]
result = {"date_utc": datetime.now(UTC).isoformat(), "passed": False}
before = states()
public = subprocess.run(
[
sys.executable,
"tests/resilience.py",
"--mode",
"persistence",
"--action-script",
"scripts/restart.sh",
"--base-url",
c.base,
],
cwd=ROOT,
capture_output=True,
text=True,
timeout=180,
)
assert public.returncode == 0, "Public persistence failed"
result["public_persistence"] = public.stdout.strip()
after = states()
assert before.keys() == after.keys() == {"api", "postgres", "cache"}
for service in before:
assert before[service]["started_at"] != after[service]["started_at"]
assert before[service]["pid"] != after[service]["pid"]
result.update(before=before, after=after)
assert c.call("GET", "/api/v1/users/me", actor=alice, schema="User")["json"] == alice["user"]
data = c.call("GET", f"/api/v1/chats/{chat['id']}/messages", actor=bob, schema="MessagePage")[
"json"
]
assert data["items"] == [message]
result["same_token_and_message_after_restart"] = True
# A real key must exist: cache role is verified, not just configured.
keys = int(compose("exec", "-T", "cache", "valkey-cli", "DBSIZE"))
assert keys > 0
compose("exec", "-T", "cache", "valkey-cli", "FLUSHDB")
c.call("GET", "/api/v1/users/me", actor=alice, schema="User")
assert int(compose("exec", "-T", "cache", "valkey-cli", "DBSIZE")) > 0
result["cache_flush_repopulates"] = True
try:
compose("stop", "cache")
started = time.monotonic()
c.call("GET", "/api/v1/users/me", actor=alice, schema="User")
elapsed = time.monotonic() - started
assert elapsed < 3
c.call("GET", "/api/v1/users/me", 401)
result["cache_failure"] = {
"authenticated_status": 200,
"anonymous_status": 401,
"seconds": round(elapsed, 4),
}
finally:
compose("start", "cache")
try:
# This token was valid and its public user card is already cached.
c.call("GET", "/api/v1/users/me", actor=alice, schema="User")
compose("stop", "postgres")
started = time.monotonic()
c.call("GET", "/api/v1/users/me", 503, actor=alice)
elapsed = time.monotonic() - started
assert elapsed < 5
c.call("GET", "/health/ready", 503)
c.call("GET", "/health/live", schema="Health")
c.call("GET", "/api/v1/users/me", 401)
result["database_failure"] = {
"cached_actor_status": 503,
"ready_status": 503,
"live_status": 200,
"seconds": round(elapsed, 4),
}
finally:
compose("start", "postgres")
wait(c)
c.call("GET", "/api/v1/users/me", actor=alice, schema="User")
result["session_after_database_recovery"] = True
# Ensure a failure after the chat INSERT rolls back that INSERT as well as memberships.
title = "rollback_" + uuid.uuid4().hex
c.call(
"POST",
"/api/v1/chats",
400,
actor=alice,
body={"title": title, "member_ids": [alice["id"], str(uuid.uuid4())]},
)
count = compose(
"exec",
"-T",
"postgres",
"psql",
"-U",
"messenger",
"-d",
"messenger",
"-Atc",
"SELECT count(*) FROM chats WHERE title='" + title + "'",
)
assert count == "0"
result["failed_chat_transaction_left_rows"] = 0
compose("run", "--rm", "migrate")
compose("run", "--rm", "migrate")
result["migrations_reapplied_twice"] = True
short = Client(args.short_url)
short_actor = short.user("expiry")
start = time.monotonic()
short.call("GET", "/api/v1/users/me", actor=short_actor, schema="User")
time.sleep(2.2)
short.call("GET", "/api/v1/users/me", 401, actor=short_actor)
result["expiry"] = {
"configured_ttl_seconds": 2,
"observed_after_seconds": round(time.monotonic() - start, 4),
"expired_status": 401,
}
c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=alice)
c.call("GET", "/api/v1/users/me", 401, actor=alice)
result["logout_with_cached_user"] = 401
# Tokens and passwords remain in this process; scan their actual values without saving them.
ids = compose("ps", "-q", "api").split()
logs = subprocess.run(["docker", "logs", ids[0]], capture_output=True, text=True, check=True)
text = logs.stdout + logs.stderr
for person in [alice, bob, short_actor]:
assert person["token"] not in text
assert person["registration"]["password"] not in text
result["credentials_absent_from_api_logs"] = True
result["passed"] = True
output.parent.mkdir(exist_ok=True, parents=True)
output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n")
print("PASS: real restart, same token, cache/DB faults, rollback, expiry and logout")
if __name__ == "__main__":
main()
+62
View File
@@ -0,0 +1,62 @@
#!/usr/bin/env python3
"""Probe the real bounded pool in an isolated process against the teaching database."""
import argparse
import json
import subprocess
from datetime import UTC, datetime
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
PROBE = """
import json, threading, time
from concurrent.futures import ThreadPoolExecutor
from messenger.postgres import PostgresStore
from messenger.domain import Failure
store=PostgresStore()
barrier=threading.Barrier(50)
def work(i):
barrier.wait()
start=time.monotonic()
try:
with store.connection() as conn:
conn.execute("SELECT pg_sleep(2.2)")
return {"status":200,"seconds":time.monotonic()-start}
except Failure as e:
return {"status":e.status,"seconds":time.monotonic()-start}
with ThreadPoolExecutor(max_workers=50) as executor:
rows=list(executor.map(work,range(50)))
store.close()
assert any(r["status"]==200 for r in rows)
assert any(r["status"]==503 for r in rows)
assert max(r["seconds"] for r in rows)<5
print(json.dumps({"passed":True,"clients":50,"max_pool_size":8,"max_waiting":32,
"admitted":sum(r["status"]==200 for r in rows),"rejected_503":sum(r["status"]==503 for r in rows),
"max_seconds":max(r["seconds"] for r in rows),"rows":rows}))
"""
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--output", default="evidence/pool.json")
args = parser.parse_args()
path = ROOT / args.output
if path.exists():
raise SystemExit("Choose a new evidence filename")
process = subprocess.run(
["docker", "compose", "exec", "-T", "api", "python", "-c", PROBE],
cwd=ROOT,
capture_output=True,
text=True,
timeout=25,
)
if process.returncode:
raise SystemExit("Pool probe failed; inspect source and dependency readiness")
result = json.loads(process.stdout)
result["date_utc"] = datetime.now(UTC).isoformat()
path.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n")
print("PASS: real bounded connection pool overload returns 503")
if __name__ == "__main__":
main()