From c715587f9528352efd0326584bb83f5af7eeca12 Mon Sep 17 00:00:00 2001 From: Kondrashov Nikita Date: Tue, 17 Nov 2026 17:14:28 +0300 Subject: [PATCH] [+] add project --- Makefile | 7 ++- README.md | 8 +++ app/main.py | 61 +++++++++++++++--- tests/README.md | 8 +++ tests/cache_singleflight.py | 119 ++++++++++++++++++++++++++++++++++++ 5 files changed, 192 insertions(+), 11 deletions(-) create mode 100644 tests/cache_singleflight.py diff --git a/Makefile b/Makefile index fe1752e..b3229d7 100644 --- a/Makefile +++ b/Makefile @@ -4,10 +4,10 @@ CA_FILE ?= ACTION_SCRIPT ?= TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) -.PHONY: help check validate test load test-persistence test-grade4 test-expiry test-rollback explain-history +.PHONY: help check validate test load test-persistence test-grade4 test-expiry test-rollback test-track5-cache explain-history help: - @echo "check: offline structure; validate: full OpenAPI; test: running API; test-grade4: concurrency and dependency outages" + @echo "check: offline structure; validate: full OpenAPI; test: running API; test-grade4: concurrency and dependency outages; test-track5-cache: Redis single-flight" @echo "test-expiry: run against SESSION_TTL_SECONDS=2; explain-history: EXPLAIN a rollback-only 10k-message fixture" check: @@ -35,5 +35,8 @@ test-expiry: test-rollback: $(PYTHON) tests/transaction_rollback.py --base-url "$(BASE_URL)" $(TLS_ARGS) +test-track5-cache: + $(PYTHON) tests/cache_singleflight.py --base-url "$(BASE_URL)" $(TLS_ARGS) + explain-history: docker compose exec -T postgres psql -U messenger -d messenger -v ON_ERROR_STOP=1 < scripts/benchmark_history.sql diff --git a/README.md b/README.md index 79102c8..8d986b6 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,14 @@ make check make test ``` +Для трека 1 после запуска Compose-стенда выполните проверку Redis single-flight: + +```sh +make test-track5-cache BASE_URL=http://localhost:8080 +``` + +Проверка создаёт пользователя/сессию, очищает профиль из Redis, отправляет 16 параллельных запросов и по событиям `profile_cache_fill` с уникальными request ID считает фактические SQL-запросы загрузки профиля. Затем сравнивает холодный и прогретый кэш по p95 latency, перезапускает Redis, удаляет только тестовый ключ и проверяет повторную загрузку профиля из PostgreSQL. Без single-flight конкурентный cache miss мог бы вызвать до 16 запросов профиля; проверка требует ровно одного. PostgreSQL всё равно проверяет expiry/revocation каждой сессии. Тест перезапускает Redis и требует Docker Compose CLI. + `.env.example`, `compose.example.yaml` и `contracts/infrastructure.json` описывают настройки и роли компонентов. **compose.example.yaml — список ролей с пустым services, не запускаемый стенд.** Реализуйте свой `compose.yaml`/`stack.yaml`, закрепите версии образов, заполните локальный `.env` и опишите bootstrap/миграции. Все зависимости поднимаются из этого репозитория; ссылка «у меня БД уже установлена» не заменяет воспроизводимость. ```sh diff --git a/app/main.py b/app/main.py index 891af09..7f6e447 100644 --- a/app/main.py +++ b/app/main.py @@ -6,6 +6,7 @@ import logging import os import re import secrets +import time import uuid from contextlib import asynccontextmanager from datetime import datetime, timedelta, timezone @@ -326,15 +327,45 @@ def authenticated_user( raise auth_error() # PostgreSQL remains authoritative for expiry and revocation. Redis avoids # a user-profile query on a cache hit. - if cached and cached.get("user_id") == str(session["user_id"]): + if cached: profile = cached.get("user") - if isinstance(profile, dict) and profile.get("id") == str(session["user_id"]): + if ( + cached.get("user_id") == str(session["user_id"]) + and isinstance(profile, dict) + and profile.get("id") == str(session["user_id"]) + ): user = profile else: cached = None - else: - cached = None + lock_key = cache_key + ":fill-lock" + lock_token = str(uuid.uuid4()) + lock_acquired = False if not cached: + for _ in range(20): + try: + lock_acquired = bool( + cache.set(lock_key, lock_token, nx=True, px=5000) + ) + if lock_acquired: + break + raw = cache.get(cache_key) + if raw: + cached_value = json.loads(raw) + if ( + isinstance(cached_value, dict) + and cached_value.get("user_id") == str(session["user_id"]) + and isinstance(cached_value.get("user"), dict) + and cached_value["user"].get("id") == str(session["user_id"]) + ): + user = cached_value["user"] + cached = cached_value + break + except (redis.RedisError, json.JSONDecodeError): + logger.warning("session cache single-flight failed; using PostgreSQL") + break + time.sleep(0.05) + if not cached: + logger.info("profile_cache_fill request_id=%s", request.state.request_id) profile_row = connection.execute( """ SELECT id, username, display_name, created_at @@ -346,14 +377,26 @@ def authenticated_user( raise auth_error() user = user_json(profile_row) remaining = max(1, int((session["expires_at"] - now).total_seconds())) + if lock_acquired: + try: + cache.set( + cache_key, + json.dumps({"user_id": str(session["user_id"]), "user": user}), + ex=remaining, + ) + except redis.RedisError: + logger.warning("session cache write failed; continuing with PostgreSQL") + if lock_acquired: try: - cache.set( - cache_key, - json.dumps({"user_id": str(session["user_id"]), "user": user}), - ex=remaining, + cache.eval( + "if redis.call('get', KEYS[1]) == ARGV[1] " + "then return redis.call('del', KEYS[1]) else return 0 end", + 1, + lock_key, + lock_token, ) except redis.RedisError: - logger.warning("session cache write failed; continuing with PostgreSQL") + logger.warning("session cache fill lock release failed") request.state.token_hash = token_hash return user diff --git a/tests/README.md b/tests/README.md index 0dfa3f8..72b52ec 100644 --- a/tests/README.md +++ b/tests/README.md @@ -55,3 +55,11 @@ make test-security BASE_URL=https://localhost:8443 CA_FILE=/absolute/path/to/ca. ## Что ещё остаётся доказать Smoke не доказывает persistence, число реальных контейнеров, durability брокера, outbox, отсутствие утечек/уязвимостей, полноту telemetry или выполнение уровня 4/5. Конкурентные/нагрузочные/негативные проверки своего решения добавляйте отдельно. Список защиты текущей лабы находится в README.md. Проверки рассчитаны на localhost-стенд, не на production. + +## Redis single-flight, track 5 + +```sh +make test-track5-cache BASE_URL=http://localhost:8080 +``` + +Тест требует работающий Compose-стенд, Docker Compose CLI и доступные логи сервиса `api`. Он сбрасывает только ключ профиля созданной им тестовой сессии, выполняет конкурентные холодные и прогретые чтения, считает события `profile_cache_fill` по уникальным request ID и выводит p95 latency. Ожидается один запрос профиля в PostgreSQL на холодную конкурентную группу и ноль на прогретую. Затем тест перезапускает Redis, удаляет только этот тестовый ключ и проверяет повторную загрузку из PostgreSQL. Идентификаторы событий не содержат токенов или персональных данных. diff --git a/tests/cache_singleflight.py b/tests/cache_singleflight.py new file mode 100644 index 0000000..0eafb7c --- /dev/null +++ b/tests/cache_singleflight.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +import hashlib +import math +import subprocess +import time +import uuid +from concurrent.futures import ThreadPoolExecutor + +from client import Client, Failure, arguments, check, run + + +def docker(*command): + return subprocess.run( + ["docker", "compose", *command], + check=True, + capture_output=True, + text=True, + timeout=15, + ) + + +def fill_events(request_ids): + logs = docker("logs", "--no-color", "--since", "5m", "api").stdout + return { + request_id + for request_id in request_ids + if "profile_cache_fill request_id=" + request_id in logs + } + + +def ready(client): + for _ in range(60): + try: + client.call("GET", "/health/ready", schema="Health") + return + except Failure: + time.sleep(1) + raise Failure("API did not become ready after Redis restart") + + +def p95_milliseconds(results): + elapsed = sorted(result["elapsed"] for result in results) + return elapsed[math.ceil(0.95 * len(elapsed)) - 1] * 1000 + + +def main(): + args = arguments("Redis profile-cache single-flight consistency check") + client = Client(args.base_url, args.ca_file, timeout=10) + client.call("GET", "/health/ready", schema="Health") + actor = client.user("cache") + cache_key = "session:" + hashlib.sha256(actor["token"].encode()).hexdigest() + docker("exec", "-T", "redis", "redis-cli", "DEL", cache_key) + + def get_profile(request_id): + return Client(args.base_url, args.ca_file, timeout=10).call( + "GET", + "/api/v1/users/me", + actor=actor, + schema="User", + headers={"X-Request-Id": request_id}, + ) + + cold_ids = ["cache-cold-" + uuid.uuid4().hex for _ in range(16)] + with ThreadPoolExecutor(max_workers=len(cold_ids)) as executor: + cold_results = list(executor.map(get_profile, cold_ids)) + check( + all(result["json"] == actor["user"] for result in cold_results), + "concurrent cold-cache requests returned inconsistent profiles", + ) + cold_fills = fill_events(cold_ids) + check( + len(cold_fills) == 1, + "cold-cache request burst filled the profile cache " + + str(len(cold_fills)) + + " times instead of once", + ) + + warm_ids = ["cache-warm-" + uuid.uuid4().hex for _ in range(16)] + with ThreadPoolExecutor(max_workers=len(warm_ids)) as executor: + warm_results = list(executor.map(get_profile, warm_ids)) + check( + all(result["json"] == actor["user"] for result in warm_results), + "concurrent warm-cache requests returned inconsistent profiles", + ) + check(not fill_events(warm_ids), "warm-cache requests unexpectedly queried profiles") + + docker("restart", "redis") + ready(client) + docker("exec", "-T", "redis", "redis-cli", "DEL", cache_key) + restart_id = "cache-restart-" + uuid.uuid4().hex + restarted_result = get_profile(restart_id) + check( + restarted_result["json"] == actor["user"], + "profile read-after-Redis-restart returned inconsistent data", + ) + check( + fill_events([restart_id]) == {restart_id}, + "profile was not reloaded from PostgreSQL after Redis restart", + ) + + print( + "PASS: Redis single-flight; " + + str(len(cold_ids)) + + " concurrent cold reads caused 1 profile SQL read " + + "(vs up to " + + str(len(cold_ids)) + + " without single-flight), " + + str(len(warm_ids)) + + " warm reads caused 0; " + + "cold p95=" + + format(p95_milliseconds(cold_results), ".1f") + + "ms, warm p95=" + + format(p95_milliseconds(warm_results), ".1f") + + "ms; cache restart recovered from PostgreSQL" + ) + + +if __name__ == "__main__": + run(main)