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
+46 -12
View File
@@ -3,6 +3,7 @@
import os
from contextlib import asynccontextmanager
from pathlib import Path
from typing import Any, cast
import uvicorn
from fastapi import FastAPI, Request
@@ -10,7 +11,6 @@ from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
from starlette.middleware.base import BaseHTTPMiddleware
from utils import setup_logger
@@ -83,7 +83,7 @@ app = FastAPI(
)
# 业务异常统一带 errorCode,前端据此区分手机号未绑定 / 设备不一致等场景。
app.add_exception_handler(ApiError, api_error_handler)
app.add_exception_handler(ApiError, cast(Any, api_error_handler))
# CORS(支持通过环境变量配置,逗号分隔;默认开发环境)
_cors_env = os.getenv("CORS_ORIGINS", "")
@@ -109,16 +109,50 @@ app.add_middleware(GZipMiddleware, minimum_size=1024)
# 安全响应头中间件
class SecurityHeadersMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
response = await call_next(request)
response.headers["X-Content-Type-Options"] = "nosniff"
response.headers["X-Frame-Options"] = "DENY"
response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
if request.url.path.startswith("/assets/"):
# Vite 产物文件名带 hash,可以长期缓存。
response.headers["Cache-Control"] = "public, max-age=31536000, immutable"
return response
class SecurityHeadersMiddleware:
def __init__(self, app: Any):
self.app = app
async def __call__(self, scope: Any, receive: Any, send: Any):
if scope["type"] != "http":
await self.app(scope, receive, send)
return
path = str(scope.get("path") or "")
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)