perf(runtime): 修复 WebSocket 中间件与慢查询

This commit is contained in:
yml
2026-11-23 16:55:00 +08:00
parent 38ae5c867c
commit b30b16294f
6 changed files with 145 additions and 36 deletions
+6
View File
@@ -181,6 +181,12 @@ class TestRetention(_Base):
statuses = {t.status for t in self.session.query(DouyuTask).all()} statuses = {t.status for t in self.session.query(DouyuTask).all()}
assert statuses == {"planned", "pending", "running"} assert statuses == {"planned", "pending", "running"}
def test_unknown_statuses_are_kept(self):
self.make_task("query_limited_goods", age_days=999, status="new_future_state")
out = self.run(noise_days=7, business_days=90)
assert out["deleted"] == 0
assert self.count() == 1
def test_config_windows_are_honoured(self): def test_config_windows_are_honoured(self):
self.make_task("query_limited_goods", age_days=2) self.make_task("query_limited_goods", age_days=2)
out = self.run(noise_days=1, business_days=90) out = self.run(noise_days=1, business_days=90)
+37
View File
@@ -0,0 +1,37 @@
"""纯 ASGI 中间件不能吞掉 WebSocket 生命周期。"""
from __future__ import annotations
import asyncio
from web.backend.main import SecurityHeadersMiddleware
from web.backend.session import SessionRenewalMiddleware
async def _websocket_app(scope, receive, send):
assert scope["type"] == "websocket"
await send({"type": "websocket.accept"})
await send({"type": "websocket.close", "code": 1000})
def test_websocket_bypasses_http_middleware():
messages: list[dict] = []
async def send(message):
messages.append(message)
async def receive():
return {"type": "websocket.connect"}
scope = {
"type": "websocket",
"path": "/api/douyu/ws/test",
"headers": [],
}
wrapped = SessionRenewalMiddleware(SecurityHeadersMiddleware(_websocket_app))
asyncio.run(wrapped(scope, receive, send))
assert messages == [
{"type": "websocket.accept"},
{"type": "websocket.close", "code": 1000},
]
+46 -12
View File
@@ -3,6 +3,7 @@
import os import os
from contextlib import asynccontextmanager from contextlib import asynccontextmanager
from pathlib import Path from pathlib import Path
from typing import Any, cast
import uvicorn import uvicorn
from fastapi import FastAPI, Request from fastapi import FastAPI, Request
@@ -10,7 +11,6 @@ from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware from fastapi.middleware.gzip import GZipMiddleware
from fastapi.responses import FileResponse from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles from fastapi.staticfiles import StaticFiles
from starlette.middleware.base import BaseHTTPMiddleware
from utils import setup_logger from utils import setup_logger
@@ -83,7 +83,7 @@ app = FastAPI(
) )
# 业务异常统一带 errorCode,前端据此区分手机号未绑定 / 设备不一致等场景。 # 业务异常统一带 errorCode,前端据此区分手机号未绑定 / 设备不一致等场景。
app.add_exception_handler(ApiError, api_error_handler) app.add_exception_handler(ApiError, cast(Any, api_error_handler))
# CORS(支持通过环境变量配置,逗号分隔;默认开发环境) # CORS(支持通过环境变量配置,逗号分隔;默认开发环境)
_cors_env = os.getenv("CORS_ORIGINS", "") _cors_env = os.getenv("CORS_ORIGINS", "")
@@ -109,16 +109,50 @@ app.add_middleware(GZipMiddleware, minimum_size=1024)
# 安全响应头中间件 # 安全响应头中间件
class SecurityHeadersMiddleware(BaseHTTPMiddleware): class SecurityHeadersMiddleware:
async def dispatch(self, request: Request, call_next): def __init__(self, app: Any):
response = await call_next(request) self.app = app
response.headers["X-Content-Type-Options"] = "nosniff"
response.headers["X-Frame-Options"] = "DENY" async def __call__(self, scope: Any, receive: Any, send: Any):
response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin" if scope["type"] != "http":
if request.url.path.startswith("/assets/"): await self.app(scope, receive, send)
# Vite 产物文件名带 hash,可以长期缓存。 return
response.headers["Cache-Control"] = "public, max-age=31536000, immutable" path = str(scope.get("path") or "")
return response
async def send_wrapper(message: Any):
if message["type"] == "http.response.start":
headers = [
(key, value)
for key, value in message.get("headers", [])
if key
not in {
b"x-content-type-options",
b"x-frame-options",
b"referrer-policy",
b"cache-control",
}
]
headers.extend(
[
(b"x-content-type-options", b"nosniff"),
(b"x-frame-options", b"DENY"),
(
b"referrer-policy",
b"strict-origin-when-cross-origin",
),
]
)
if path.startswith("/assets/"):
headers.append(
(
b"cache-control",
b"public, max-age=31536000, immutable",
)
)
message["headers"] = headers
await send(message)
await self.app(scope, receive, send_wrapper)
app.add_middleware(SecurityHeadersMiddleware) app.add_middleware(SecurityHeadersMiddleware)
+11 -7
View File
@@ -651,11 +651,11 @@ def _sync_candidate_query(
~state_exists, ~state_exists,
~active_account_work_exists(work_type=WORK_STOREHOME_SYNC), ~active_account_work_exists(work_type=WORK_STOREHOME_SYNC),
assigned_to_pool_filter(), assigned_to_pool_filter(),
~active_lease_exists(),
~active_collab_order_exists(),
role_change_ready_filter(now),
) )
.order_by( .order_by(
case((active_lease_exists(), 1), else_=0),
case((active_collab_order_exists(), 1), else_=0),
case((role_change_ready_filter(now), 0), else_=1),
case((Account.role_bind_status == "unbound", 0), else_=1), case((Account.role_bind_status == "unbound", 0), else_=1),
Account.overview_queried_at.is_(None).desc(), Account.overview_queried_at.is_(None).desc(),
Account.overview_queried_at.asc(), Account.overview_queried_at.asc(),
@@ -711,19 +711,23 @@ def enqueue_supply_replenishment(
inventory.allocatable_shortage, inventory.allocatable_shortage,
) )
limit = max(1, min(int(max_per_target), missing, headroom)) limit = max(1, min(int(max_per_target), missing, headroom))
accounts = ( account_ids = [
int(account_id)
for (account_id,) in (
_sync_candidate_query( _sync_candidate_query(
db, db,
target=target, target=target,
now=moment, now=moment,
) )
.with_entities(Account.id)
.limit(limit) .limit(limit)
.all() .all()
) )
for account in accounts: ]
for account_id in account_ids:
enqueue_account_work( enqueue_account_work(
db, db,
account_id=int(account.id), account_id=account_id,
work_type=WORK_STOREHOME_SYNC, work_type=WORK_STOREHOME_SYNC,
priority=35, priority=35,
due_at=moment, due_at=moment,
@@ -80,6 +80,16 @@ DEFAULT_MAX_BATCHES = 50
#: 在途任务绝不可删:批次线程正拿着这些行。 #: 在途任务绝不可删:批次线程正拿着这些行。
IN_FLIGHT_STATUSES = ("planned", "pending", "running") IN_FLIGHT_STATUSES = ("planned", "pending", "running")
#: 只清理明确结束的状态。未知/新增状态默认保留,避免未来状态机扩展后被误删。
TERMINAL_STATUSES = (
"success",
"failed",
"error",
"stopped",
"timeout",
"cancelled",
)
def _load_config(job: AutomationJob) -> dict[str, Any]: def _load_config(job: AutomationJob) -> dict[str, Any]:
config = job.config config = job.config
@@ -127,7 +137,7 @@ def _delete_batch(
) )
query = db.query(DouyuTask.id, DouyuTask.created_at).filter( query = db.query(DouyuTask.id, DouyuTask.created_at).filter(
type_filter, type_filter,
~DouyuTask.status.in_(IN_FLIGHT_STATUSES), DouyuTask.status.in_(TERMINAL_STATUSES),
DouyuTask.created_at < cutoff, DouyuTask.created_at < cutoff,
) )
if cursor_created_at is not None: if cursor_created_at is not None:
+34 -16
View File
@@ -14,7 +14,6 @@ import os
from datetime import UTC, datetime from datetime import UTC, datetime
from fastapi import Request, Response from fastapi import Request, Response
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
from .security import AccessToken, renew_access_token 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 return getattr(request.state, "current_user", None) is not None
class SessionRenewalMiddleware(BaseHTTPMiddleware): class SessionRenewalMiddleware:
"""滑动续期:活跃请求自动延长 24h,但永不突破 7 天绝对上限。""" """滑动续期:活跃请求自动延长 24h,但永不突破 7 天绝对上限。"""
async def dispatch( def __init__(self, app):
self, request: Request, call_next: RequestResponseEndpoint self.app = app
) -> Response:
response = await call_next(request)
if not _should_renew(request, response.status_code):
return response
token = getattr(request.state, "auth_cookie_token", None) async def __call__(self, scope, receive, send):
if not token: if scope["type"] != "http":
return response await self.app(scope, receive, send)
renewed: AccessToken | None = renew_access_token(token) return
if renewed is None: request = Request(scope)
return response
set_session_cookie(response, renewed.token, renewed.expires_at) async def send_wrapper(message):
return response 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)