Implement lab2 PostgreSQL sessions and Redis cache

This commit is contained in:
Polusikkkk
2026-10-16 18:23:50 +03:00
parent 65003b6119
commit 083dc49564
25 changed files with 2782 additions and 29 deletions
+328
View File
@@ -0,0 +1,328 @@
from __future__ import annotations
import base64
import json
import os
import subprocess
import unittest
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from threading import Barrier
from urllib.error import HTTPError
from urllib.request import Request, urlopen
from uuid import uuid4
BASE_URL = os.getenv(
"BASE_URL",
"http://localhost:18081",
).rstrip("/")
PROJECT_DIR = Path(__file__).resolve().parent.parent
PASSWORD = "Synthetic-test-password-123"
class Lab2Checks(unittest.TestCase):
def request(
self,
method,
path,
payload=None,
token=None,
headers=None,
):
request_headers = dict(headers or {})
data = None
if payload is not None:
data = json.dumps(
payload,
ensure_ascii=False,
).encode("utf-8")
request_headers["Content-Type"] = "application/json"
if token is not None:
request_headers["Authorization"] = f"Bearer {token}"
request = Request(
BASE_URL + path,
data=data,
headers=request_headers,
method=method,
)
try:
response = urlopen(request, timeout=20)
except HTTPError as exc:
response = exc
with response:
status = response.code
response_headers = response.headers
raw = response.read()
request_id = response_headers.get("X-Request-Id")
self.assertTrue(request_id, "Missing X-Request-Id")
body = json.loads(raw.decode("utf-8")) if raw else None
if status >= 400:
self.assertIsInstance(body, dict)
self.assertEqual(set(body), {"error"})
self.assertEqual(
set(body["error"]),
{"code", "message", "request_id"},
)
self.assertEqual(
body["error"]["request_id"],
request_id,
)
return status, body, response_headers
def create_user(self, password=PASSWORD):
username = "u_" + uuid4().hex[:20]
status, user, _ = self.request(
"POST",
"/api/v1/users",
{
"username": username,
"display_name": "Тестовый пользователь",
"password": password,
},
)
self.assertEqual(status, 201)
self.assertEqual(
set(user),
{"id", "username", "display_name", "created_at"},
)
return username, user
def login(self, username, password=PASSWORD):
credentials = base64.b64encode(
f"{username}:{password}".encode("utf-8")
).decode("ascii")
return self.request(
"POST",
"/api/v1/auth/sessions",
headers={"Authorization": f"Basic {credentials}"},
)
def create_logged_in_user(self):
username, user = self.create_user()
status, session, _ = self.login(username)
self.assertEqual(status, 201)
return user, session["token"]
def database_counts(self):
result = subprocess.run(
[
"docker",
"compose",
"--env-file",
".env",
"exec",
"-T",
"postgres",
"psql",
"-U",
"messenger",
"-d",
"messenger",
"-At",
"-v",
"ON_ERROR_STOP=1",
"-c",
(
"SELECT "
"(SELECT count(*) FROM chats), "
"(SELECT count(*) FROM chat_members);"
),
],
cwd=PROJECT_DIR,
check=True,
capture_output=True,
text=True,
timeout=15,
)
return tuple(
int(value)
for value in result.stdout.strip().split("|")
)
def test_wrong_password(self):
username, _ = self.create_user()
status, body, headers = self.login(
username,
"Definitely-wrong-password-123",
)
self.assertEqual(status, 401)
self.assertEqual(body["error"]["code"], "unauthorized")
self.assertEqual(
headers.get("WWW-Authenticate"),
'Basic realm="messenger", charset="UTF-8"',
)
unknown_username = "missing_" + uuid4().hex[:16]
other_status, other_body, _ = self.login(
unknown_username,
"Definitely-wrong-password-123",
)
self.assertEqual(other_status, 401)
self.assertEqual(
body["error"]["message"],
other_body["error"]["message"],
)
def test_logout(self):
_, token = self.create_logged_in_user()
status, _, _ = self.request(
"GET",
"/api/v1/users/me",
token=token,
)
self.assertEqual(status, 200)
status, body, _ = self.request(
"DELETE",
"/api/v1/auth/sessions/current",
token=token,
)
self.assertEqual(status, 204)
self.assertIsNone(body)
status, _, headers = self.request(
"GET",
"/api/v1/users/me",
token=token,
)
self.assertEqual(status, 401)
self.assertEqual(
headers.get("WWW-Authenticate"),
'Bearer realm="messenger"',
)
status, _, _ = self.request(
"DELETE",
"/api/v1/auth/sessions/current",
token=token,
)
self.assertEqual(status, 401)
def test_x_user_id_does_not_authenticate_or_change_user(self):
first_user, token = self.create_logged_in_user()
_, second_user = self.create_user()
status, _, _ = self.request(
"GET",
"/api/v1/users/me",
headers={"X-User-Id": second_user["id"]},
)
self.assertEqual(status, 401)
status, body, _ = self.request(
"GET",
"/api/v1/users/me",
token=token,
headers={"X-User-Id": second_user["id"]},
)
self.assertEqual(status, 200)
self.assertEqual(body["id"], first_user["id"])
def test_unicode_password_with_colons(self):
password = "Учебный:пароль:длинный-123"
username, _ = self.create_user(password=password)
status, _, _ = self.login(username, password=password)
self.assertEqual(status, 201)
def test_concurrent_username_registration(self):
workers = 4
barrier = Barrier(workers)
username = "race_" + uuid4().hex[:20]
payload = {
"username": username,
"display_name": "Конкурентная регистрация",
"password": PASSWORD,
}
def register(_):
barrier.wait(timeout=10)
status, _, _ = self.request(
"POST",
"/api/v1/users",
payload,
)
return status
with ThreadPoolExecutor(max_workers=workers) as executor:
statuses = list(executor.map(register, range(workers)))
self.assertEqual(
sorted(statuses),
[201, 409, 409, 409],
)
status, _, _ = self.login(username)
self.assertEqual(status, 201)
def test_chat_creation_rollback(self):
user, token = self.create_logged_in_user()
before = self.database_counts()
status, body, _ = self.request(
"POST",
"/api/v1/chats",
{
"title": "Этот чат должен откатиться",
"member_ids": [
user["id"],
str(uuid4()),
],
},
token=token,
)
self.assertEqual(status, 400)
self.assertEqual(body["error"]["code"], "invalid_request")
after = self.database_counts()
self.assertEqual(
before,
after,
"Failed chat creation left database rows",
)
status, _, _ = self.request(
"POST",
"/api/v1/chats",
{
"title": "Создание после rollback",
"member_ids": [user["id"]],
},
token=token,
)
self.assertEqual(status, 201)
if __name__ == "__main__":
unittest.main(verbosity=2)
+325
View File
@@ -0,0 +1,325 @@
from __future__ import annotations
import os
import subprocess
import time
import lab2_checks as checks
PROJECT_DIR = checks.PROJECT_DIR
client = checks.Lab2Checks()
COMPOSE = [
"docker",
"compose",
"--env-file",
".env",
]
def compose(*args, ttl=None):
env = os.environ.copy()
if ttl is not None:
env["SESSION_TTL_SECONDS"] = str(ttl)
result = subprocess.run(
COMPOSE + list(args),
cwd=PROJECT_DIR,
env=env,
capture_output=True,
text=True,
timeout=90,
)
if result.returncode != 0:
raise RuntimeError(
"Compose command failed: "
+ " ".join(args)
+ ". Check docker compose ps -a and service logs."
)
return result.stdout.strip()
def start_storage(service):
compose(
"up",
"-d",
"--no-deps",
"--wait",
"--wait-timeout",
"45",
service,
)
def recreate_api(ttl):
compose(
"up",
"-d",
"--no-deps",
"--force-recreate",
"--wait",
"--wait-timeout",
"45",
"api",
ttl=ttl,
)
def expect_status(
method,
path,
expected,
token=None,
headers=None,
):
started = time.monotonic()
status, body, response_headers = client.request(
method,
path,
token=token,
headers=headers,
)
elapsed = time.monotonic() - started
client.assertEqual(
status,
expected,
f"Unexpected status for {method} {path}",
)
client.assertLess(
elapsed,
10,
f"Request exceeded local test budget: {path}",
)
return body, response_headers, elapsed
def wait_for_working_token(token, timeout=20):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
status, _, _ = client.request(
"GET",
"/api/v1/users/me",
token=token,
)
except OSError:
time.sleep(0.5)
continue
if status == 200:
return
time.sleep(0.5)
raise AssertionError(
"Existing session did not recover after database restart"
)
def main():
original_ttl = int(
compose(
"exec",
"-T",
"api",
"python",
"-c",
(
"import os; "
"print(os.getenv('SESSION_TTL_SECONDS', '3600'))"
),
)
)
client.assertGreaterEqual(
original_ttl,
300,
"Start this scenario with normal SESSION_TTL_SECONDS >= 300",
)
user, token = client.create_logged_in_user()
try:
# Warm the user cache before dependency failures.
expect_status(
"GET",
"/api/v1/users/me",
200,
token=token,
)
expect_status(
"GET",
"/api/v1/users/me",
200,
token=token,
)
compose("stop", "--timeout", "10", "redis")
_, _, elapsed = expect_status(
"GET",
"/api/v1/users/me",
200,
token=token,
)
expect_status(
"GET",
"/api/v1/users/me",
401,
headers={"X-User-Id": str(user["id"])},
)
expect_status("GET", "/health/live", 200)
expect_status("GET", "/health/ready", 200)
print(
f"PASS: Redis outage fallback; "
f"authenticated request took {elapsed:.3f}s",
flush=True,
)
start_storage("redis")
# Refill the cache, then prove it cannot replace session checks.
expect_status(
"GET",
"/api/v1/users/me",
200,
token=token,
)
compose("stop", "--timeout", "10", "postgres")
body, _, elapsed = expect_status(
"GET",
"/api/v1/users/me",
503,
token=token,
)
client.assertEqual(
body["error"]["code"],
"unavailable",
)
expect_status("GET", "/health/live", 200)
expect_status("GET", "/health/ready", 503)
expect_status(
"GET",
"/api/v1/users/me",
401,
headers={"X-User-Id": str(user["id"])},
)
print(
f"PASS: PostgreSQL outage fails closed; "
f"authenticated request took {elapsed:.3f}s",
flush=True,
)
start_storage("postgres")
wait_for_working_token(token)
print(
"PASS: existing session recovered after PostgreSQL restart",
flush=True,
)
recreate_api(ttl=2)
_, short_token = client.create_logged_in_user()
expect_status(
"GET",
"/api/v1/users/me",
200,
token=short_token,
)
started = time.monotonic()
deadline = started + 10
while True:
status, body, headers = client.request(
"GET",
"/api/v1/users/me",
token=short_token,
)
if status == 401:
client.assertEqual(
body["error"]["code"],
"unauthorized",
)
client.assertEqual(
headers.get("WWW-Authenticate"),
'Bearer realm="messenger"',
)
break
client.assertEqual(status, 200)
if time.monotonic() >= deadline:
raise AssertionError(
"Session did not expire with TTL=2"
)
time.sleep(0.25)
print(
f"PASS: short session expired; "
f"observed after {time.monotonic() - started:.3f}s",
flush=True,
)
finally:
restoration_errors = []
for service in ("postgres", "redis"):
try:
start_storage(service)
except Exception as exc:
restoration_errors.append(
f"{service}: {type(exc).__name__}"
)
try:
recreate_api(ttl=original_ttl)
except Exception as exc:
restoration_errors.append(
f"api: {type(exc).__name__}"
)
if restoration_errors:
raise RuntimeError(
"Automatic restoration failed: "
+ ", ".join(restoration_errors)
)
print(
f"RESTORED: services running; "
f"SESSION_TTL_SECONDS={original_ttl}",
flush=True,
)
expect_status("GET", "/health/ready", 200)
print(
"PASS: dependency outages and short session expiry",
flush=True,
)
if __name__ == "__main__":
main()