perf(runtime): 修复 WebSocket 中间件与慢查询
This commit is contained in:
+34
-16
@@ -14,7 +14,6 @@ import os
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from fastapi import Request, Response
|
||||
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
|
||||
|
||||
from .security import AccessToken, renew_access_token
|
||||
|
||||
@@ -67,21 +66,40 @@ def _should_renew(request: Request, status_code: int) -> bool:
|
||||
return getattr(request.state, "current_user", None) is not None
|
||||
|
||||
|
||||
class SessionRenewalMiddleware(BaseHTTPMiddleware):
|
||||
class SessionRenewalMiddleware:
|
||||
"""滑动续期:活跃请求自动延长 24h,但永不突破 7 天绝对上限。"""
|
||||
|
||||
async def dispatch(
|
||||
self, request: Request, call_next: RequestResponseEndpoint
|
||||
) -> Response:
|
||||
response = await call_next(request)
|
||||
if not _should_renew(request, response.status_code):
|
||||
return response
|
||||
def __init__(self, app):
|
||||
self.app = app
|
||||
|
||||
token = getattr(request.state, "auth_cookie_token", None)
|
||||
if not token:
|
||||
return response
|
||||
renewed: AccessToken | None = renew_access_token(token)
|
||||
if renewed is None:
|
||||
return response
|
||||
set_session_cookie(response, renewed.token, renewed.expires_at)
|
||||
return response
|
||||
async def __call__(self, scope, receive, send):
|
||||
if scope["type"] != "http":
|
||||
await self.app(scope, receive, send)
|
||||
return
|
||||
request = Request(scope)
|
||||
|
||||
async def send_wrapper(message):
|
||||
if message["type"] == "http.response.start" and _should_renew(
|
||||
request,
|
||||
int(message["status"]),
|
||||
):
|
||||
token = getattr(request.state, "auth_cookie_token", None)
|
||||
renewed: AccessToken | None = (
|
||||
renew_access_token(token) if token else None
|
||||
)
|
||||
if renewed is not None:
|
||||
response = Response()
|
||||
set_session_cookie(
|
||||
response,
|
||||
renewed.token,
|
||||
renewed.expires_at,
|
||||
)
|
||||
cookie = response.headers.get("set-cookie")
|
||||
if cookie:
|
||||
message["headers"] = [
|
||||
*message.get("headers", []),
|
||||
(b"set-cookie", cookie.encode("latin-1")),
|
||||
]
|
||||
await send(message)
|
||||
|
||||
await self.app(scope, receive, send_wrapper)
|
||||
|
||||
Reference in New Issue
Block a user