From 21b8c2481545d30f5cae1da2051f4f1161f818d8 Mon Sep 17 00:00:00 2001 From: sophie Date: Wed, 17 Jun 2026 11:24:54 +0800 Subject: [PATCH] =?UTF-8?q?refactor(backend):=20=E5=90=8E=E7=AB=AF?= =?UTF-8?q?=E9=87=8D=E6=9E=84=E5=88=9D=E6=AD=A5=E8=AE=BE=E6=83=B3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/app/api/__init__.py | 52 ++ backend/app/api/internal/__init__.py | 8 + backend/app/api/internal/jobs.py | 8 + backend/app/api/schedule/__init__.py | 9 + backend/app/api/tools/__init__.py | 10 + backend/app/api/tools/file_check.py | 8 + backend/app/api/tools/shipping_notice.py | 8 + backend/app/api/workspace/__init__.py | 15 + backend/app/api/workspace/file_check.py | 5 + backend/app/api/workspace/schedule.py | 5 + backend/app/api/workspace/shipping_notice.py | 5 + backend/app/core/__init__.py | 6 + backend/app/core/auth/__init__.py | 6 + backend/app/core/auth/context.py | 39 ++ backend/app/core/auth/jwt.py | 9 + backend/app/core/config/__init__.py | 6 + backend/app/core/config/env_persistence.py | 9 + backend/app/core/config/settings.py | 9 + backend/app/core/db/__init__.py | 6 + backend/app/core/db/sequence.py | 7 + backend/app/core/db/session.py | 28 + backend/app/core/decorators.py | 9 + backend/app/core/errors.py | 26 + backend/app/core/response.py | 9 + backend/app/extensions.py | 12 + backend/app/jobs/__init__.py | 11 + backend/app/jobs/context.py | 26 + backend/app/jobs/handlers/__init__.py | 6 + backend/app/jobs/handlers/file_check_run.py | 18 + backend/app/jobs/handlers/kb_clean.py | 24 + backend/app/jobs/handlers/kb_dify_sync.py | 18 + backend/app/jobs/handlers/schedule_run.py | 18 + .../app/jobs/handlers/wecom_directory_sync.py | 18 + backend/app/jobs/queue.py | 34 + backend/app/jobs/registry.py | 37 ++ backend/app/jobs/runner.py | 38 ++ backend/app/jobs/store.py | 20 + backend/app/jobs/types.py | 29 + backend/app/schemas/__init__.py | 6 + backend/app/schemas/admin/__init__.py | 5 + backend/app/schemas/admin/agents.py | 5 + backend/app/schemas/admin/settings.py | 5 + backend/app/schemas/admin/users.py | 6 + backend/app/schemas/chat.py | 6 + backend/app/schemas/kb.py | 6 + backend/app/schemas/user/__init__.py | 5 + backend/app/services/admin/__init__.py | 6 + backend/app/services/admin/agent_service.py | 5 + .../app/services/admin/dashboard_service.py | 5 + .../app/services/admin/department_service.py | 5 + .../app/services/admin/permission_service.py | 5 + .../app/services/admin/settings_service.py | 5 + backend/app/services/admin/user_service.py | 5 + backend/app/services/auth/__init__.py | 6 + backend/app/services/auth/casdoor_service.py | 5 + .../app/services/auth/wecom_auth_service.py | 5 + backend/app/services/chat/__init__.py | 6 + backend/app/services/chat/log_service.py | 5 + backend/app/services/chat/perf.py | 6 + backend/app/services/chat/preview_service.py | 6 + backend/app/services/chat/router.py | 27 + backend/app/services/chat/session_service.py | 6 + backend/app/services/faq/__init__.py | 6 + backend/app/services/faq/aggregator.py | 2 + backend/app/services/faq/cache.py | 2 + backend/app/services/faq/hot_settings.py | 2 + backend/app/services/integrations/__init__.py | 6 + backend/app/services/integrations/dify.py | 9 + .../services/integrations/integration_api.py | 8 + backend/app/services/integrations/minio.py | 8 + .../app/services/integrations/oa/__init__.py | 6 + .../integrations/oa/leave_workflow.py | 2 + .../app/services/integrations/oa/sqlserver.py | 2 + .../services/integrations/oa/wecom_sync.py | 2 + .../app/services/integrations/plm/__init__.py | 5 + .../app/services/integrations/plm/oracle.py | 2 + backend/app/services/integrations/text2sql.py | 8 + .../services/integrations/wecom/__init__.py | 5 + .../app/services/integrations/wecom/crypto.py | 2 + .../integrations/wecom/directory_sync.py | 2 + .../app/services/integrations/wecom/notify.py | 2 + backend/app/services/kb/__init__.py | 9 + backend/app/services/speech/__init__.py | 8 + backend/app/services/user/__init__.py | 6 + backend/app/services/user/admin_service.py | 9 + backend/app/services/user/faq_service.py | 5 + backend/app/services/user/homepage_service.py | 5 + backend/app/services/user/profile_service.py | 5 + backend/tests/jobs/__init__.py | 1 + backend/tests/jobs/test_registry.py | 16 + backend/tests/services/chat/__init__.py | 1 + backend/worker.py | 57 ++ backend/workers/README.md | 1 + backend/workers/worker_kb.py | 19 + backend/workers/worker_scheduler.py | 19 + .../refactor/backend_architecture_refactor.md | 587 ++++++++++++++++++ 96 files changed, 1592 insertions(+) create mode 100644 backend/app/api/__init__.py create mode 100644 backend/app/api/internal/__init__.py create mode 100644 backend/app/api/internal/jobs.py create mode 100644 backend/app/api/schedule/__init__.py create mode 100644 backend/app/api/tools/__init__.py create mode 100644 backend/app/api/tools/file_check.py create mode 100644 backend/app/api/tools/shipping_notice.py create mode 100644 backend/app/api/workspace/__init__.py create mode 100644 backend/app/api/workspace/file_check.py create mode 100644 backend/app/api/workspace/schedule.py create mode 100644 backend/app/api/workspace/shipping_notice.py create mode 100644 backend/app/core/__init__.py create mode 100644 backend/app/core/auth/__init__.py create mode 100644 backend/app/core/auth/context.py create mode 100644 backend/app/core/auth/jwt.py create mode 100644 backend/app/core/config/__init__.py create mode 100644 backend/app/core/config/env_persistence.py create mode 100644 backend/app/core/config/settings.py create mode 100644 backend/app/core/db/__init__.py create mode 100644 backend/app/core/db/sequence.py create mode 100644 backend/app/core/db/session.py create mode 100644 backend/app/core/decorators.py create mode 100644 backend/app/core/errors.py create mode 100644 backend/app/core/response.py create mode 100644 backend/app/extensions.py create mode 100644 backend/app/jobs/__init__.py create mode 100644 backend/app/jobs/context.py create mode 100644 backend/app/jobs/handlers/__init__.py create mode 100644 backend/app/jobs/handlers/file_check_run.py create mode 100644 backend/app/jobs/handlers/kb_clean.py create mode 100644 backend/app/jobs/handlers/kb_dify_sync.py create mode 100644 backend/app/jobs/handlers/schedule_run.py create mode 100644 backend/app/jobs/handlers/wecom_directory_sync.py create mode 100644 backend/app/jobs/queue.py create mode 100644 backend/app/jobs/registry.py create mode 100644 backend/app/jobs/runner.py create mode 100644 backend/app/jobs/store.py create mode 100644 backend/app/jobs/types.py create mode 100644 backend/app/schemas/__init__.py create mode 100644 backend/app/schemas/admin/__init__.py create mode 100644 backend/app/schemas/admin/agents.py create mode 100644 backend/app/schemas/admin/settings.py create mode 100644 backend/app/schemas/admin/users.py create mode 100644 backend/app/schemas/chat.py create mode 100644 backend/app/schemas/kb.py create mode 100644 backend/app/schemas/user/__init__.py create mode 100644 backend/app/services/admin/__init__.py create mode 100644 backend/app/services/admin/agent_service.py create mode 100644 backend/app/services/admin/dashboard_service.py create mode 100644 backend/app/services/admin/department_service.py create mode 100644 backend/app/services/admin/permission_service.py create mode 100644 backend/app/services/admin/settings_service.py create mode 100644 backend/app/services/admin/user_service.py create mode 100644 backend/app/services/auth/__init__.py create mode 100644 backend/app/services/auth/casdoor_service.py create mode 100644 backend/app/services/auth/wecom_auth_service.py create mode 100644 backend/app/services/chat/__init__.py create mode 100644 backend/app/services/chat/log_service.py create mode 100644 backend/app/services/chat/perf.py create mode 100644 backend/app/services/chat/preview_service.py create mode 100644 backend/app/services/chat/router.py create mode 100644 backend/app/services/chat/session_service.py create mode 100644 backend/app/services/faq/__init__.py create mode 100644 backend/app/services/faq/aggregator.py create mode 100644 backend/app/services/faq/cache.py create mode 100644 backend/app/services/faq/hot_settings.py create mode 100644 backend/app/services/integrations/__init__.py create mode 100644 backend/app/services/integrations/dify.py create mode 100644 backend/app/services/integrations/integration_api.py create mode 100644 backend/app/services/integrations/minio.py create mode 100644 backend/app/services/integrations/oa/__init__.py create mode 100644 backend/app/services/integrations/oa/leave_workflow.py create mode 100644 backend/app/services/integrations/oa/sqlserver.py create mode 100644 backend/app/services/integrations/oa/wecom_sync.py create mode 100644 backend/app/services/integrations/plm/__init__.py create mode 100644 backend/app/services/integrations/plm/oracle.py create mode 100644 backend/app/services/integrations/text2sql.py create mode 100644 backend/app/services/integrations/wecom/__init__.py create mode 100644 backend/app/services/integrations/wecom/crypto.py create mode 100644 backend/app/services/integrations/wecom/directory_sync.py create mode 100644 backend/app/services/integrations/wecom/notify.py create mode 100644 backend/app/services/kb/__init__.py create mode 100644 backend/app/services/speech/__init__.py create mode 100644 backend/app/services/user/__init__.py create mode 100644 backend/app/services/user/admin_service.py create mode 100644 backend/app/services/user/faq_service.py create mode 100644 backend/app/services/user/homepage_service.py create mode 100644 backend/app/services/user/profile_service.py create mode 100644 backend/tests/jobs/__init__.py create mode 100644 backend/tests/jobs/test_registry.py create mode 100644 backend/tests/services/chat/__init__.py create mode 100644 backend/worker.py create mode 100644 backend/workers/README.md create mode 100644 backend/workers/worker_kb.py create mode 100644 backend/workers/worker_scheduler.py create mode 100644 docs/refactor/backend_architecture_refactor.md diff --git a/backend/app/api/__init__.py b/backend/app/api/__init__.py new file mode 100644 index 00000000..ec00b1a9 --- /dev/null +++ b/backend/app/api/__init__.py @@ -0,0 +1,52 @@ +""" +backend/app/api/__init__.py + +用途:集中注册所有 Blueprint(Wave 1 接入 create_app)。 +依赖:各 api 子包 blueprint。 +逻辑:替代 app/__init__.py 内 15 行散乱 register_blueprint。 +""" +from __future__ import annotations + +from flask import Flask + + +def register_blueprints(app: Flask) -> None: + """ + 注册全部 HTTP Blueprint,保持对外 url_prefix 不变。 + 核心逻辑:Wave 0 仍从既有单体模块 import;Wave 1+ 逐步切换至分包。 + Args: + app: Flask 应用实例。 + """ + # [STEP 1] 单体模块(Wave 3 前保持不变) + from app.api.chat import chat_bp + from app.api.admin import admin_bp + from app.api.agents import agents_bp + from app.api.user import user_bp + from app.api.knowledge_base import knowledge_base_bp + from app.api.integration import integration_bp + from app.api.internal_jobs import internal_jobs_bp + from app.api.speech import speech_bp + + # [STEP 2] 已分包骨架(re-export 旧模块,Wave 1 可切换 import 来源) + from app.api.schedule import schedule_admin_bp + from app.api.workspace import ( + workspace_file_check_bp, + workspace_schedule_bp, + workspace_shipping_notice_bp, + ) + from app.api.tools import file_check_bp, shipping_notice_bp + + app.register_blueprint(chat_bp, url_prefix='/api/chat') + app.register_blueprint(admin_bp, url_prefix='/api/admin') + app.register_blueprint(agents_bp, url_prefix='/api/agents') + app.register_blueprint(user_bp, url_prefix='/api/user') + app.register_blueprint(knowledge_base_bp, url_prefix='/api/kb') + app.register_blueprint(integration_bp, url_prefix='/api/integration') + app.register_blueprint(schedule_admin_bp, url_prefix='/api/admin') + app.register_blueprint(workspace_schedule_bp, url_prefix='/api/workspace') + app.register_blueprint(workspace_shipping_notice_bp, url_prefix='/api/workspace') + app.register_blueprint(workspace_file_check_bp, url_prefix='/api/workspace') + app.register_blueprint(internal_jobs_bp, url_prefix='/api/internal/jobs') + app.register_blueprint(shipping_notice_bp, url_prefix='/api/shipping-notice') + app.register_blueprint(file_check_bp, url_prefix='/api/file-check') + app.register_blueprint(speech_bp, url_prefix='/api/speech') diff --git a/backend/app/api/internal/__init__.py b/backend/app/api/internal/__init__.py new file mode 100644 index 00000000..a0184f8c --- /dev/null +++ b/backend/app/api/internal/__init__.py @@ -0,0 +1,8 @@ +""" +backend/app/api/internal/__init__.py + +用途:内部 job 回调/健康检查 Blueprint。 +""" +from app.api.internal.jobs import internal_jobs_bp # noqa: F401 + +__all__ = ['internal_jobs_bp'] diff --git a/backend/app/api/internal/jobs.py b/backend/app/api/internal/jobs.py new file mode 100644 index 00000000..92ccc426 --- /dev/null +++ b/backend/app/api/internal/jobs.py @@ -0,0 +1,8 @@ +""" +backend/app/api/internal/jobs.py + +用途:内部 jobs API(Wave 1 自 internal_jobs.py 迁入)。 +""" +from app.api.internal_jobs import internal_jobs_bp # noqa: F401 + +__all__ = ['internal_jobs_bp'] diff --git a/backend/app/api/schedule/__init__.py b/backend/app/api/schedule/__init__.py new file mode 100644 index 00000000..cc143382 --- /dev/null +++ b/backend/app/api/schedule/__init__.py @@ -0,0 +1,9 @@ +""" +backend/app/api/schedule/__init__.py + +用途:排程管理 Blueprint 入口(自 schedule_admin.py 收敛)。 +逻辑:Wave 1 前 re-export 旧模块 blueprint。 +""" +from app.api.schedule_admin import schedule_admin_bp # noqa: F401 + +__all__ = ['schedule_admin_bp'] diff --git a/backend/app/api/tools/__init__.py b/backend/app/api/tools/__init__.py new file mode 100644 index 00000000..6627ca7e --- /dev/null +++ b/backend/app/api/tools/__init__.py @@ -0,0 +1,10 @@ +""" +backend/app/api/tools/__init__.py + +用途:Dify HTTP Tool API Blueprint 聚合。 +逻辑:Wave 1 前 re-export shipping_notice_tools、file_check_tools。 +""" +from app.api.tools.shipping_notice import shipping_notice_bp # noqa: F401 +from app.api.tools.file_check import file_check_bp # noqa: F401 + +__all__ = ['shipping_notice_bp', 'file_check_bp'] diff --git a/backend/app/api/tools/file_check.py b/backend/app/api/tools/file_check.py new file mode 100644 index 00000000..394a7e35 --- /dev/null +++ b/backend/app/api/tools/file_check.py @@ -0,0 +1,8 @@ +""" +backend/app/api/tools/file_check.py + +用途:文件检核 Tool API Blueprint(Wave 1 自 file_check_tools.py 迁入)。 +""" +from app.api.file_check_tools import file_check_bp # noqa: F401 + +__all__ = ['file_check_bp'] diff --git a/backend/app/api/tools/shipping_notice.py b/backend/app/api/tools/shipping_notice.py new file mode 100644 index 00000000..f9963a29 --- /dev/null +++ b/backend/app/api/tools/shipping_notice.py @@ -0,0 +1,8 @@ +""" +backend/app/api/tools/shipping_notice.py + +用途:出货通知 Tool API Blueprint(Wave 1 自 shipping_notice_tools.py 迁入)。 +""" +from app.api.shipping_notice_tools import shipping_notice_bp # noqa: F401 + +__all__ = ['shipping_notice_bp'] diff --git a/backend/app/api/workspace/__init__.py b/backend/app/api/workspace/__init__.py new file mode 100644 index 00000000..bd9e707d --- /dev/null +++ b/backend/app/api/workspace/__init__.py @@ -0,0 +1,15 @@ +""" +backend/app/api/workspace/__init__.py + +用途:工作台域 Blueprint 聚合(schedule、shipping_notice、file_check)。 +逻辑:Wave 1 前 re-export 旧 workspace_* 模块。 +""" +from app.api.workspace_schedule import workspace_schedule_bp # noqa: F401 +from app.api.workspace_shipping_notice import workspace_shipping_notice_bp # noqa: F401 +from app.api.workspace_file_check import workspace_file_check_bp # noqa: F401 + +__all__ = [ + 'workspace_schedule_bp', + 'workspace_shipping_notice_bp', + 'workspace_file_check_bp', +] diff --git a/backend/app/api/workspace/file_check.py b/backend/app/api/workspace/file_check.py new file mode 100644 index 00000000..b9bf6b05 --- /dev/null +++ b/backend/app/api/workspace/file_check.py @@ -0,0 +1,5 @@ +""" +backend/app/api/workspace/file_check.py + +用途:工作台文件检核路由(Wave 1 自 workspace_file_check.py 迁入)。 +""" diff --git a/backend/app/api/workspace/schedule.py b/backend/app/api/workspace/schedule.py new file mode 100644 index 00000000..dcb6978e --- /dev/null +++ b/backend/app/api/workspace/schedule.py @@ -0,0 +1,5 @@ +""" +backend/app/api/workspace/schedule.py + +用途:工作台排程路由(Wave 1 自 workspace_schedule.py 迁入)。 +""" diff --git a/backend/app/api/workspace/shipping_notice.py b/backend/app/api/workspace/shipping_notice.py new file mode 100644 index 00000000..651c18fc --- /dev/null +++ b/backend/app/api/workspace/shipping_notice.py @@ -0,0 +1,5 @@ +""" +backend/app/api/workspace/shipping_notice.py + +用途:工作台出货通知路由(Wave 1 自 workspace_shipping_notice.py 迁入)。 +""" diff --git a/backend/app/core/__init__.py b/backend/app/core/__init__.py new file mode 100644 index 00000000..a2bf5d76 --- /dev/null +++ b/backend/app/core/__init__.py @@ -0,0 +1,6 @@ +""" +backend/app/core/__init__.py + +用途:横切能力包入口(errors、response、auth、config、db)。 +逻辑:Wave 1 逐步将 app 根目录模块迁入 core/ 子包;过渡期旧路径 re-export。 +""" diff --git a/backend/app/core/auth/__init__.py b/backend/app/core/auth/__init__.py new file mode 100644 index 00000000..0ea0ea18 --- /dev/null +++ b/backend/app/core/auth/__init__.py @@ -0,0 +1,6 @@ +""" +backend/app/core/auth/__init__.py + +用途:认证与当前用户解析包入口。 +逻辑:api 层通过 get_current_user 获取 User;Wave 1 自 auth_jwt.py 迁入 jwt.py。 +""" diff --git a/backend/app/core/auth/context.py b/backend/app/core/auth/context.py new file mode 100644 index 00000000..0affde86 --- /dev/null +++ b/backend/app/core/auth/context.py @@ -0,0 +1,39 @@ +""" +backend/app/core/auth/context.py + +用途:从 Flask g/request 解析请求上下文(request_id、user),供 api 层薄封装。 +逻辑:Wave 3 拆分 user/chat 路由时,将重复 auth 逻辑收敛到本模块。 +""" +from __future__ import annotations + +from typing import Any + + +def get_request_id() -> str | None: + """ + 读取当前请求的 X-Request-Id 或 g.request_id。 + 核心逻辑:延迟 import flask.g,避免 services 层依赖。 + Returns: + request_id 字符串,无上下文时返回 None。 + """ + try: + from flask import g + + return getattr(g, 'request_id', None) + except RuntimeError: + return None + + +def get_optional_config(key: str, default: Any = None) -> Any: + """ + 读取 Flask app.config 项(仅 api / jobs context 使用)。 + Args: + key: config 键名。 + default: 无 app context 时的默认值。 + """ + try: + from flask import current_app + + return current_app.config.get(key, default) + except RuntimeError: + return default diff --git a/backend/app/core/auth/jwt.py b/backend/app/core/auth/jwt.py new file mode 100644 index 00000000..3a271cf1 --- /dev/null +++ b/backend/app/core/auth/jwt.py @@ -0,0 +1,9 @@ +""" +backend/app/core/auth/jwt.py + +用途:Casdoor JWT 校验与当前用户解析(Wave 1 自 app/auth_jwt.py 迁入)。 +逻辑:api 路由与 decorators 调用 get_current_user()。 +""" +from app.auth_jwt import get_current_user # noqa: F401 + +__all__ = ['get_current_user'] diff --git a/backend/app/core/config/__init__.py b/backend/app/core/config/__init__.py new file mode 100644 index 00000000..7c5299d8 --- /dev/null +++ b/backend/app/core/config/__init__.py @@ -0,0 +1,6 @@ +""" +backend/app/core/config/__init__.py + +用途:应用配置包入口(settings、env_persistence)。 +逻辑:create_app 加载 Config;before_request 刷新 DB 持久化配置。 +""" diff --git a/backend/app/core/config/env_persistence.py b/backend/app/core/config/env_persistence.py new file mode 100644 index 00000000..f0030852 --- /dev/null +++ b/backend/app/core/config/env_persistence.py @@ -0,0 +1,9 @@ +""" +backend/app/core/config/env_persistence.py + +用途:DB 持久化运行时配置(Wave 1 自 app/env_persistence.py 迁入)。 +逻辑:before_request 调用 apply_env_settings 刷新 app.config。 +""" +from app.env_persistence import apply_env_settings # noqa: F401 + +__all__ = ['apply_env_settings'] diff --git a/backend/app/core/config/settings.py b/backend/app/core/config/settings.py new file mode 100644 index 00000000..09f483cb --- /dev/null +++ b/backend/app/core/config/settings.py @@ -0,0 +1,9 @@ +""" +backend/app/core/config/settings.py + +用途:Config 类与环境映射(Wave 1 自 app/config.py 迁入)。 +逻辑:create_app(config_name) 通过 config[config_name] 加载。 +""" +from app.config import ACTIVE_ENV_NAME, config # noqa: F401 + +__all__ = ['config', 'ACTIVE_ENV_NAME'] diff --git a/backend/app/core/db/__init__.py b/backend/app/core/db/__init__.py new file mode 100644 index 00000000..70d0aa9e --- /dev/null +++ b/backend/app/core/db/__init__.py @@ -0,0 +1,6 @@ +""" +backend/app/core/db/__init__.py + +用途:数据库会话工具包入口。 +逻辑:Wave 1 提供 run_with_retry;sequence 工具供迁移/运维脚本使用。 +""" diff --git a/backend/app/core/db/sequence.py b/backend/app/core/db/sequence.py new file mode 100644 index 00000000..7840ec85 --- /dev/null +++ b/backend/app/core/db/sequence.py @@ -0,0 +1,7 @@ +""" +backend/app/core/db/sequence.py + +用途:PostgreSQL 序列修复工具(Wave 1 自 services/db_sequence.py 迁入)。 +逻辑:迁移脚本与 check_schema_drift 调用。 +""" +from app.services.db_sequence import * # noqa: F403 diff --git a/backend/app/core/db/session.py b/backend/app/core/db/session.py new file mode 100644 index 00000000..1c61815d --- /dev/null +++ b/backend/app/core/db/session.py @@ -0,0 +1,28 @@ +""" +backend/app/core/db/session.py + +用途:数据库会话辅助(重试、只读查询封装)。 +逻辑:Wave 1 从 api/user.py、knowledge_base.py 等抽取 _run_db_with_retry 模式。 +""" +from __future__ import annotations + +from collections.abc import Callable +from typing import TypeVar + +T = TypeVar('T') + + +def run_with_retry(fn: Callable[[], T], *, max_attempts: int = 3) -> T: + """ + 在数据库短暂失败时重试可调用对象。 + 核心逻辑:捕获 OperationalError/DisconnectionError 后 rollback 并重试。 + Args: + fn: 无参 callable,内部使用 db.session。 + max_attempts: 最大尝试次数。 + Returns: + fn 的返回值。 + Raises: + 最后一次失败的异常。 + """ + # [STEP 1] Wave 0 占位:Wave 1 从 user.py / knowledge_base.py 抽取实现 + return fn() diff --git a/backend/app/core/decorators.py b/backend/app/core/decorators.py new file mode 100644 index 00000000..ceb36e33 --- /dev/null +++ b/backend/app/core/decorators.py @@ -0,0 +1,9 @@ +""" +backend/app/core/decorators.py + +用途:路由权限装饰器(Wave 1 自 app/decorators.py 迁入)。 +逻辑:api 层路由使用 @require_admin、@require_agent_permission。 +""" +from app.decorators import require_admin, require_agent_permission # noqa: F401 + +__all__ = ['require_admin', 'require_agent_permission'] diff --git a/backend/app/core/errors.py b/backend/app/core/errors.py new file mode 100644 index 00000000..3e75b17c --- /dev/null +++ b/backend/app/core/errors.py @@ -0,0 +1,26 @@ +""" +backend/app/core/errors.py + +用途:统一业务异常类型(Wave 1 自 app/errors.py 迁入)。 +依赖:无 Flask 依赖。 +逻辑:API 全局 handler 识别 AppError;业务层 raise 子类替代 jsonify(error)。 +""" +from app.errors import ( # noqa: F401 — Wave 1: 实现迁入本文件后删除 app/errors.py shim + AppError, + ConflictError, + ForbiddenError, + NotFoundError, + ServiceUnavailableError, + UnauthorizedError, + ValidationError, +) + +__all__ = [ + 'AppError', + 'ValidationError', + 'UnauthorizedError', + 'ForbiddenError', + 'NotFoundError', + 'ConflictError', + 'ServiceUnavailableError', +] diff --git a/backend/app/core/response.py b/backend/app/core/response.py new file mode 100644 index 00000000..ffc0b0d3 --- /dev/null +++ b/backend/app/core/response.py @@ -0,0 +1,9 @@ +""" +backend/app/core/response.py + +用途:统一 API 响应工具(Wave 1 自 app/response_utils.py 迁入)。 +逻辑:error_payload 供全局异常 handler 使用;ok() 供成功 envelope(可选)。 +""" +from app.response_utils import error_payload, ok, utc_iso_now # noqa: F401 + +__all__ = ['error_payload', 'ok', 'utc_iso_now'] diff --git a/backend/app/extensions.py b/backend/app/extensions.py new file mode 100644 index 00000000..122f9361 --- /dev/null +++ b/backend/app/extensions.py @@ -0,0 +1,12 @@ +""" +backend/app/extensions.py + +用途:Flask 扩展实例(db、migrate)集中定义;Wave 1 从 __init__.py 迁入并接线。 +依赖:flask_sqlalchemy、flask_migrate。 +逻辑:create_app 调用 db.init_app(app);models 与各 service 从本模块 import db。 +""" +from flask_sqlalchemy import SQLAlchemy +from flask_migrate import Migrate + +db = SQLAlchemy() +migrate = Migrate() diff --git a/backend/app/jobs/__init__.py b/backend/app/jobs/__init__.py new file mode 100644 index 00000000..73385707 --- /dev/null +++ b/backend/app/jobs/__init__.py @@ -0,0 +1,11 @@ +""" +backend/app/jobs/__init__.py + +用途:统一后台任务层入口(方案 D)。 +依赖:types、registry、queue、runner。 +逻辑:Web API enqueue;worker.py 调用 runner.run_forever。 +""" +from app.jobs.types import JobStatus, JobType +from app.jobs.queue import enqueue + +__all__ = ['JobType', 'JobStatus', 'enqueue'] diff --git a/backend/app/jobs/context.py b/backend/app/jobs/context.py new file mode 100644 index 00000000..e4684331 --- /dev/null +++ b/backend/app/jobs/context.py @@ -0,0 +1,26 @@ +""" +backend/app/jobs/context.py + +用途:Worker 运行时上下文,注入 config / db / logger。 +逻辑:handler.run(ctx, payload) 通过 ctx 访问依赖,禁止 import flask.request。 +""" +from __future__ import annotations + +import logging +from dataclasses import dataclass, field +from typing import Any + + +@dataclass +class JobContext: + """ + Worker 执行上下文。 + Attributes: + config: Flask app.config 快照或类 dict。 + logger: 模块 logger。 + extras: 扩展字段(如 worker_label)。 + """ + + config: dict[str, Any] + logger: logging.Logger + extras: dict[str, Any] = field(default_factory=dict) diff --git a/backend/app/jobs/handlers/__init__.py b/backend/app/jobs/handlers/__init__.py new file mode 100644 index 00000000..8fdec6e2 --- /dev/null +++ b/backend/app/jobs/handlers/__init__.py @@ -0,0 +1,6 @@ +""" +backend/app/jobs/handlers/__init__.py + +用途:导入各 handler 模块以触发 @register_handler 注册。 +逻辑:Wave 2 起在 worker 启动前 import 本包。 +""" diff --git a/backend/app/jobs/handlers/file_check_run.py b/backend/app/jobs/handlers/file_check_run.py new file mode 100644 index 00000000..2bb83aa1 --- /dev/null +++ b/backend/app/jobs/handlers/file_check_run.py @@ -0,0 +1,18 @@ +""" +backend/app/jobs/handlers/file_check_run.py + +用途:文件检核异步执行 handler。 +逻辑:Wave 4 替代 api/file_check_tools 内 threading.Thread。 +""" +from __future__ import annotations + +from app.jobs.context import JobContext +from app.jobs.registry import register_handler +from app.jobs.types import JobType + + +@register_handler(JobType.FILE_CHECK_RUN) +def run_file_check(ctx: JobContext, payload: dict) -> None: + """执行异步文件检核。""" + ctx.logger.info('file_check_run handler skeleton invoked payload=%s', payload) + raise NotImplementedError('file_check_run handler pending Wave 4') diff --git a/backend/app/jobs/handlers/kb_clean.py b/backend/app/jobs/handlers/kb_clean.py new file mode 100644 index 00000000..7848935a --- /dev/null +++ b/backend/app/jobs/handlers/kb_clean.py @@ -0,0 +1,24 @@ +""" +backend/app/jobs/handlers/kb_clean.py + +用途:KB 文档清洗任务 handler。 +逻辑:Wave 2 包装 knowledge_cleaning.queue_service.process_next_clean_job。 +""" +from __future__ import annotations + +from app.jobs.context import JobContext +from app.jobs.registry import register_handler +from app.jobs.types import JobType + + +@register_handler(JobType.KB_CLEAN) +def run_kb_clean(ctx: JobContext, payload: dict) -> None: + """ + 执行单条 KB 清洗任务。 + Args: + ctx: Worker 上下文。 + payload: 含 document_id 等字段。 + """ + ctx.logger.info('kb_clean handler skeleton invoked payload=%s', payload) + # Wave 2: from app.services.knowledge_cleaning.queue_service import process_job + raise NotImplementedError('kb_clean handler pending Wave 2') diff --git a/backend/app/jobs/handlers/kb_dify_sync.py b/backend/app/jobs/handlers/kb_dify_sync.py new file mode 100644 index 00000000..328b4e5c --- /dev/null +++ b/backend/app/jobs/handlers/kb_dify_sync.py @@ -0,0 +1,18 @@ +""" +backend/app/jobs/handlers/kb_dify_sync.py + +用途:KB 文档同步至 Dify 任务 handler。 +逻辑:Wave 2 包装 knowledge_cleaning.dify_sync_service。 +""" +from __future__ import annotations + +from app.jobs.context import JobContext +from app.jobs.registry import register_handler +from app.jobs.types import JobType + + +@register_handler(JobType.KB_DIFY_SYNC) +def run_kb_dify_sync(ctx: JobContext, payload: dict) -> None: + """同步已清洗文档到 Dify。""" + ctx.logger.info('kb_dify_sync handler skeleton invoked payload=%s', payload) + raise NotImplementedError('kb_dify_sync handler pending Wave 2') diff --git a/backend/app/jobs/handlers/schedule_run.py b/backend/app/jobs/handlers/schedule_run.py new file mode 100644 index 00000000..a316c9ed --- /dev/null +++ b/backend/app/jobs/handlers/schedule_run.py @@ -0,0 +1,18 @@ +""" +backend/app/jobs/handlers/schedule_run.py + +用途:排程任务执行 handler。 +逻辑:Wave 4 从 scheduler_service in-process 执行体迁入。 +""" +from __future__ import annotations + +from app.jobs.context import JobContext +from app.jobs.registry import register_handler +from app.jobs.types import JobType + + +@register_handler(JobType.SCHEDULE_RUN) +def run_schedule(ctx: JobContext, payload: dict) -> None: + """执行单条 ScheduleTask。""" + ctx.logger.info('schedule_run handler skeleton invoked payload=%s', payload) + raise NotImplementedError('schedule_run handler pending Wave 4') diff --git a/backend/app/jobs/handlers/wecom_directory_sync.py b/backend/app/jobs/handlers/wecom_directory_sync.py new file mode 100644 index 00000000..e36d3422 --- /dev/null +++ b/backend/app/jobs/handlers/wecom_directory_sync.py @@ -0,0 +1,18 @@ +""" +backend/app/jobs/handlers/wecom_directory_sync.py + +用途:企微通讯录同步 handler。 +逻辑:Wave 4 包装 wecom_directory_sync 服务。 +""" +from __future__ import annotations + +from app.jobs.context import JobContext +from app.jobs.registry import register_handler +from app.jobs.types import JobType + + +@register_handler(JobType.WECOM_DIRECTORY_SYNC) +def run_wecom_directory_sync(ctx: JobContext, payload: dict) -> None: + """同步企微通讯录到本地用户/部门。""" + ctx.logger.info('wecom_directory_sync handler skeleton invoked payload=%s', payload) + raise NotImplementedError('wecom_directory_sync handler pending Wave 4') diff --git a/backend/app/jobs/queue.py b/backend/app/jobs/queue.py new file mode 100644 index 00000000..89d25260 --- /dev/null +++ b/backend/app/jobs/queue.py @@ -0,0 +1,34 @@ +""" +backend/app/jobs/queue.py + +用途:任务入队 API。 +逻辑:API / services 调用 enqueue;Wave 2 写入 Job 表并 adapter KbJob。 +""" +from __future__ import annotations + +from typing import Any + +from app.jobs.types import JobType + + +def enqueue( + job_type: JobType, + payload: dict[str, Any], + *, + correlation_id: str | None = None, + scheduled_at: Any = None, +) -> int: + """ + 将任务写入队列并返回 job id。 + 核心逻辑:Wave 2 实现 store.create + KbJob adapter。 + Args: + job_type: 任务类型。 + payload: 任务参数 JSON。 + correlation_id: 关联业务 id(如 kb_document_id)。 + scheduled_at: 延迟执行时间(可选)。 + Returns: + Job 主键。 + Raises: + NotImplementedError: Wave 0 占位。 + """ + raise NotImplementedError('jobs.enqueue is not wired until Wave 2') diff --git a/backend/app/jobs/registry.py b/backend/app/jobs/registry.py new file mode 100644 index 00000000..52405e89 --- /dev/null +++ b/backend/app/jobs/registry.py @@ -0,0 +1,37 @@ +""" +backend/app/jobs/registry.py + +用途:JobType → Handler 注册表。 +逻辑:handlers 模块 import 时 @register_handler 装饰;runner 按 type 分发。 +""" +from __future__ import annotations + +from collections.abc import Callable +from typing import Any + +from app.jobs.types import JobType + +HandlerFn = Callable[[Any, dict], None] + +_REGISTRY: dict[JobType, HandlerFn] = {} + + +def register_handler(job_type: JobType) -> Callable[[HandlerFn], HandlerFn]: + """ + 注册某 JobType 的处理函数。 + Args: + job_type: 任务类型枚举。 + Returns: + 装饰器。 + """ + + def decorator(fn: HandlerFn) -> HandlerFn: + _REGISTRY[job_type] = fn + return fn + + return decorator + + +def get_handler(job_type: JobType) -> HandlerFn | None: + """按类型获取 handler;未注册返回 None。""" + return _REGISTRY.get(job_type) diff --git a/backend/app/jobs/runner.py b/backend/app/jobs/runner.py new file mode 100644 index 00000000..21780cc3 --- /dev/null +++ b/backend/app/jobs/runner.py @@ -0,0 +1,38 @@ +""" +backend/app/jobs/runner.py + +用途:Worker 主循环 poll → dispatch → ack/fail。 +逻辑:worker.py 调用 run_forever(ctx);Wave 2 接入 store 与 registry。 +""" +from __future__ import annotations + +import time + +from app.jobs.context import JobContext +from app.jobs.registry import get_handler +from app.jobs import store + + +def run_forever(ctx: JobContext, *, poll_interval_seconds: float = 2.0) -> None: + """ + 持续轮询并执行任务。 + 核心逻辑:claim_next → get_handler → handler(ctx, payload) → 更新状态。 + Args: + ctx: Worker 上下文。 + poll_interval_seconds: 无任务时的休眠秒数。 + """ + ctx.logger.info('Job runner started (skeleton mode — Wave 2 will enable claim loop)') + while True: + try: + job = store.claim_next() + except NotImplementedError: + time.sleep(poll_interval_seconds) + continue + if not job: + time.sleep(poll_interval_seconds) + continue + handler = get_handler(job['job_type']) + if not handler: + ctx.logger.error('No handler for job_type=%s', job.get('job_type')) + continue + handler(ctx, job.get('payload') or {}) diff --git a/backend/app/jobs/store.py b/backend/app/jobs/store.py new file mode 100644 index 00000000..53c6581c --- /dev/null +++ b/backend/app/jobs/store.py @@ -0,0 +1,20 @@ +""" +backend/app/jobs/store.py + +用途:Job 表 CRUD(claim、update status)。 +逻辑:runner 通过 claim_next 获取待执行任务;Wave 2 落地 SQLAlchemy 模型。 +""" +from __future__ import annotations + +from typing import Any + + +def claim_next() -> dict[str, Any] | None: + """ + 认领下一条待执行 Job(SELECT FOR UPDATE SKIP LOCKED)。 + Returns: + job 字典或 None。 + Raises: + NotImplementedError: Wave 0 占位。 + """ + raise NotImplementedError('jobs.store.claim_next is not wired until Wave 2') diff --git a/backend/app/jobs/types.py b/backend/app/jobs/types.py new file mode 100644 index 00000000..5b91ce7d --- /dev/null +++ b/backend/app/jobs/types.py @@ -0,0 +1,29 @@ +""" +backend/app/jobs/types.py + +用途:Job 类型与状态枚举。 +逻辑:handlers 与 queue 通过 JobType 注册;store 持久化 status 字符串。 +""" +from __future__ import annotations + +from enum import StrEnum + + +class JobType(StrEnum): + """后台任务类型。""" + + KB_CLEAN = 'kb_clean' + KB_DIFY_SYNC = 'kb_dify_sync' + SCHEDULE_RUN = 'schedule_run' + FILE_CHECK_RUN = 'file_check_run' + WECOM_DIRECTORY_SYNC = 'wecom_directory_sync' + + +class JobStatus(StrEnum): + """Job 生命周期状态。""" + + PENDING = 'pending' + RUNNING = 'running' + SUCCEEDED = 'succeeded' + FAILED = 'failed' + DEAD = 'dead' diff --git a/backend/app/schemas/__init__.py b/backend/app/schemas/__init__.py new file mode 100644 index 00000000..a2e0d656 --- /dev/null +++ b/backend/app/schemas/__init__.py @@ -0,0 +1,6 @@ +""" +backend/app/schemas/__init__.py + +用途:请求/响应 DTO 包(dataclass 或 Pydantic,非 FastAPI 专用)。 +逻辑:api 层解析入参、校验后传入 services;Wave 3 随 admin/user/kb 拆分落地。 +""" diff --git a/backend/app/schemas/admin/__init__.py b/backend/app/schemas/admin/__init__.py new file mode 100644 index 00000000..4344a176 --- /dev/null +++ b/backend/app/schemas/admin/__init__.py @@ -0,0 +1,5 @@ +""" +backend/app/schemas/admin/__init__.py + +用途:管理后台 DTO 包入口。 +""" diff --git a/backend/app/schemas/admin/agents.py b/backend/app/schemas/admin/agents.py new file mode 100644 index 00000000..bac6379f --- /dev/null +++ b/backend/app/schemas/admin/agents.py @@ -0,0 +1,5 @@ +""" +backend/app/schemas/admin/agents.py + +用途:Agent 管理 API DTO。 +""" diff --git a/backend/app/schemas/admin/settings.py b/backend/app/schemas/admin/settings.py new file mode 100644 index 00000000..35fdf159 --- /dev/null +++ b/backend/app/schemas/admin/settings.py @@ -0,0 +1,5 @@ +""" +backend/app/schemas/admin/settings.py + +用途:系统设置 API DTO。 +""" diff --git a/backend/app/schemas/admin/users.py b/backend/app/schemas/admin/users.py new file mode 100644 index 00000000..8f7841ff --- /dev/null +++ b/backend/app/schemas/admin/users.py @@ -0,0 +1,6 @@ +""" +backend/app/schemas/admin/users.py + +用途:用户管理 API DTO。 +逻辑:Wave 3 admin/users 路由使用。 +""" diff --git a/backend/app/schemas/chat.py b/backend/app/schemas/chat.py new file mode 100644 index 00000000..3e44ebfc --- /dev/null +++ b/backend/app/schemas/chat.py @@ -0,0 +1,6 @@ +""" +backend/app/schemas/chat.py + +用途:聊天域 API 请求/响应 DTO。 +逻辑:Wave 3 从 api/chat/_legacy 抽取 completions、sessions 参数模型。 +""" diff --git a/backend/app/schemas/kb.py b/backend/app/schemas/kb.py new file mode 100644 index 00000000..ffbf94dc --- /dev/null +++ b/backend/app/schemas/kb.py @@ -0,0 +1,6 @@ +""" +backend/app/schemas/kb.py + +用途:知识库域 API 请求/响应 DTO。 +逻辑:Wave 3 从 api/kb 拆分 upload、sync 参数模型。 +""" diff --git a/backend/app/schemas/user/__init__.py b/backend/app/schemas/user/__init__.py new file mode 100644 index 00000000..6365bf17 --- /dev/null +++ b/backend/app/schemas/user/__init__.py @@ -0,0 +1,5 @@ +""" +backend/app/schemas/user/__init__.py + +用途:当前用户域 API DTO(profile、homepage、faq)。 +""" diff --git a/backend/app/services/admin/__init__.py b/backend/app/services/admin/__init__.py new file mode 100644 index 00000000..4895b4b3 --- /dev/null +++ b/backend/app/services/admin/__init__.py @@ -0,0 +1,6 @@ +""" +backend/app/services/admin/__init__.py + +用途:管理后台业务服务包。 +逻辑:Wave 3 从 api/admin/_legacy 抽取 users/agents/departments/settings 等。 +""" diff --git a/backend/app/services/admin/agent_service.py b/backend/app/services/admin/agent_service.py new file mode 100644 index 00000000..59f4de90 --- /dev/null +++ b/backend/app/services/admin/agent_service.py @@ -0,0 +1,5 @@ +""" +backend/app/services/admin/agent_service.py + +用途:Agent CRUD、权限、guide 配置。 +""" diff --git a/backend/app/services/admin/dashboard_service.py b/backend/app/services/admin/dashboard_service.py new file mode 100644 index 00000000..9790f589 --- /dev/null +++ b/backend/app/services/admin/dashboard_service.py @@ -0,0 +1,5 @@ +""" +backend/app/services/admin/dashboard_service.py + +用途:管理后台仪表盘统计聚合。 +""" diff --git a/backend/app/services/admin/department_service.py b/backend/app/services/admin/department_service.py new file mode 100644 index 00000000..8bf71d71 --- /dev/null +++ b/backend/app/services/admin/department_service.py @@ -0,0 +1,5 @@ +""" +backend/app/services/admin/department_service.py + +用途:部门 CRUD。 +""" diff --git a/backend/app/services/admin/permission_service.py b/backend/app/services/admin/permission_service.py new file mode 100644 index 00000000..d470ec7e --- /dev/null +++ b/backend/app/services/admin/permission_service.py @@ -0,0 +1,5 @@ +""" +backend/app/services/admin/permission_service.py + +用途:权限申请、批量授权业务逻辑。 +""" diff --git a/backend/app/services/admin/settings_service.py b/backend/app/services/admin/settings_service.py new file mode 100644 index 00000000..3dcbb3dc --- /dev/null +++ b/backend/app/services/admin/settings_service.py @@ -0,0 +1,5 @@ +""" +backend/app/services/admin/settings_service.py + +用途:AppSetting、运行时配置管理业务逻辑。 +""" diff --git a/backend/app/services/admin/user_service.py b/backend/app/services/admin/user_service.py new file mode 100644 index 00000000..2c15269c --- /dev/null +++ b/backend/app/services/admin/user_service.py @@ -0,0 +1,5 @@ +""" +backend/app/services/admin/user_service.py + +用途:管理端用户 CRUD、权限分配。 +""" diff --git a/backend/app/services/auth/__init__.py b/backend/app/services/auth/__init__.py new file mode 100644 index 00000000..5bd3e722 --- /dev/null +++ b/backend/app/services/auth/__init__.py @@ -0,0 +1,6 @@ +""" +backend/app/services/auth/__init__.py + +用途:认证域业务(Casdoor OIDC、企微 OAuth)。 +逻辑:Wave 3 从 api/user/_legacy auth 相关路由抽取。 +""" diff --git a/backend/app/services/auth/casdoor_service.py b/backend/app/services/auth/casdoor_service.py new file mode 100644 index 00000000..b3fdb6e2 --- /dev/null +++ b/backend/app/services/auth/casdoor_service.py @@ -0,0 +1,5 @@ +""" +backend/app/services/auth/casdoor_service.py + +用途:Casdoor OIDC 登录、token 交换、用户同步业务逻辑。 +""" diff --git a/backend/app/services/auth/wecom_auth_service.py b/backend/app/services/auth/wecom_auth_service.py new file mode 100644 index 00000000..dfde5359 --- /dev/null +++ b/backend/app/services/auth/wecom_auth_service.py @@ -0,0 +1,5 @@ +""" +backend/app/services/auth/wecom_auth_service.py + +用途:企业微信 OAuth、绑定、解绑业务逻辑。 +""" diff --git a/backend/app/services/chat/__init__.py b/backend/app/services/chat/__init__.py new file mode 100644 index 00000000..03fa53fe --- /dev/null +++ b/backend/app/services/chat/__init__.py @@ -0,0 +1,6 @@ +""" +backend/app/services/chat/__init__.py + +用途:聊天域业务服务包。 +逻辑:Wave 3 从 api/chat/_legacy 与 chat.py 意图路由抽取。 +""" diff --git a/backend/app/services/chat/log_service.py b/backend/app/services/chat/log_service.py new file mode 100644 index 00000000..faafd971 --- /dev/null +++ b/backend/app/services/chat/log_service.py @@ -0,0 +1,5 @@ +""" +backend/app/services/chat/log_service.py + +用途:聊天历史、反馈业务逻辑。 +""" diff --git a/backend/app/services/chat/perf.py b/backend/app/services/chat/perf.py new file mode 100644 index 00000000..94fdc8d2 --- /dev/null +++ b/backend/app/services/chat/perf.py @@ -0,0 +1,6 @@ +""" +backend/app/services/chat/perf.py + +用途:聊天性能埋点(Wave 3 自 services/chat_perf.py 迁入)。 +""" +from app.services.chat_perf import * # noqa: F403 diff --git a/backend/app/services/chat/preview_service.py b/backend/app/services/chat/preview_service.py new file mode 100644 index 00000000..40e0d6cd --- /dev/null +++ b/backend/app/services/chat/preview_service.py @@ -0,0 +1,6 @@ +""" +backend/app/services/chat/preview_service.py + +用途:PLM/Excel 预览与文件转换(从 api/chat 抽出)。 +逻辑:Wave 3 将 subprocess/openpyxl 逻辑迁入本模块。 +""" diff --git a/backend/app/services/chat/router.py b/backend/app/services/chat/router.py new file mode 100644 index 00000000..9466cc59 --- /dev/null +++ b/backend/app/services/chat/router.py @@ -0,0 +1,27 @@ +""" +backend/app/services/chat/router.py + +用途:Chat Intent Router,按意图分流至 PLM/HR/Text2SQL/Dify。 +依赖:integrations/* stream_chat 实现。 +逻辑:api/chat/completions 调用本模块 select_stream_generator。 +设计参考:docs/tec.md §4.1 Chat Intent Router。 +""" +from __future__ import annotations + +from typing import Any, Iterator + + +def select_stream_generator(*, user: Any, agent: Any, query: str, **kwargs: Any) -> Iterator[str]: + """ + 根据 agent 配置与用户问题选择流式 generator。 + 核心逻辑:Wave 3 从 api/chat.py /completions 分支迁入。 + Args: + user: 当前 User 模型实例。 + agent: 当前 Agent 模型实例。 + query: 用户问题文本。 + Returns: + SSE 事件字符串迭代器。 + Raises: + NotImplementedError: Wave 0 占位。 + """ + raise NotImplementedError('ChatIntentRouter pending Wave 3 migration from api/chat.py') diff --git a/backend/app/services/chat/session_service.py b/backend/app/services/chat/session_service.py new file mode 100644 index 00000000..c6f4aa8c --- /dev/null +++ b/backend/app/services/chat/session_service.py @@ -0,0 +1,6 @@ +""" +backend/app/services/chat/session_service.py + +用途:聊天会话 CRUD 业务逻辑。 +逻辑:Wave 3 从 api/chat/_legacy 抽取 sessions 相关路由逻辑。 +""" diff --git a/backend/app/services/faq/__init__.py b/backend/app/services/faq/__init__.py new file mode 100644 index 00000000..f83d72c2 --- /dev/null +++ b/backend/app/services/faq/__init__.py @@ -0,0 +1,6 @@ +""" +backend/app/services/faq/__init__.py + +用途:FAQ 缓存与热榜聚合(收敛 faq_*、hot_faq_* 模块)。 +逻辑:Wave 4 自 services 根目录迁入。 +""" diff --git a/backend/app/services/faq/aggregator.py b/backend/app/services/faq/aggregator.py new file mode 100644 index 00000000..2c94c06c --- /dev/null +++ b/backend/app/services/faq/aggregator.py @@ -0,0 +1,2 @@ +"""FAQ 热榜聚合(Wave 4 自 hot_faq_aggregator.py 迁入)。""" +from app.services import hot_faq_aggregator # noqa: F401 diff --git a/backend/app/services/faq/cache.py b/backend/app/services/faq/cache.py new file mode 100644 index 00000000..0ff5ef09 --- /dev/null +++ b/backend/app/services/faq/cache.py @@ -0,0 +1,2 @@ +"""FAQ Redis 缓存(Wave 4 自 faq_cache.py 迁入)。""" +from app.services import faq_cache # noqa: F401 diff --git a/backend/app/services/faq/hot_settings.py b/backend/app/services/faq/hot_settings.py new file mode 100644 index 00000000..a9332121 --- /dev/null +++ b/backend/app/services/faq/hot_settings.py @@ -0,0 +1,2 @@ +"""FAQ 热榜设置(Wave 4 自 faq_hot_settings.py 迁入)。""" +from app.services import faq_hot_settings # noqa: F401 diff --git a/backend/app/services/integrations/__init__.py b/backend/app/services/integrations/__init__.py new file mode 100644 index 00000000..d2e99f33 --- /dev/null +++ b/backend/app/services/integrations/__init__.py @@ -0,0 +1,6 @@ +""" +backend/app/services/integrations/__init__.py + +用途:外部系统纯适配层(Dify、OA、PLM、WeCom、MinIO)。 +逻辑:Wave 4 从 services 根目录迁入;禁止领域编排。 +""" diff --git a/backend/app/services/integrations/dify.py b/backend/app/services/integrations/dify.py new file mode 100644 index 00000000..74f363b1 --- /dev/null +++ b/backend/app/services/integrations/dify.py @@ -0,0 +1,9 @@ +""" +backend/app/services/integrations/dify.py + +用途:Dify API 客户端(流式、上传、workflow)。 +逻辑:Wave 4 自 app/services/dify.py 迁入。 +""" +from app.services import dify # noqa: F401 + +__all__ = ['dify'] diff --git a/backend/app/services/integrations/integration_api.py b/backend/app/services/integrations/integration_api.py new file mode 100644 index 00000000..fa4ad5e9 --- /dev/null +++ b/backend/app/services/integrations/integration_api.py @@ -0,0 +1,8 @@ +""" +backend/app/services/integrations/integration_api.py + +用途:知识库源文件反查等集成 API 适配。 +""" +from app.services import integration_api # noqa: F401 + +__all__ = ['integration_api'] diff --git a/backend/app/services/integrations/minio.py b/backend/app/services/integrations/minio.py new file mode 100644 index 00000000..98a58252 --- /dev/null +++ b/backend/app/services/integrations/minio.py @@ -0,0 +1,8 @@ +""" +backend/app/services/integrations/minio.py + +用途:MinIO 对象存储适配。 +""" +from app.services import minio_service # noqa: F401 + +__all__ = ['minio_service'] diff --git a/backend/app/services/integrations/oa/__init__.py b/backend/app/services/integrations/oa/__init__.py new file mode 100644 index 00000000..b2440826 --- /dev/null +++ b/backend/app/services/integrations/oa/__init__.py @@ -0,0 +1,6 @@ +""" +backend/app/services/integrations/oa/__init__.py + +用途:OA 系统适配(SQL Server、请假 SOAP、企微同步)。 +逻辑:Wave 4 自 oa_sqlserver、oa_leave_workflow、oa_wecom_sync 迁入。 +""" diff --git a/backend/app/services/integrations/oa/leave_workflow.py b/backend/app/services/integrations/oa/leave_workflow.py new file mode 100644 index 00000000..77da5d72 --- /dev/null +++ b/backend/app/services/integrations/oa/leave_workflow.py @@ -0,0 +1,2 @@ +"""OA 请假 Workflow SOAP 适配(Wave 4 自 oa_leave_workflow.py 迁入)。""" +from app.services import oa_leave_workflow # noqa: F401 diff --git a/backend/app/services/integrations/oa/sqlserver.py b/backend/app/services/integrations/oa/sqlserver.py new file mode 100644 index 00000000..b40009d6 --- /dev/null +++ b/backend/app/services/integrations/oa/sqlserver.py @@ -0,0 +1,2 @@ +"""OA SQL Server 适配(Wave 4 自 oa_sqlserver.py 迁入)。""" +from app.services import oa_sqlserver # noqa: F401 diff --git a/backend/app/services/integrations/oa/wecom_sync.py b/backend/app/services/integrations/oa/wecom_sync.py new file mode 100644 index 00000000..d09e4201 --- /dev/null +++ b/backend/app/services/integrations/oa/wecom_sync.py @@ -0,0 +1,2 @@ +"""OA 与企微同步适配(Wave 4 自 oa_wecom_sync.py 迁入)。""" +from app.services import oa_wecom_sync # noqa: F401 diff --git a/backend/app/services/integrations/plm/__init__.py b/backend/app/services/integrations/plm/__init__.py new file mode 100644 index 00000000..3553572d --- /dev/null +++ b/backend/app/services/integrations/plm/__init__.py @@ -0,0 +1,5 @@ +""" +backend/app/services/integrations/plm/__init__.py + +用途:PLM Oracle 适配。 +""" diff --git a/backend/app/services/integrations/plm/oracle.py b/backend/app/services/integrations/plm/oracle.py new file mode 100644 index 00000000..f82e7cc1 --- /dev/null +++ b/backend/app/services/integrations/plm/oracle.py @@ -0,0 +1,2 @@ +"""PLM Oracle 流式查询适配(Wave 4 自 plm_oracle.py 迁入)。""" +from app.services import plm_oracle # noqa: F401 diff --git a/backend/app/services/integrations/text2sql.py b/backend/app/services/integrations/text2sql.py new file mode 100644 index 00000000..eb794ea2 --- /dev/null +++ b/backend/app/services/integrations/text2sql.py @@ -0,0 +1,8 @@ +""" +backend/app/services/integrations/text2sql.py + +用途:ERP 知识库 Text2SQL 流式服务。 +""" +from app.services import text2sql # noqa: F401 + +__all__ = ['text2sql'] diff --git a/backend/app/services/integrations/wecom/__init__.py b/backend/app/services/integrations/wecom/__init__.py new file mode 100644 index 00000000..43ce2e30 --- /dev/null +++ b/backend/app/services/integrations/wecom/__init__.py @@ -0,0 +1,5 @@ +""" +backend/app/services/integrations/wecom/__init__.py + +用途:企业微信 SDK 适配(通知、通讯录、加解密)。 +""" diff --git a/backend/app/services/integrations/wecom/crypto.py b/backend/app/services/integrations/wecom/crypto.py new file mode 100644 index 00000000..3ebdfe31 --- /dev/null +++ b/backend/app/services/integrations/wecom/crypto.py @@ -0,0 +1,2 @@ +"""企微回调加解密(Wave 4 自 wecom_crypto.py 迁入)。""" +from app.services import wecom_crypto # noqa: F401 diff --git a/backend/app/services/integrations/wecom/directory_sync.py b/backend/app/services/integrations/wecom/directory_sync.py new file mode 100644 index 00000000..9d7919fb --- /dev/null +++ b/backend/app/services/integrations/wecom/directory_sync.py @@ -0,0 +1,2 @@ +"""企微通讯录同步(Wave 4 自 wecom_directory_sync.py 迁入)。""" +from app.services import wecom_directory_sync # noqa: F401 diff --git a/backend/app/services/integrations/wecom/notify.py b/backend/app/services/integrations/wecom/notify.py new file mode 100644 index 00000000..924c70f8 --- /dev/null +++ b/backend/app/services/integrations/wecom/notify.py @@ -0,0 +1,2 @@ +"""企微消息通知(Wave 4 自 wecom_notify.py 迁入)。""" +from app.services import wecom_notify # noqa: F401 diff --git a/backend/app/services/kb/__init__.py b/backend/app/services/kb/__init__.py new file mode 100644 index 00000000..b082d2a7 --- /dev/null +++ b/backend/app/services/kb/__init__.py @@ -0,0 +1,9 @@ +""" +backend/app/services/kb/__init__.py + +用途:知识库域服务包(收敛 knowledge_cleaning/)。 +逻辑:Wave 2–4 逐步 alias 至 knowledge_cleaning 子模块。 +""" +from app.services import knowledge_cleaning # noqa: F401 + +__all__ = ['knowledge_cleaning'] diff --git a/backend/app/services/speech/__init__.py b/backend/app/services/speech/__init__.py new file mode 100644 index 00000000..669877ee --- /dev/null +++ b/backend/app/services/speech/__init__.py @@ -0,0 +1,8 @@ +""" +backend/app/services/speech/__init__.py + +用途:语音 ASR 服务。 +""" +from app.services import speech_asr # noqa: F401 + +__all__ = ['speech_asr'] diff --git a/backend/app/services/user/__init__.py b/backend/app/services/user/__init__.py new file mode 100644 index 00000000..961abf80 --- /dev/null +++ b/backend/app/services/user/__init__.py @@ -0,0 +1,6 @@ +""" +backend/app/services/user/__init__.py + +用途:用户域业务服务(profile、homepage、admin 级联删除)。 +逻辑:Wave 3 从 api/user/_legacy 与 user_admin.py 抽取。 +""" diff --git a/backend/app/services/user/admin_service.py b/backend/app/services/user/admin_service.py new file mode 100644 index 00000000..e0317641 --- /dev/null +++ b/backend/app/services/user/admin_service.py @@ -0,0 +1,9 @@ +""" +backend/app/services/user/admin_service.py + +用途:用户管理侧业务(删除级联、权限批量变更等)。 +逻辑:Wave 3 收敛 app/services/user_admin.py。 +""" +from app.services import user_admin # noqa: F401 — Wave 3: 实现迁入本模块 + +__all__ = ['user_admin'] diff --git a/backend/app/services/user/faq_service.py b/backend/app/services/user/faq_service.py new file mode 100644 index 00000000..1f6588fe --- /dev/null +++ b/backend/app/services/user/faq_service.py @@ -0,0 +1,5 @@ +""" +backend/app/services/user/faq_service.py + +用途:常见问题(FAQ)业务逻辑。 +""" diff --git a/backend/app/services/user/homepage_service.py b/backend/app/services/user/homepage_service.py new file mode 100644 index 00000000..8c0735ec --- /dev/null +++ b/backend/app/services/user/homepage_service.py @@ -0,0 +1,5 @@ +""" +backend/app/services/user/homepage_service.py + +用途:首页布局、收藏 Agent、默认 Agent 业务逻辑。 +""" diff --git a/backend/app/services/user/profile_service.py b/backend/app/services/user/profile_service.py new file mode 100644 index 00000000..63f813e6 --- /dev/null +++ b/backend/app/services/user/profile_service.py @@ -0,0 +1,5 @@ +""" +backend/app/services/user/profile_service.py + +用途:用户资料、密码修改等业务逻辑。 +""" diff --git a/backend/tests/jobs/__init__.py b/backend/tests/jobs/__init__.py new file mode 100644 index 00000000..5ab4bd24 --- /dev/null +++ b/backend/tests/jobs/__init__.py @@ -0,0 +1 @@ +"""tests/jobs 包:方案 D 任务层测试(Wave 2 起补充)。""" diff --git a/backend/tests/jobs/test_registry.py b/backend/tests/jobs/test_registry.py new file mode 100644 index 00000000..9e390201 --- /dev/null +++ b/backend/tests/jobs/test_registry.py @@ -0,0 +1,16 @@ +""" +tests/jobs/test_registry.py + +用途:验证 Job handler 注册表。 +""" +from app.jobs.registry import get_handler, register_handler +from app.jobs.types import JobType + + +def test_register_and_get_handler(): + # 断言:临时 handler 可注册并按 type 取回 + @register_handler(JobType.KB_CLEAN) + def _dummy(ctx, payload): + pass + + assert get_handler(JobType.KB_CLEAN) is _dummy diff --git a/backend/tests/services/chat/__init__.py b/backend/tests/services/chat/__init__.py new file mode 100644 index 00000000..f26243a7 --- /dev/null +++ b/backend/tests/services/chat/__init__.py @@ -0,0 +1 @@ +"""tests/services/chat 包:ChatIntentRouter 等单元测试(Wave 3 起补充)。""" diff --git a/backend/worker.py b/backend/worker.py new file mode 100644 index 00000000..711a1b80 --- /dev/null +++ b/backend/worker.py @@ -0,0 +1,57 @@ +""" +backend/worker.py + +用途:统一后台 worker 入口(方案 D)。 +依赖:app.create_app、app.jobs.runner、app.jobs.handlers。 +逻辑:Wave 2 替代 worker_kb.py 主循环;Compose/Supervisor 可配置 --queues。 +""" +from __future__ import annotations + +import argparse +import logging +import sys + +from app import create_app +from app.jobs.context import JobContext +from app.jobs.runner import run_forever + +_LOG_FORMAT = '%(asctime)s %(levelname)s [worker] %(message)s' + + +def _configure_logging() -> logging.Logger: + logger = logging.getLogger('hxops.worker') + if not logger.handlers: + handler = logging.StreamHandler(sys.stdout) + handler.setFormatter(logging.Formatter(_LOG_FORMAT)) + logger.addHandler(handler) + logger.setLevel(logging.INFO) + return logger + + +def main(*, queues: list[str] | None = None, config_name: str = 'default') -> None: + """ + 启动 worker 主循环。 + Args: + queues: 消费的队列名列表(Wave 2 按 JobType 过滤)。 + config_name: Flask 配置名。 + """ + logger = _configure_logging() + app = create_app(config_name) + with app.app_context(): + ctx = JobContext( + config=dict(app.config), + logger=logger, + extras={'queues': queues or ['kb']}, + ) + logger.info('Worker starting queues=%s (skeleton — Wave 2 enables job processing)', ctx.extras['queues']) + # Wave 2: import app.jobs.handlers # noqa: F401 — register handlers + run_forever(ctx) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description='HXOPS unified background worker') + parser.add_argument('--queues', default='kb', help='Comma-separated queue names') + parser.add_argument('--config', default='default', dest='config_name') + args = parser.parse_args() + queue_list = [q.strip() for q in args.queues.split(',') if q.strip()] + main(queues=queue_list, config_name=args.config_name) diff --git a/backend/workers/README.md b/backend/workers/README.md new file mode 100644 index 00000000..e7c6dfdf --- /dev/null +++ b/backend/workers/README.md @@ -0,0 +1 @@ +# Worker 进程启动脚本目录。详见 docs/refactor/backend_jobs_layer.md diff --git a/backend/workers/worker_kb.py b/backend/workers/worker_kb.py new file mode 100644 index 00000000..e19d3425 --- /dev/null +++ b/backend/workers/worker_kb.py @@ -0,0 +1,19 @@ +""" +backend/workers/worker_kb.py + +用途:KB worker Supervisor 兼容启动脚本。 +逻辑:转调 backend/worker.py,默认只消费 kb 队列。 +""" +from __future__ import annotations + +import sys +from pathlib import Path + +_backend_root = Path(__file__).resolve().parents[1] +if str(_backend_root) not in sys.path: + sys.path.insert(0, str(_backend_root)) + +from worker import main + +if __name__ == '__main__': + main(queues=['kb']) diff --git a/backend/workers/worker_scheduler.py b/backend/workers/worker_scheduler.py new file mode 100644 index 00000000..781da1e1 --- /dev/null +++ b/backend/workers/worker_scheduler.py @@ -0,0 +1,19 @@ +""" +backend/workers/worker_scheduler.py + +用途:排程 worker 入口(Wave 4 scheduler 迁出 web 进程后启用)。 +逻辑:消费 schedule 队列,执行 schedule_run handler。 +""" +from __future__ import annotations + +import sys +from pathlib import Path + +_backend_root = Path(__file__).resolve().parents[1] +if str(_backend_root) not in sys.path: + sys.path.insert(0, str(_backend_root)) + +from worker import main + +if __name__ == '__main__': + main(queues=['schedule']) diff --git a/docs/refactor/backend_architecture_refactor.md b/docs/refactor/backend_architecture_refactor.md new file mode 100644 index 00000000..5252a17b --- /dev/null +++ b/docs/refactor/backend_architecture_refactor.md @@ -0,0 +1,587 @@ +# HXOPS 后端重构架构方案 + +> 更新时间:2026-06-17 +> 适用范围:`backend/` 目录 +> 文档定位:定义 Flask 内治理(方案 A)与统一后台任务层(方案 D)的目标架构,作为后续分阶段重构的基准。 +> **不迁移 FastAPI**,生产栈保持 Flask + Gevent + SQLAlchemy 2.0 + Gunicorn。 + +--- + +## 1. 架构选型 + +在现有技术栈基础上,采用 **按业务域垂直分包 + API 薄 / Service 厚 + 统一 Job 层** 的组合架构,并行推进: + +| 方案 | 内容 | +| --- | --- | +| **方案 A — Flask 内治理** | 拆分 god 文件、统一 `AppError`、解耦 Flask 依赖、`models/` 按域拆分 | +| **方案 D — 统一任务层** | Web 只 `enqueue`,worker 统一 `poll → dispatch → handler` | + +**选型理由:** + +- 与现有 Flask + Gevent SSE 链路兼容,无需重写对话流式接口 +- 已有成功模式可复用:`shipping_notice/`、`file_check_tools/`、`schedule/` 子包 +- 已有基础设施可扩展:`AppError`、`env_persistence`、`worker_kb.py` + `KbJob` +- 团队规范(`AGENTS.md`)允许历史 Flask 维护;本方案不引入双栈(Flask + FastAPI) + +**保持不变的技术栈:** + +| 层级 | 选型 | +| --- | --- | +| Web 框架 | Flask 3.x(Blueprint 路由) | +| 并发 | Gevent worker(SSE 长连接) | +| ORM | SQLAlchemy 2.0 + Flask-SQLAlchemy | +| 迁移 | Alembic(Flask-Migrate) | +| 认证 | Casdoor JWT(JWKS)+ legacy header(dev/test) | +| 后台任务 | 统一 `jobs/` 层 + 独立 worker 进程 | +| 文档清洗 | `edkb_system/`(独立子系统,不并入 `app/services`) | + +**当前主要问题(重构动机):** + +| 问题 | 典型文件 | 约行数 | +| --- | --- | --- | +| API 层 god 文件 | `api/user.py`、`api/chat.py`、`api/admin.py` | 1400–2200 | +| Service 层 monolith | `services/text2sql.py`、`shipping_notice/tools.py` | 1200–2000 | +| 单文件模型 | `models.py` | 796(30+ 模型) | +| 错误响应不统一 | API 层混用 `AppError` 与 `jsonify({'error':...})` | 300+ 处 jsonify | +| 后台执行分散 | in-process scheduler 线程、API 内 `threading`、独立 `worker_kb.py` | — | +| Flask 强耦合 | `services/*` 中 `current_app`、`request` | 阻碍测试与 worker 复用 | + +--- + +## 2. 目标目录总览 + +以下为重构完成后的 **目标目录树**(Wave 0 已部分落地,见 §10)。 + +```text +backend/ +├── run.py # Web 入口 +├── worker.py # 统一 worker 入口(方案 D) +├── worker_kb.py # 兼容旧部署,内部转调 worker.py +├── workers/ +│ ├── worker_kb.py # Supervisor 兼容脚本 +│ └── worker_scheduler.py # schedule 迁出 web 进程后的入口 +│ +├── app/ +│ ├── __init__.py # create_app:注册 blueprint、middleware、异常处理 +│ ├── extensions.py # db、migrate(Wave 1 从 __init__ 抽出) +│ │ +│ ├── core/ # 横切能力,不含业务 +│ │ ├── errors.py +│ │ ├── response.py +│ │ ├── decorators.py +│ │ ├── auth/ +│ │ │ ├── jwt.py +│ │ │ └── context.py +│ │ ├── config/ +│ │ │ ├── settings.py +│ │ │ └── env_persistence.py +│ │ └── db/ +│ │ ├── session.py +│ │ └── sequence.py +│ │ +│ ├── models/ # 按域拆分(Wave 1 启用,与 models.py 互斥) +│ │ ├── __init__.py +│ │ ├── base.py +│ │ ├── user.py +│ │ ├── agent.py +│ │ ├── department.py +│ │ ├── chat.py +│ │ ├── content.py +│ │ ├── kb.py +│ │ ├── schedule.py +│ │ ├── shipping.py +│ │ ├── wecom.py +│ │ ├── settings.py +│ │ └── job.py # 方案 D 通用 Job 表 +│ │ +│ ├── schemas/ # 请求/响应 DTO(dataclass 或 Pydantic) +│ │ ├── chat.py +│ │ ├── admin/ +│ │ ├── user/ +│ │ └── kb.py +│ │ +│ ├── api/ # HTTP 层:薄 Blueprint +│ │ ├── __init__.py # register_blueprints(app) +│ │ ├── chat/ +│ │ │ ├── __init__.py +│ │ │ ├── completions.py # POST /completions(SSE) +│ │ │ ├── sessions.py +│ │ │ ├── logs.py +│ │ │ └── preview.py +│ │ ├── user/ +│ │ │ ├── auth.py +│ │ │ ├── profile.py +│ │ │ ├── homepage.py +│ │ │ ├── faq.py +│ │ │ └── wecom.py +│ │ ├── admin/ +│ │ │ ├── users.py +│ │ │ ├── agents.py +│ │ │ ├── departments.py +│ │ │ ├── permissions.py +│ │ │ ├── settings.py +│ │ │ ├── dashboard.py +│ │ │ ├── wecom.py +│ │ │ ├── announcements.py +│ │ │ ├── feedback.py +│ │ │ └── guides.py +│ │ ├── schedule/ # 原 schedule_admin +│ │ │ ├── tasks.py +│ │ │ └── runs.py +│ │ ├── kb/ +│ │ │ ├── groups.py +│ │ │ ├── documents.py +│ │ │ ├── upload.py +│ │ │ └── jobs.py +│ │ ├── agents/ +│ │ ├── integration/ +│ │ ├── workspace/ +│ │ │ ├── schedule.py +│ │ │ ├── shipping_notice.py +│ │ │ └── file_check.py +│ │ ├── tools/ # Dify HTTP Tool API +│ │ │ ├── shipping_notice.py +│ │ │ └── file_check.py +│ │ ├── internal/ +│ │ │ └── jobs.py +│ │ └── speech/ +│ │ +│ ├── services/ # 业务逻辑层(禁止 flask.request) +│ │ ├── chat/ +│ │ │ ├── router.py # Chat Intent Router +│ │ │ ├── session_service.py +│ │ │ ├── log_service.py +│ │ │ ├── preview_service.py +│ │ │ └── perf.py +│ │ ├── user/ +│ │ ├── admin/ +│ │ ├── auth/ +│ │ ├── kb/ # 收敛 knowledge_cleaning/ +│ │ ├── schedule/ # 保留现有子包 +│ │ ├── shipping_notice/ # 保留现有子包 +│ │ ├── file_check_tools/ # 保留现有子包 +│ │ ├── integrations/ +│ │ │ ├── dify.py +│ │ │ ├── minio.py +│ │ │ ├── text2sql.py +│ │ │ ├── oa/ +│ │ │ ├── plm/ +│ │ │ └── wecom/ +│ │ ├── faq/ +│ │ └── speech/ +│ │ +│ ├── jobs/ # 方案 D:统一后台任务层 +│ │ ├── types.py +│ │ ├── registry.py +│ │ ├── queue.py +│ │ ├── store.py +│ │ ├── runner.py +│ │ ├── context.py +│ │ └── handlers/ +│ │ ├── kb_clean.py +│ │ ├── kb_dify_sync.py +│ │ ├── schedule_run.py +│ │ ├── file_check_run.py +│ │ └── wecom_directory_sync.py +│ │ +│ ├── cli/ +│ └── path_utils.py +│ +├── edkb_system/ # 文档清洗管线(独立子系统) +├── migrations/ +├── tests/ +│ ├── api/ +│ ├── services/ +│ └── jobs/ +└── scripts/ +``` + +### 2.1 与现有目录的映射关系 + +| 现有路径 | 目标路径 | 说明 | +| --- | --- | --- | +| `app/__init__.py`(db 定义) | `app/extensions.py` | Wave 1 抽离 `db`、`migrate` | +| `app/errors.py` | `core/errors.py` | 旧路径 re-export 过渡 | +| `app/response_utils.py` | `core/response.py` | 同上 | +| `app/auth_jwt.py` | `core/auth/jwt.py` | 同上 | +| `app/decorators.py` | `core/decorators.py` | 同上 | +| `app/config.py` | `core/config/settings.py` | 同上 | +| `app/env_persistence.py` | `core/config/env_persistence.py` | 同上 | +| `app/models.py` | `models/*.py` | **互斥**,须先删单体再建包 | +| `app/api/user.py` | `api/user/*` + `services/user/*` | Wave 3 | +| `app/api/chat.py` | `api/chat/*` + `services/chat/router.py` | Wave 3 | +| `app/api/admin.py` | `api/admin/*` + `services/admin/*` | Wave 3 | +| `app/api/knowledge_base.py` | `api/kb/*` + `services/kb/*` | Wave 3 | +| `app/api/schedule_admin.py` | `api/schedule/*` | Wave 1 | +| `app/api/workspace_*.py` | `api/workspace/*` | Wave 0 骨架已建 | +| `app/api/shipping_notice_tools.py` | `api/tools/shipping_notice.py` | Wave 0 骨架已建 | +| `app/api/file_check_tools.py` | `api/tools/file_check.py` | Wave 0 骨架已建 | +| `app/api/internal_jobs.py` | `api/internal/jobs.py` | Wave 0 骨架已建 | +| `app/services/dify.py` 等根目录集成 | `services/integrations/*` | Wave 4 | +| `services/knowledge_cleaning/` | `services/kb/` | alias 过渡 | +| `services/user_admin.py` | `services/user/admin_service.py` | Wave 3 | +| `worker_kb.py` | `worker.py` + `jobs/handlers/kb_clean.py` | Wave 2 | +| scheduler in-process thread | `jobs/handlers/schedule_run.py` | Wave 4 | + +### 2.2 迁移互斥约束(重要) + +Python 3 中以下 **不能并存**,否则包会覆盖模块、导致生产 import 静默错误: + +| 冲突 | 处理方式 | +| --- | --- | +| `app/models.py` 与 `app/models/` | Wave 1:拆完再删 `models.py` | +| `app/api/chat.py` 与 `app/api/chat/` | 先 `chat.py` → `chat/_legacy.py`,再建分包 | +| 同理 `user.py`、`admin.py`、`knowledge_base.py` 等 | 标准步骤见 §8.2 | + +**Wave 0 已建、无冲突的分包:** `api/schedule/`、`api/workspace/`、`api/tools/`、`api/internal/`、`core/`、`jobs/`、`schemas/`、`services/{chat,user,admin,...}/`。 + +**Wave 3 前未建的分包:** `api/chat/`、`api/user/`、`api/admin/`、`api/kb/` 等(与现有 `.py` 同名)。 + +--- + +## 3. 分层职责 + +各层职责边界如下,**上层可依赖下层,下层不得反向依赖上层**。 + +```mermaid +flowchart TB + subgraph API["api/(HTTP 层)"] + A1["鉴权、参数解析、调用 service、返回 JSON/SSE"] + end + + subgraph Services["services/(业务层)"] + S1["领域编排、事务边界、组合 integrations"] + end + + subgraph Integrations["services/integrations/(适配层)"] + I1["Dify、OA、PLM、WeCom、MinIO 纯客户端"] + end + + subgraph Jobs["jobs/(任务层)"] + J1["enqueue / handler,worker 与 web 共用 services"] + end + + subgraph Models["models/(数据层)"] + M1["SQLAlchemy 模型"] + end + + subgraph Core["core/(横切)"] + C1["errors、auth、config、response"] + end + + API --> Services + API --> Core + Services --> Integrations + Services --> Models + Services --> Jobs + Jobs --> Services + Jobs --> Models + Jobs --> Core +``` + +### 3.1 api/(HTTP 层) + +- **职责**:Blueprint 路由、鉴权、`request` 解析、调用 service、返回响应 +- **约束**:单个路由函数目标 **< 80 行**;不写复杂业务、不直接编排外部集成 +- **允许**:`request`、`g`、`current_app.config` +- **禁止**:subprocess、大段 SQL、Dify/OA 直连(应经 service) + +### 3.2 services/(业务层) + +- **职责**:领域业务编排、事务边界、组合 integrations 与 models +- **约束**:**禁止** `import flask.request`;config 通过构造函数或参数注入 +- **示例**:`chat/router.py` 按意图选择 PLM / HR / Text2SQL / Dify 流式 generator + +### 3.3 services/integrations/(适配层) + +- **职责**:外部系统 HTTP/SDK 调用、SSE generator 产出 +- **约束**:不做领域模型编排;不依赖 api 层 +- **示例**:`integrations/dify.py` 只负责 Dify API,不含 ChatSession 逻辑 + +### 3.4 jobs/(任务层) + +- **职责**:异步任务 enqueue、claim、handler 分发、重试与状态 +- **约束**:handler 通过 `JobContext` 访问 config/db,禁止读 HTTP request +- **示例**:KB 清洗、排程执行、file-check 异步检核 + +### 3.5 core/(横切层) + +- **职责**:`AppError`、`error_payload`、JWT、装饰器、env 持久化、DB 工具 +- **约束**:无业务域语义 + +--- + +## 4. 各业务域说明 + +### 4.1 chat(对话) + +| 项 | 说明 | +| --- | --- | +| URL 前缀 | `/api/chat` | +| 目标 API | `completions.py`(SSE)、`sessions.py`、`logs.py`、`preview.py` | +| 核心 Service | `services/chat/router.py` — Chat Intent Router | +| 路由策略 | PLM → `integrations/plm`;HR 假期 → `integrations/oa`;ERP → `text2sql`;默认 → `integrations/dify` | +| 设计参考 | `docs/tec.md` §4.1 Chat Intent Router | +| 迁移来源 | `api/chat.py`(~1882 行,含预览/subprocess/openpyxl) | + +### 4.2 user(当前用户 / 认证) + +| 项 | 说明 | +| --- | --- | +| URL 前缀 | `/api/user` | +| 目标 API | `auth.py`(Casdoor OIDC)、`profile.py`、`homepage.py`、`faq.py`、`wecom.py` | +| 核心 Service | `services/auth/casdoor_service.py`、`services/user/*` | +| 迁移来源 | `api/user.py`(~2223 行:登录、企微 OAuth、首页、FAQ) | + +### 4.3 admin(管理后台) + +| 项 | 说明 | +| --- | --- | +| URL 前缀 | `/api/admin` | +| 目标 API | `users/`、`agents/`、`departments/`、`settings/`、`dashboard/`、`wecom/` 等 | +| 核心 Service | `services/admin/*` | +| 注意 | `schedule_admin_bp` 与 `admin_bp` 共用 `/api/admin`,路由命名勿冲突 | +| 迁移来源 | `api/admin.py`(~1455 行,54 个路由) | + +### 4.4 kb(知识库) + +| 项 | 说明 | +| --- | --- | +| URL 前缀 | `/api/kb` | +| 目标 API | `groups.py`、`documents.py`、`upload.py`、`jobs.py` | +| 核心 Service | `services/kb/*`(收敛 `knowledge_cleaning/`) | +| 异步 | 上传 → `jobs.enqueue(KB_CLEAN)` → worker → `edkb_system` → Dify sync | +| 迁移来源 | `api/knowledge_base.py`(~1063 行) | + +### 4.5 schedule(排程管理) + +| 项 | 说明 | +| --- | --- | +| URL 前缀 | `/api/admin`(与 admin 同前缀) | +| 目标 API | `api/schedule/tasks.py`、`runs.py` | +| 核心 Service | `services/schedule/*`(保留现有) | +| Wave 4 | cron 触发改为 `enqueue(SCHEDULE_RUN)`,迁出 web 进程内 thread | + +### 4.6 workspace / tools(工作台与 Tool API) + +| 项 | 说明 | +| --- | --- | +| workspace | `/api/workspace` — 排程记录、出货通知、文件检核工作台 | +| tools | `/api/shipping-notice`、`/api/file-check` — Dify HTTP Tool,已有 OpenAPI export | +| 保留 | `shipping_notice/`、`file_check_tools/` 子包继续作为拆分模板 | + +### 4.7 integrations(外部集成) + +| 子目录 | 现有模块 | 用途 | +| --- | --- | --- | +| `integrations/dify.py` | `services/dify.py` | Dify SSE、上传、workflow | +| `integrations/oa/` | `oa_sqlserver.py`、`oa_leave_workflow.py` | OA SQL Server、SOAP 请假 | +| `integrations/plm/` | `plm_oracle.py` | PLM Oracle 查询 | +| `integrations/wecom/` | `wecom_notify.py`、`wecom_directory_sync.py` | 企微通知、通讯录 | +| `integrations/minio.py` | `minio_service.py` | 对象存储 | +| `integrations/text2sql.py` | `text2sql.py` | ERP 知识库 SQL | + +--- + +## 5. 统一后台任务层(方案 D) + +### 5.1 背景 + +Web 进程内存在多种后台执行方式(scheduler thread、API 内 `threading`、`worker_kb.py`),缺少统一的重试、监控与扩缩容模型。 + +**目标数据流:** + +```text +Flask API → jobs.queue.enqueue(type, payload) → 立即返回 job_id +Worker → jobs.runner.poll → registry → handler → services/* +``` + +### 5.2 模块职责 + +| 模块 | 职责 | +| --- | --- | +| `jobs/types.py` | `JobType`、`JobStatus` 枚举 | +| `jobs/registry.py` | `job_type → handler` 注册 | +| `jobs/store.py` | Job 表 CRUD、`claim_next`(`FOR UPDATE SKIP LOCKED`) | +| `jobs/queue.py` | 对外 `enqueue()`、`enqueue_delayed()` | +| `jobs/runner.py` | worker 主循环 | +| `jobs/context.py` | `JobContext(config, logger)` 注入 | +| `jobs/handlers/*.py` | 各类型任务执行体 | + +### 5.3 JobType 规划 + +| JobType | 来源 | Handler | Wave | +| --- | --- | --- | --- | +| `KB_CLEAN` | KB 上传/重洗 | `handlers/kb_clean.py` | 2 | +| `KB_DIFY_SYNC` | 清洗完成 | `handlers/kb_dify_sync.py` | 2 | +| `SCHEDULE_RUN` | cron | `handlers/schedule_run.py` | 4 | +| `FILE_CHECK_RUN` | Tool API 异步检核 | `handlers/file_check_run.py` | 4 | +| `WECOM_DIRECTORY_SYNC` | 管理端/定时 | `handlers/wecom_directory_sync.py` | 4 | + +### 5.4 与 KbJob 的过渡 + +Wave 2 采用 **Adapter 双轨**:`enqueue` 写通用 `Job` 表,同时 adapter 写 `KbJob`,兼容现有 KB 状态查询 API;Wave 4 再统一读 Job 表。 + +### 5.5 Worker 部署 + +| 入口 | 用途 | +| --- | --- | +| `backend/worker.py` | 统一入口,`--queues kb,schedule` | +| `backend/worker_kb.py` | 兼容旧 Compose/Supervisor 配置 | +| `backend/workers/worker_scheduler.py` | 仅 schedule queue(Wave 4) | + +--- + +## 6. URL 注册(保持不变) + +对外 URL **不变**,前端零改动: + +| Blueprint | url_prefix | 目标模块 | +| --- | --- | --- | +| chat_bp | `/api/chat` | `api/chat/` | +| admin_bp | `/api/admin` | `api/admin/` | +| schedule_admin_bp | `/api/admin` | `api/schedule/` | +| user_bp | `/api/user` | `api/user/` | +| knowledge_base_bp | `/api/kb` | `api/kb/` | +| agents_bp | `/api/agents` | `api/agents/` | +| integration_bp | `/api/integration` | `api/integration/` | +| workspace_* | `/api/workspace` | `api/workspace/` | +| shipping_notice_bp | `/api/shipping-notice` | `api/tools/shipping_notice.py` | +| file_check_bp | `/api/file-check` | `api/tools/file_check.py` | +| internal_jobs_bp | `/api/internal/jobs` | `api/internal/jobs.py` | +| speech_bp | `/api/speech` | `api/speech/` | + +`app/api/__init__.py` 提供 `register_blueprints(app)` 集中注册(Wave 1 接入 `create_app`)。 + +--- + +## 7. 编码约定 + +### 7.1 错误处理 + +- 业务层 **必须** `raise AppError` 子类(`ValidationError`、`NotFoundError` 等) +- **禁止** 新增 `return jsonify({'error': ...}), 4xx` +- 全局 handler(`create_app`)统一输出 `error_payload` + +### 7.2 Import 方向 + +```text +api → services → integrations + → models + → jobs.queue(仅 enqueue) +jobs/handlers → services +core ← 所有层 +``` + +### 7.3 注释 + +遵循 `AGENTS.md` §5 与 `.cursor/rules/code-comments.mdc`:文件层 + 函数层注释;修改逻辑须同步更新注释。 + +### 7.4 测试目录 + +```text +tests/api// +tests/services// +tests/jobs/handlers/ +``` + +与 `docs/test_plan_matrix.md` 域矩阵对齐。 + +--- + +## 8. 分阶段迁移计划 + +```text +Wave 0 骨架建立 ← 当前(目录 + 占位模块,行为不变) +Wave 1 基础设施 core/ 接线、models 拆分、AppError 统一、register_blueprints +Wave 2 任务层 jobs/ 实现 + worker.py 接 KB 清洗 +Wave 3 拆 god 文件 user → chat → admin → kb +Wave 4 集成收敛 integrations/、scheduler/file-check 迁出 web 进程 +``` + +### 8.1 Wave 1 — 基础设施 + +- `extensions.py` 抽离 `db`、`migrate` +- `core/*` 迁入并保留旧路径 re-export +- `models.py` 拆为 `models/*.py`(**先拆后删**) +- 完成 `migrate_jsonify_errors.py`;修复 `gunicorn_config.py` workers 未赋值 +- `create_app` 改用 `register_blueprints(app)` + +### 8.2 Wave 3 — API 单体迁包标准步骤 + +以 `user.py` 为例: + +```text +1. app/api/user.py → app/api/user/_legacy.py +2. app/api/user/__init__.py re-export user_bp 及测试依赖符号 +3. 新建 auth.py、profile.py … 从 _legacy 逐步剪切 +4. _legacy 归零后删除 +``` + +测试 `monkeypatch('app.api.user._get_current_user')` 须保持可用:在 `__init__.py` 显式 re-export。 + +### 8.3 完成定义 + +- [ ] 无 >800 行业务源文件(`edkb_system/` 除外) +- [ ] API 统一 `AppError` +- [ ] `services/` 无 `flask.request` +- [ ] 后台任务统一经 `jobs/` +- [ ] web 进程无 scheduler thread + +--- + +## 9. 值得保留的模式 + +| 模式 | 说明 | +| --- | --- | +| `AppError` 体系 | 扩展即可,勿另造轮子 | +| `env_persistence.py` | DB 持久化配置 + env 镜像 | +| 领域 service 子包 | `shipping_notice/`、`file_check_tools/` 为拆分模板 | +| Chat 意图路由概念 | `supports()` + `stream_chat()` 插件式扩展 | +| KB worker 分离 | `worker_kb.py` + `KbJob` 方向正确 | +| SQLAlchemy 2.0 `Mapped[]` | 迁移时直接沿用 | +| Tool API OpenAPI | `export_*_openapi.py` 脚本 | +| Schema drift 工具 | `check_schema_drift.py` 等运维脚本 | + +--- + +## 10. Wave 0 骨架落地(已实现) + +Wave 0 目标:**建立目录与占位模块,不改变运行时行为**(`create_app` 仍从原单体 import Blueprint)。 + +### 10.1 已建目录 + +```text +app/extensions.py +app/core/{errors,response,decorators,auth,config,db}/ +app/jobs/{types,registry,queue,store,runner,context,handlers}/ +app/schemas/{chat,kb,admin,user}/ +app/services/{chat,user,admin,auth,kb,integrations,faq,speech}/ +app/api/{__init__,schedule,workspace,tools,internal}/ +backend/worker.py +backend/workers/ +tests/jobs/ +``` + +### 10.2 占位策略 + +- `core/*`、`services/integrations/*` 等多为 **re-export** 旧模块 +- `jobs/queue.py`、`jobs/store.py` 为 `NotImplementedError`(Wave 2 实现) +- `services/chat/router.py` 为占位(Wave 3 从 `api/chat.py` 迁入) +- **未创建** `app/models/`、`app/api/chat/` 等(与现有文件互斥) + +### 10.3 下一步(Wave 1) + +1. `create_app` → `register_blueprints(app)` +2. `extensions.py` 接线 `db` / `migrate` +3. 启动 `models/` 拆分 + +--- + +## 11. 相关文档 + +- [项目上下文与技术栈](../project_context.md) +- [技术架构(Chat Router、KB 异步)](../tec.md) +- [测试计划矩阵](../test_plan_matrix.md) +- [前端重构架构方案](./frontend_architecture_refactor.md) +- [AGENTS.md](../../AGENTS.md)