forked from mtusi2026/mtusi2026lab2
Исправить logout при сбое записи в кэш сессий
This commit is contained in:
+40
-5
@@ -1,9 +1,10 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
from typing import Optional, Union
|
||||
from typing import Dict, Optional, Set, Union
|
||||
|
||||
import redis.asyncio as redis
|
||||
from redis.exceptions import RedisError
|
||||
@@ -19,6 +20,8 @@ class SessionCache:
|
||||
def __init__(self, url: Optional[str]):
|
||||
self._client: Optional[redis.Redis] = None
|
||||
self._down_until = 0.0
|
||||
self._pending_revokes: Dict[bytes, float] = {}
|
||||
self._retry_tasks: Set[asyncio.Task] = set()
|
||||
if url:
|
||||
pool = redis.BlockingConnectionPool.from_url(
|
||||
url,
|
||||
@@ -45,8 +48,17 @@ class SessionCache:
|
||||
def _key(token_hash: bytes) -> str:
|
||||
return "session:" + token_hash.hex()
|
||||
|
||||
def _revoke_pending(self, token_hash: bytes) -> bool:
|
||||
deadline = self._pending_revokes.get(token_hash)
|
||||
if deadline is None:
|
||||
return False
|
||||
if time.monotonic() >= deadline:
|
||||
self._pending_revokes.pop(token_hash, None)
|
||||
return False
|
||||
return True
|
||||
|
||||
async def get(self, token_hash: bytes) -> Union[dict, str, None]:
|
||||
if not self._usable():
|
||||
if not self._usable() or self._revoke_pending(token_hash):
|
||||
return None
|
||||
try:
|
||||
raw = await self._client.get(self._key(token_hash))
|
||||
@@ -69,13 +81,34 @@ class SessionCache:
|
||||
except (RedisError, OSError) as exc:
|
||||
self._failed("set", exc)
|
||||
|
||||
async def revoke(self, token_hash: bytes, ttl_seconds: int) -> None:
|
||||
if self._client is None:
|
||||
return
|
||||
async def _write_tombstone(self, token_hash: bytes, ttl_seconds: int) -> bool:
|
||||
try:
|
||||
await self._client.set(self._key(token_hash), REVOKED, ex=max(1, min(ttl_seconds, config.SESSION_CACHE_MAX_SECONDS)))
|
||||
return True
|
||||
except (RedisError, OSError) as exc:
|
||||
self._failed("revoke", exc)
|
||||
return False
|
||||
|
||||
async def revoke(self, token_hash: bytes, ttl_seconds: int) -> bool:
|
||||
if self._client is None:
|
||||
return True
|
||||
if await self._write_tombstone(token_hash, ttl_seconds):
|
||||
return True
|
||||
deadline = time.monotonic() + config.SESSION_CACHE_MAX_SECONDS + 1
|
||||
self._pending_revokes[token_hash] = deadline
|
||||
task = asyncio.create_task(self._retry_revoke(token_hash, ttl_seconds, deadline))
|
||||
self._retry_tasks.add(task)
|
||||
task.add_done_callback(self._retry_tasks.discard)
|
||||
return False
|
||||
|
||||
async def _retry_revoke(self, token_hash: bytes, ttl_seconds: int, deadline: float) -> None:
|
||||
while time.monotonic() < deadline:
|
||||
await asyncio.sleep(1)
|
||||
remaining = int(deadline - time.monotonic())
|
||||
if remaining > 0 and await self._write_tombstone(token_hash, min(ttl_seconds, remaining)):
|
||||
logger.info("revocation tombstone written after cache recovery")
|
||||
break
|
||||
self._pending_revokes.pop(token_hash, None)
|
||||
|
||||
async def ping(self) -> bool:
|
||||
if self._client is None:
|
||||
@@ -86,5 +119,7 @@ class SessionCache:
|
||||
return False
|
||||
|
||||
async def close(self) -> None:
|
||||
for task in list(self._retry_tasks):
|
||||
task.cancel()
|
||||
if self._client is not None:
|
||||
await self._client.aclose()
|
||||
|
||||
Reference in New Issue
Block a user