Реализация лабораторной 3: балансировка, отказ API-реплики, idempotency
- 2 API-реплики (api-1, api-2) с уникальным INSTANCE_ID - Nginx load balancer с health-check и failover - PostgreSQL источник истины, Valkey кэш сессий - Idempotency-Key в заголовке, replay возвращает исходное сообщение - X-Instance-Id в каждом ответе для идентификации реплики - /version и /info эндпоинты - Housekeeping-loop для очистки истёкших сессий и ключей - stop-one.sh/cmd для failover-теста, restart.sh/cmd для persistence - Исправлены импорты config/models/api/store/sessions - Добавлены миграции 004 (idempotency), 005 (indexes), 006 (message_id) - Отчёт с доказательствами критериев уровня 3 и 4 - Все тесты проходят: smoke, 26 student tests, failover, persistence, degradation
This commit is contained in:
@@ -0,0 +1,99 @@
|
||||
"""Session expiry with SESSION_TTL_SECONDS=2, plus logout and bad credentials.
|
||||
|
||||
Run against the dedicated short-TTL stand:
|
||||
|
||||
scripts/ttl-stack.sh start
|
||||
BASE_URL=http://localhost:8081 python -m unittest -v test_expiry
|
||||
scripts/ttl-stack.sh stop
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import statistics
|
||||
import time
|
||||
import unittest
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import common
|
||||
|
||||
|
||||
def expires_at(session: dict) -> datetime:
|
||||
return datetime.fromisoformat(session["expires_at"][:-1] + "+00:00")
|
||||
|
||||
|
||||
class ShortTtlSessions(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls) -> None:
|
||||
ready = common.request("GET", "/health/ready")
|
||||
if ready.status != 200:
|
||||
raise AssertionError("stand is not ready: %r" % (ready.json,))
|
||||
|
||||
def test_expiry_is_enforced_and_cache_does_not_extend_it(self) -> None:
|
||||
user = common.actor("ttl")
|
||||
started = datetime.now(timezone.utc)
|
||||
session = common.login(user.username, user.password)
|
||||
self.assertEqual(session.status, 201)
|
||||
lifetime = (expires_at(session.json) - started).total_seconds()
|
||||
self.assertLessEqual(lifetime, 5.0, "stand does not use a short TTL")
|
||||
|
||||
# Two reads: the second one is served from the Valkey cache, so the
|
||||
# expiry check below covers the cached path as well.
|
||||
for _ in range(2):
|
||||
self.assertEqual(
|
||||
common.request("GET", "/api/v1/users/me", token=session.json["token"]).status,
|
||||
200,
|
||||
)
|
||||
|
||||
time.sleep(3.2)
|
||||
expired = common.request("GET", "/api/v1/users/me", token=session.json["token"])
|
||||
common.expect_error(self, expired, 401, "unauthorized")
|
||||
self.assertTrue(expired.header("WWW-Authenticate").lower().startswith("bearer"))
|
||||
revoked = common.request(
|
||||
"DELETE", "/api/v1/auth/sessions/current", token=session.json["token"]
|
||||
)
|
||||
common.expect_error(self, revoked, 401, "unauthorized")
|
||||
|
||||
# A fresh login still works, so expiry removed only the old session.
|
||||
again = common.login(user.username, user.password)
|
||||
self.assertEqual(again.status, 201)
|
||||
self.assertEqual(
|
||||
common.request("GET", "/api/v1/users/me", token=again.json["token"]).status,
|
||||
200,
|
||||
)
|
||||
|
||||
def test_logout_is_immediate_even_when_the_session_is_cached(self) -> None:
|
||||
user = common.actor("ttllogout")
|
||||
token = user.token
|
||||
self.assertEqual(common.request("GET", "/api/v1/users/me", token=token).status, 200)
|
||||
self.assertEqual(
|
||||
common.request("DELETE", "/api/v1/auth/sessions/current", token=token).status,
|
||||
204,
|
||||
)
|
||||
outcome = common.request("GET", "/api/v1/users/me", token=token)
|
||||
common.expect_error(self, outcome, 401, "unauthorized")
|
||||
|
||||
def test_wrong_password_issues_no_session(self) -> None:
|
||||
user = common.actor("ttlwrong")
|
||||
denied = common.login(user.username, "not-the-password")
|
||||
common.expect_error(self, denied, 401, "unauthorized")
|
||||
self.assertTrue(denied.header("WWW-Authenticate").lower().startswith("basic"))
|
||||
|
||||
def test_session_lookup_latency_is_bounded(self) -> None:
|
||||
user = common.actor("ttllatency")
|
||||
samples = []
|
||||
for _ in range(30):
|
||||
started = time.monotonic()
|
||||
response = common.request("GET", "/api/v1/users/me", token=user.token, timeout=5)
|
||||
samples.append(time.monotonic() - started)
|
||||
self.assertEqual(response.status, 200)
|
||||
print(
|
||||
"\n /users/me warm cache p50=%.1fms p95=%.1fms"
|
||||
% (
|
||||
statistics.median(samples) * 1000,
|
||||
sorted(samples)[int(len(samples) * 0.95) - 1] * 1000,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user