diff --git a/backend/.env.example b/backend/.env.example index fab3b832..07b2909d 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -17,6 +17,8 @@ SECRET_KEY= # 应用配置示例 # APP_NAME=陇耘鲜达 # DEBUG=true +# SQL 回显与 DEBUG 解耦;需要排查 SQL 时再打开 +# SQLALCHEMY_ECHO=false # 浏览器跨域:若设置 BACKEND_CORS_ORIGINS,须为 JSON 数组,会整体覆盖代码默认值,例如: # BACKEND_CORS_ORIGINS=["http://localhost:5173","http://localhost:3006","http://127.0.0.1:3006"] diff --git a/backend/app/core/api_request_log_middleware.py b/backend/app/core/api_request_log_middleware.py index f2fc1fe8..8d97482d 100644 --- a/backend/app/core/api_request_log_middleware.py +++ b/backend/app/core/api_request_log_middleware.py @@ -40,6 +40,25 @@ def _truncate(s: str, max_len: int) -> str: return s[:max_len] + f"\n... [truncated, total {len(s)} chars]" +def _truncate_utf8_bytes(s: Optional[str], max_bytes: int) -> Optional[str]: + """按 UTF-8 字节截断,适配 MySQL TEXT 字节上限。""" + if not s: + return s + raw = s.encode("utf-8") + if len(raw) <= max_bytes: + return s + cut = raw[:max_bytes] + while cut: + try: + text = cut.decode("utf-8") + break + except UnicodeDecodeError: + cut = cut[:-1] + else: + return None + return text + f"\n... [truncated, total {len(raw)} bytes]" + + def _redact_obj(obj: Any) -> Any: if isinstance(obj, dict): out = {} @@ -135,6 +154,10 @@ def _persist_log( from app.core.utils import generate_id from app.models.models import SysApiRequestLog + max_db = settings.API_REQUEST_LOG_DB_MAX_BYTES + req_body = _truncate_utf8_bytes(request_body, max_db) + resp_body = _truncate_utf8_bytes(response_body, max_db) + db = SessionLocal() try: row = SysApiRequestLog( @@ -142,8 +165,8 @@ def _persist_log( http_method=http_method, path=_truncate(path, 500), query_string=_truncate(query_string or "", 2000) or None, - request_body=request_body, - response_body=response_body, + request_body=req_body, + response_body=resp_body, status_code=status_code, duration_ms=duration_ms, user_id=user_id, @@ -161,6 +184,32 @@ def _persist_log( except Exception as e: logger.warning("api_request_log persist failed: %s", e) db.rollback() + # 字段过长/字符集异常时降级为空 body,保留审计元数据 + try: + row = SysApiRequestLog( + id=generate_id(), + http_method=http_method, + path=_truncate(path, 500), + query_string=_truncate(query_string or "", 2000) or None, + request_body=None, + response_body=None, + status_code=status_code, + duration_ms=duration_ms, + user_id=user_id, + username=_truncate(username or "", 100) if username else None, + role=role, + ip_address=ip_address, + user_agent=_truncate(user_agent or "", 500) if user_agent else None, + is_del=0, + create_at=datetime.now(), + create_by=None, + create_name=None, + ) + db.add(row) + db.commit() + except Exception as e2: + logger.warning("api_request_log persist fallback failed: %s", e2) + db.rollback() finally: db.close() @@ -180,6 +229,9 @@ def _schedule_persist_log(**kwargs) -> None: task = loop.create_task(asyncio.to_thread(_persist_log, **kwargs)) def _on_done(t: asyncio.Task) -> None: + if t.cancelled(): + # reload / shutdown 取消未完成写入任务,属预期 + return try: t.result() except Exception as e: diff --git a/backend/app/core/config.py b/backend/app/core/config.py index d3b64d00..f28d76f6 100644 --- a/backend/app/core/config.py +++ b/backend/app/core/config.py @@ -28,6 +28,8 @@ class Settings(BaseSettings): # 应用基础配置 APP_NAME: str = "zkxw 管理骨架" DEBUG: bool = True + # SQLAlchemy 引擎 SQL 回显;默认关闭,避免 DEBUG=true 时终端被 SQL 刷屏 + SQLALCHEMY_ECHO: bool = False API_V1_PREFIX: str = "/api" # 数据库配置 @@ -201,8 +203,11 @@ class Settings(BaseSettings): # 全量 API 请求日志(中间件写入 sys_api_request_log) API_REQUEST_LOG_ENABLED: bool = True - API_REQUEST_LOG_MAX_BODY: int = 65536 - API_REQUEST_LOG_MAX_BODY_BYTES: int = 131072 + # MySQL TEXT 上限约 65535 字节;按字符截断会因中文多字节溢出,默认按安全字符上限 + API_REQUEST_LOG_MAX_BODY: int = 16000 + API_REQUEST_LOG_MAX_BODY_BYTES: int = 48000 + # 写入库时再按 UTF-8 字节截断,避免 Data too long + API_REQUEST_LOG_DB_MAX_BYTES: int = 60000 # Web API 请求/响应加密配置 API_ENCRYPT_ENABLED: bool = False diff --git a/backend/app/core/database.py b/backend/app/core/database.py index 225ad636..b770a529 100644 --- a/backend/app/core/database.py +++ b/backend/app/core/database.py @@ -8,7 +8,7 @@ engine = create_engine( settings.DATABASE_URL, pool_pre_ping=True, pool_recycle=3600, - echo=settings.DEBUG, + echo=settings.SQLALCHEMY_ECHO, ) # 避免 commit 后 ORM 实例自动过期,导致读取字段时回表 SELECT(高频接口会显著拖慢) diff --git a/backend/app/crud/production_task.py b/backend/app/crud/production_task.py index 0ddd9e29..4f90253b 100644 --- a/backend/app/crud/production_task.py +++ b/backend/app/crud/production_task.py @@ -1264,7 +1264,6 @@ def list_production_tasks( BizProductionTaskStep.del_flag == 0, ) .distinct() - .subquery() ) q = q.filter( or_( @@ -1282,7 +1281,6 @@ def list_production_tasks( BizProductionTaskHandover.del_flag == 0, ) .distinct() - .subquery() ) q = q.filter( BizProductionTask.current_assignee_user_id != mh_uid, @@ -3434,7 +3432,6 @@ def _base_active_step_count_query( BizProductionTaskStep.del_flag == 0, ) .distinct() - .subquery() ) q = q.filter( or_( diff --git a/web-admin/public/clear-local.html b/web-admin/public/clear-local.html new file mode 100644 index 00000000..453b16c1 --- /dev/null +++ b/web-admin/public/clear-local.html @@ -0,0 +1,17 @@ + + +
+ +正在清理本地缓存并跳转登录页…
+ + + diff --git a/web-admin/src/components/core/views/exception/ArtException.vue b/web-admin/src/components/core/views/exception/ArtException.vue index c7880b5f..14933810 100644 --- a/web-admin/src/components/core/views/exception/ArtException.vue +++ b/web-admin/src/components/core/views/exception/ArtException.vue @@ -50,11 +50,12 @@ import ExceptionIllustration from './ExceptionIllustration.vue' import { useCommon } from '@/hooks/core/useCommon' import { useUserStore } from '@/store/modules/user' + import { resetRouteInitState } from '@/router/guards/beforeEach' const router = useRouter() const userStore = useUserStore() - withDefaults( + const props = withDefaults( defineProps<{ code: string title: string @@ -72,7 +73,15 @@ const { homePath } = useCommon() + /** 500 页允许在后端恢复后重新拉菜单/用户信息 */ + const clearInitLockIfServerError = () => { + if (props.variant === 'server-error') { + resetRouteInitState() + } + } + const goBack = () => { + clearInitLockIfServerError() if (window.history.length > 1) { router.back() return @@ -81,6 +90,7 @@ } const backHome = () => { + clearInitLockIfServerError() const targetHomePath = homePath.value || '/' if (!userStore.isLogin) { diff --git a/web-admin/src/router/guards/beforeEach.ts b/web-admin/src/router/guards/beforeEach.ts index 1783690a..b460744f 100644 --- a/web-admin/src/router/guards/beforeEach.ts +++ b/web-admin/src/router/guards/beforeEach.ts @@ -368,8 +368,6 @@ async function handleDynamicRoutes( return } - // 标记初始化失败,防止死循环 - routeInitFailed = true routeInitInProgress = false // 输出详细错误信息,便于排查 @@ -377,7 +375,14 @@ async function handleDynamicRoutes( console.error(`[RouteGuard] 错误码: ${error.code}, 消息: ${error.message}`) } - // 跳转到 500 页面,使用 replace 避免产生历史记录 + // 后端短暂不可达/超时:展示 500,但不永久锁定,便于服务恢复后点「返回首页」重试 + if (isRecoverableInitError(error)) { + next({ name: 'Exception500', replace: true }) + return + } + + // 其它初始化失败:标记失败,防止死循环(刷新页面或重新登录可重置) + routeInitFailed = true next({ name: 'Exception500', replace: true }) } } @@ -448,3 +453,15 @@ function handleRootPathRedirect(to: RouteLocationNormalized, next: NavigationGua function isUnauthorizedError(error: unknown): boolean { return isHttpError(error) && error.code === ApiStatus.unauthorized } + +/** 后端暂不可达类错误:允许用户在服务恢复后重试初始化 */ +function isRecoverableInitError(error: unknown): boolean { + if (!isHttpError(error)) return false + return ( + error.code === ApiStatus.networkError || + error.code === ApiStatus.requestTimeout || + error.code === ApiStatus.badGateway || + error.code === ApiStatus.serviceUnavailable || + error.code === ApiStatus.gatewayTimeout + ) +}