level 4: redis cache etc
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
"""Session lookup cache. PostgreSQL remains the source of truth."""
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
from redis.asyncio import Redis
|
||||
|
||||
logger = logging.getLogger('messenger')
|
||||
|
||||
_PREFIX = 'session:'
|
||||
|
||||
|
||||
def open_cache(url: str) -> Redis:
|
||||
return Redis.from_url(
|
||||
url,
|
||||
socket_connect_timeout=1,
|
||||
socket_timeout=1,
|
||||
max_connections=10,
|
||||
decode_responses=True,
|
||||
)
|
||||
|
||||
|
||||
def _stamp(moment: datetime) -> str:
|
||||
return moment.astimezone(timezone.utc).isoformat(timespec='microseconds').replace('+00:00', 'Z')
|
||||
|
||||
|
||||
class SessionCache:
|
||||
"""Stores sha256(token) -> expires_at. A read never refreshes the TTL."""
|
||||
|
||||
def __init__(self, client: Redis) -> None:
|
||||
self._client = client
|
||||
|
||||
async def get(self, token_hash: str) -> Optional[str]:
|
||||
"""Cached expiry, or None on a miss and when Redis cannot be reached."""
|
||||
try:
|
||||
return await self._client.get(_PREFIX + token_hash)
|
||||
except Exception as exc:
|
||||
logger.warning('session cache read skipped (%s)', type(exc).__name__)
|
||||
return None
|
||||
|
||||
async def remember(
|
||||
self,
|
||||
token_hash: str,
|
||||
expires_at: datetime,
|
||||
now: datetime,
|
||||
*,
|
||||
only_if_absent: bool,
|
||||
) -> None:
|
||||
remaining_ms = int((expires_at - now).total_seconds() * 1000)
|
||||
if remaining_ms <= 0:
|
||||
await self.drop(token_hash)
|
||||
return
|
||||
try:
|
||||
await self._client.set(
|
||||
_PREFIX + token_hash,
|
||||
_stamp(expires_at),
|
||||
px=remaining_ms,
|
||||
nx=only_if_absent,
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning('session cache write skipped (%s)', type(exc).__name__)
|
||||
|
||||
async def drop(self, token_hash: str) -> None:
|
||||
try:
|
||||
await self._client.delete(_PREFIX + token_hash)
|
||||
except Exception as exc:
|
||||
logger.warning('session cache delete skipped (%s)', type(exc).__name__)
|
||||
|
||||
async def close(self) -> None:
|
||||
await self._client.aclose()
|
||||
+10
-8
@@ -12,22 +12,23 @@ class Settings:
|
||||
shutdown_timeout: int
|
||||
session_ttl_seconds: int
|
||||
database_url: str
|
||||
redis_url: str
|
||||
|
||||
|
||||
def _database_url() -> str:
|
||||
"""DATABASE_URL_FILE wins. The value is not logged."""
|
||||
file_name = os.getenv('DATABASE_URL_FILE', '').strip()
|
||||
def _secret(file_var: str, value_var: str) -> str:
|
||||
"""A *_FILE variable wins. The secret value is not logged."""
|
||||
file_name = os.getenv(file_var, '').strip()
|
||||
if file_name:
|
||||
try:
|
||||
value = Path(file_name).read_text(encoding='utf-8').strip()
|
||||
except OSError:
|
||||
raise RuntimeError('DATABASE_URL_FILE could not be read') from None
|
||||
raise RuntimeError('%s could not be read' % file_var) from None
|
||||
if not value:
|
||||
raise RuntimeError('DATABASE_URL_FILE is empty')
|
||||
raise RuntimeError('%s is empty' % file_var)
|
||||
return value
|
||||
value = os.getenv('DATABASE_URL', '').strip()
|
||||
value = os.getenv(value_var, '').strip()
|
||||
if not value:
|
||||
raise RuntimeError('DATABASE_URL or DATABASE_URL_FILE is required')
|
||||
raise RuntimeError('%s or %s is required' % (value_var, file_var))
|
||||
return value
|
||||
|
||||
|
||||
@@ -39,5 +40,6 @@ def load_settings() -> Settings:
|
||||
log_level=os.getenv('LOG_LEVEL', 'info').lower(),
|
||||
shutdown_timeout=int(os.getenv('SHUTDOWN_TIMEOUT_SECONDS', '5')),
|
||||
session_ttl_seconds=int(os.getenv('SESSION_TTL_SECONDS', '3600')),
|
||||
database_url=_database_url(),
|
||||
database_url=_secret('DATABASE_URL_FILE', 'DATABASE_URL'),
|
||||
redis_url=_secret('CACHE_URL_FILE', 'REDIS_URL'),
|
||||
)
|
||||
|
||||
@@ -21,6 +21,7 @@ async def open_pool(database_url: str) -> asyncpg.Pool:
|
||||
max_size=10,
|
||||
timeout=5,
|
||||
command_timeout=5,
|
||||
server_settings={'statement_timeout': '5000'},
|
||||
)
|
||||
async with pool.acquire() as conn:
|
||||
await conn.execute('SELECT 1')
|
||||
|
||||
+7
-2
@@ -10,6 +10,7 @@ from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
from .cache import SessionCache, open_cache
|
||||
from .config import load_settings
|
||||
from .db import open_pool
|
||||
from .errors import ApiError
|
||||
@@ -58,12 +59,16 @@ _OPENAPI_PATH = Path(__file__).resolve().parents[1] / 'contracts' / 'openapi.jso
|
||||
async def lifespan(app: FastAPI):
|
||||
settings = load_settings()
|
||||
pool = await open_pool(settings.database_url)
|
||||
cache = SessionCache(open_cache(settings.redis_url))
|
||||
try:
|
||||
await apply_migrations(pool)
|
||||
app.state.store = Store(pool, settings.session_ttl_seconds)
|
||||
app.state.store = Store(pool, cache, settings.session_ttl_seconds)
|
||||
yield
|
||||
finally:
|
||||
await pool.close()
|
||||
try:
|
||||
await cache.close()
|
||||
finally:
|
||||
await pool.close()
|
||||
|
||||
|
||||
def create_app() -> FastAPI:
|
||||
|
||||
+87
-48
@@ -8,6 +8,7 @@ from typing import Dict, List, Optional, Sequence, Tuple
|
||||
|
||||
import asyncpg
|
||||
|
||||
from .cache import SessionCache
|
||||
from .errors import conflict, invalid_request, unavailable
|
||||
from .pagination import Key
|
||||
from .passwords import hash_password, password_matches
|
||||
@@ -88,11 +89,22 @@ def _as_uuid(value: str, message: str) -> uuid.UUID:
|
||||
raise invalid_request(message) from None
|
||||
|
||||
|
||||
class Store:
|
||||
"""PostgreSQL is the source of truth. One process clock keeps created_at ordered."""
|
||||
def _db_down(exc: BaseException) -> bool:
|
||||
return isinstance(exc, (
|
||||
asyncpg.PostgresConnectionError,
|
||||
asyncpg.InterfaceError,
|
||||
asyncpg.CannotConnectNowError,
|
||||
OSError,
|
||||
TimeoutError,
|
||||
))
|
||||
|
||||
def __init__(self, pool: asyncpg.Pool, session_ttl_seconds: int = 3600) -> None:
|
||||
|
||||
class Store:
|
||||
"""PostgreSQL is the source of truth. Redis only caches the session lookup."""
|
||||
|
||||
def __init__(self, pool: asyncpg.Pool, cache: SessionCache, session_ttl_seconds: int = 3600) -> None:
|
||||
self._pool = pool
|
||||
self._cache = cache
|
||||
self._session_ttl = timedelta(seconds=session_ttl_seconds)
|
||||
self._lock = threading.Lock()
|
||||
self._last_moment: Optional[datetime] = None
|
||||
@@ -135,15 +147,20 @@ class Store:
|
||||
return User(str(user_id), username, display_name, _stamp(created))
|
||||
|
||||
async def authenticate(self, username: str, password: str) -> Optional[User]:
|
||||
async with self._pool.acquire() as conn:
|
||||
row = await conn.fetchrow(
|
||||
'''
|
||||
SELECT id, username, display_name, created_at, password_hash
|
||||
FROM users
|
||||
WHERE username = $1
|
||||
''',
|
||||
username,
|
||||
)
|
||||
try:
|
||||
async with self._pool.acquire() as conn:
|
||||
row = await conn.fetchrow(
|
||||
'''
|
||||
SELECT id, username, display_name, created_at, password_hash
|
||||
FROM users
|
||||
WHERE username = $1
|
||||
''',
|
||||
username,
|
||||
)
|
||||
except Exception as exc:
|
||||
if _db_down(exc):
|
||||
raise unavailable('Хранилище недоступно') from None
|
||||
raise
|
||||
stored_hash = row['password_hash'] if row is not None else None
|
||||
if not password_matches(stored_hash, password) or row is None:
|
||||
return None
|
||||
@@ -152,50 +169,72 @@ class Store:
|
||||
async def create_session(self, user_id: str) -> Tuple[str, str]:
|
||||
token = secrets.token_urlsafe(32)
|
||||
expires = datetime.now(timezone.utc) + self._session_ttl
|
||||
async with self._pool.acquire() as conn:
|
||||
await conn.execute(
|
||||
'''
|
||||
INSERT INTO sessions (token_hash, user_id, expires_at)
|
||||
VALUES ($1, $2, $3)
|
||||
''',
|
||||
_token_key(token),
|
||||
_as_uuid(user_id, 'Некорректный user_id'),
|
||||
expires,
|
||||
)
|
||||
key = _token_key(token)
|
||||
try:
|
||||
async with self._pool.acquire() as conn:
|
||||
await conn.execute(
|
||||
'''
|
||||
INSERT INTO sessions (token_hash, user_id, expires_at)
|
||||
VALUES ($1, $2, $3)
|
||||
''',
|
||||
key,
|
||||
_as_uuid(user_id, 'Некорректный user_id'),
|
||||
expires,
|
||||
)
|
||||
except Exception as exc:
|
||||
if _db_down(exc):
|
||||
raise unavailable('Хранилище недоступно') from None
|
||||
raise
|
||||
await self._cache.remember(key, expires, datetime.now(timezone.utc), only_if_absent=False)
|
||||
return token, _stamp(expires)
|
||||
|
||||
async def user_for_token(self, token: str) -> Optional[User]:
|
||||
now = datetime.now(timezone.utc)
|
||||
key = _token_key(token)
|
||||
async with self._pool.acquire() as conn:
|
||||
row = await conn.fetchrow(
|
||||
'''
|
||||
SELECT u.id, u.username, u.display_name, u.created_at, s.expires_at
|
||||
FROM sessions s
|
||||
JOIN users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = $1
|
||||
''',
|
||||
key,
|
||||
)
|
||||
if row is None:
|
||||
return None
|
||||
if row['expires_at'] <= now:
|
||||
await conn.execute('DELETE FROM sessions WHERE token_hash = $1', key)
|
||||
return None
|
||||
return _user(row)
|
||||
cached = await self._cache.get(key)
|
||||
try:
|
||||
async with self._pool.acquire() as conn:
|
||||
row = await conn.fetchrow(
|
||||
'''
|
||||
SELECT u.id, u.username, u.display_name, u.created_at, s.expires_at
|
||||
FROM sessions s
|
||||
JOIN users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = $1
|
||||
''',
|
||||
key,
|
||||
)
|
||||
if row is None or row['expires_at'] <= now:
|
||||
if row is not None:
|
||||
await conn.execute('DELETE FROM sessions WHERE token_hash = $1', key)
|
||||
await self._cache.drop(key)
|
||||
return None
|
||||
if cached is None:
|
||||
await self._cache.remember(key, row['expires_at'], now, only_if_absent=True)
|
||||
return _user(row)
|
||||
except Exception as exc:
|
||||
if _db_down(exc):
|
||||
raise unavailable('Хранилище недоступно') from None
|
||||
raise
|
||||
|
||||
async def revoke_session(self, token: str) -> bool:
|
||||
now = datetime.now(timezone.utc)
|
||||
async with self._pool.acquire() as conn:
|
||||
row = await conn.fetchrow(
|
||||
'''
|
||||
DELETE FROM sessions
|
||||
WHERE token_hash = $1 AND expires_at > $2
|
||||
RETURNING token_hash
|
||||
''',
|
||||
_token_key(token),
|
||||
now,
|
||||
)
|
||||
key = _token_key(token)
|
||||
try:
|
||||
async with self._pool.acquire() as conn:
|
||||
row = await conn.fetchrow(
|
||||
'''
|
||||
DELETE FROM sessions
|
||||
WHERE token_hash = $1 AND expires_at > $2
|
||||
RETURNING token_hash
|
||||
''',
|
||||
key,
|
||||
now,
|
||||
)
|
||||
except Exception as exc:
|
||||
if _db_down(exc):
|
||||
raise unavailable('Хранилище недоступно') from None
|
||||
raise
|
||||
await self._cache.drop(key)
|
||||
return row is not None
|
||||
|
||||
async def create_chat(self, title: str, member_ids: Sequence[str]) -> Chat:
|
||||
|
||||
Reference in New Issue
Block a user