[+] add project

This commit is contained in:
2026-11-13 21:16:52 +03:00
parent 982fe0e6d2
commit 802f1a4321
11 changed files with 453 additions and 88 deletions
+98 -40
View File
@@ -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
@@ -34,6 +35,9 @@ CURSOR_VERSION = 1
MAX_POOL_SIZE = int(os.environ.get("DB_POOL_MAX_SIZE", "10"))
if MAX_POOL_SIZE < 1 or MAX_POOL_SIZE > 50:
raise RuntimeError("DB_POOL_MAX_SIZE must be between 1 and 50")
SESSION_CACHE_SINGLEFLIGHT = os.environ.get("SESSION_CACHE_SINGLEFLIGHT", "1")
if SESSION_CACHE_SINGLEFLIGHT not in {"0", "1"}:
raise RuntimeError("SESSION_CACHE_SINGLEFLIGHT must be 0 or 1")
class APIError(Exception):
@@ -295,17 +299,25 @@ def authenticated_user(
now = datetime.now(timezone.utc)
cache = request.app.state.redis
cache_key = "session:" + token_hash.hex()
cached: Optional[Dict[str, Any]] = None
try:
raw = cache.get(cache_key)
if raw:
cached_value = json.loads(raw)
if isinstance(cached_value, dict):
cached = cached_value
else:
logger.warning("session cache entry has an invalid shape")
except (redis.RedisError, json.JSONDecodeError):
logger.warning("session cache read failed; using PostgreSQL")
def cached_profile() -> Optional[Dict[str, Any]]:
try:
raw = cache.get(cache_key)
value = json.loads(raw) if raw else None
except (redis.RedisError, json.JSONDecodeError):
logger.warning("session cache read failed; using PostgreSQL")
return None
if (
isinstance(value, dict)
and value.get("user_id") == str(session["user_id"])
and isinstance(value.get("user"), dict)
and value["user"].get("id") == str(session["user_id"])
):
return value["user"]
if value is not None:
logger.warning("session cache entry has an invalid shape")
return None
try:
session = connection.execute(
"""
@@ -324,36 +336,82 @@ def authenticated_user(
except redis.RedisError:
logger.warning("expired session cache invalidation failed")
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"]):
profile = cached.get("user")
if isinstance(profile, dict) and profile.get("id") == str(session["user_id"]):
user = profile
else:
cached = None
else:
cached = None
if not cached:
profile_row = connection.execute(
"""
SELECT id, username, display_name, created_at
FROM users WHERE id = %s
""",
(session["user_id"],),
).fetchone()
if not profile_row:
raise auth_error()
user = user_json(profile_row)
remaining = max(1, int((session["expires_at"] - now).total_seconds()))
# PostgreSQL remains authoritative for expiry/revocation. A Redis lock
# collapses concurrent profile cache misses into one profile query.
user = cached_profile()
if user is None:
lock_key = cache_key + ":fill"
lock_token = secrets.token_hex(16)
lock_acquired = False
cache_available = True
if SESSION_CACHE_SINGLEFLIGHT == "1":
try:
lock_acquired = bool(cache.set(lock_key, lock_token, nx=True, px=10000))
except redis.RedisError:
logger.warning("session cache fill lock failed; using PostgreSQL")
cache_available = False
if lock_acquired:
user = cached_profile()
if not lock_acquired and cache_available:
deadline = time.monotonic() + 2
while time.monotonic() < deadline:
time.sleep(0.025)
user = cached_profile()
if user is not None:
break
try:
lock_acquired = bool(
cache.set(lock_key, lock_token, nx=True, px=10000)
)
except redis.RedisError:
logger.warning("session cache fill lock failed; using PostgreSQL")
break
if lock_acquired:
user = cached_profile()
break
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 user is None:
logger.info(
"event=session_profile_db_load request_id=%s",
request.state.request_id,
)
try:
profile_row = connection.execute(
"""
SELECT id, username, display_name, created_at
FROM users WHERE id = %s
""",
(session["user_id"],),
).fetchone()
except psycopg.Error as exc:
logger.warning("session profile lookup failed: %s", type(exc).__name__)
raise db_unavailable() from None
if not profile_row:
raise auth_error()
user = user_json(profile_row)
remaining = max(1, int((session["expires_at"] - now).total_seconds()))
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")
finally:
if lock_acquired:
try:
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 fill lock release failed")
request.state.token_hash = token_hash
return user