level 4: redis cache etc
This commit is contained in:
+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