""" backend/app/__init__.py 用途:应用工厂:创建 Flask 应用、挂载全局异常与响应处理。 依赖:app.extensions(db、migrate)、app.api.register_blueprints、app.core.config。 逻辑:create_app 初始化扩展后委托 api 层集中注册 Blueprint;启动时 load_context_adapters 注册 Dify 上下文 adapter; 并幂等补建 file-asset-cleanup 默认排程(覆盖空库先迁移后建用户); AUTO_UPLOAD 显式开启时启动级校验货代上传 RPA 就绪(仅告警不阻断启动)。 """ import logging import uuid from flask import Flask, jsonify, request, g from flask_cors import CORS from werkzeug.exceptions import HTTPException from sqlalchemy import inspect as sqlalchemy_inspect from app.core.config.settings import config from app.core.errors import AppError from app.extensions import db, migrate from app.core.response import error_payload, utc_iso_now logger = logging.getLogger(__name__) def _is_database_table_ready(table_name: str) -> bool: """判断启动期依赖的业务表是否已由 Alembic 创建。 [STEP 1] 使用独立连接查询表元数据,避免空库启动时触发 ORM 查询。 [STEP 2] 表不存在或数据库暂不可用时返回 False,让迁移命令先完成结构初始化。 Args: table_name: 需要检查的 public schema 表名。 Returns: 表存在且可被当前数据库连接访问时返回 True,否则返回 False。 """ try: return bool(sqlalchemy_inspect(db.engine).has_table(table_name)) except Exception as exc: # pragma: no cover - 启动容错 logger.info('Skip startup table readiness check for %s: %s', table_name, exc) return False def _apply_persisted_settings(app: Flask, *, force: bool = False) -> None: """ 将运行时可编辑配置同步进 ``app.config``。 核心逻辑:委托 apply_env_settings(进程内 TTL,默认 30s);force 时强制读库。 表尚未创建(迁移前)时静默跳过。 """ from app.core.config.env_persistence import apply_env_settings try: applied = apply_env_settings(force=force) except Exception as exc: # pragma: no cover - defensive logger.warning('Failed to refresh persisted settings: %s', exc) return for key, value in applied.items(): app.config[key] = value def create_app(config_name='default'): app = Flask(__name__) app.config.from_object(config[config_name]) db.init_app(app) migrate.init_app(app, db) CORS(app) # 允许跨域 from app.api import register_blueprints register_blueprints(app) # 能力声明是代码级契约:组合根在每次 create_app 时显式注册各域能力(幂等), # 保证管理端「能力清单」冷启动即可见,且测试 reset 注册表后建新 app 也能恢复。 # 注意用 from-import:`import app.services...` 会把局部名 app 遮蔽成包模块。 from app.services.in_transit_transfer import capabilities as _transfer_capabilities _transfer_capabilities.register_transfer_capabilities() # 启动时强制加载一次,避免 worker 冷启动到首个请求之间仍用镜像默认值。 with app.app_context(): _apply_persisted_settings(app, force=True) from app.services.agent_runtime_context.bootstrap import load_context_adapters load_context_adapters() from app.services.agent_registry.handlers.bootstrap import load_handlers load_handlers() from app.services.chat.intent_route_registry import ensure_intent_routes_loaded ensure_intent_routes_loaded() # 迁移命令也会创建 app;空库阶段不能执行依赖 schedule_tasks 的 ORM 初始化。 # 迁移完成后正常启动时,此表存在,以下默认排程补建逻辑照常执行。 if _is_database_table_ready('schedule_tasks'): try: from app.services.file_assets.cleanup_schedule import ( ensure_default_file_asset_cleanup_schedule, register_file_asset_cleanup_schedule_hooks, ) register_file_asset_cleanup_schedule_hooks() ensure_default_file_asset_cleanup_schedule() from app.services.shipping_notice.order_extraction_progress_cleanup_schedule import ( ensure_default_order_extraction_progress_cleanup_schedule, ) ensure_default_order_extraction_progress_cleanup_schedule() except Exception as exc: # pragma: no cover - 表未就绪时容忍 logger.warning('Failed to ensure file-asset-cleanup schedule: %s', exc) try: from app.services.voucher_check.schedule_seed import ( ensure_default_voucher_check_schedule, ensure_default_voucher_oa_sales_release_schedule, ensure_default_voucher_po_print_schedule, register_voucher_check_schedule_hooks, ) register_voucher_check_schedule_hooks() ensure_default_voucher_check_schedule() ensure_default_voucher_po_print_schedule() ensure_default_voucher_oa_sales_release_schedule() except Exception as exc: # pragma: no cover - 表未就绪时容忍 logger.warning('Failed to ensure accounting-voucher-check / po-print / oa-sales-release schedules: %s', exc) try: from app.services.contract_payment.schedule_seed import ensure_default_contract_payment_schedules ensure_default_contract_payment_schedules() except Exception as exc: # pragma: no cover - 表未就绪时容忍 logger.warning('Failed to ensure contract-payment schedules: %s', exc) try: from app.services.equipment_acceptance.schedule_seed import ensure_default_equipment_acceptance_schedules ensure_default_equipment_acceptance_schedules() except Exception as exc: # pragma: no cover - 表未就绪时容忍 logger.warning('Failed to ensure equipment-acceptance schedules: %s', exc) try: from app.services.order_delivery_reply.schedule_seed import ensure_default_order_delivery_schedules ensure_default_order_delivery_schedules() except Exception as exc: # pragma: no cover - 表未就绪时容忍 logger.warning('Failed to ensure order-delivery-reply schedule: %s', exc) try: from app.services.order_delivery_reply.app_seed import ensure_builtin_order_delivery_agent ensure_builtin_order_delivery_agent() except Exception as exc: # pragma: no cover - 表未就绪时容忍 logger.warning('Failed to ensure order-delivery-reply agent: %s', exc) try: from app.services.lean_training_schedule_seed import ensure_default_lean_training_schedule ensure_default_lean_training_schedule() except Exception as exc: # pragma: no cover - 表未就绪时容忍 logger.warning('Failed to ensure lean-training schedule: %s', exc) else: logger.info('Skip startup schedule seeding: schedule_tasks table is not ready') # 固资快照同步已迁至独立进程 workers/worker_fixed_assets.py,Web 不再起线程; # 排程执行同样由独立 worker 进程(workers/worker_scheduler.py,生产 hxops-schedule-worker 容器) # 负责(dev Wave 4),Web 进程不再兜底扫描。 # AUTO_UPLOAD 显式开启时启动级校验货代上传 RPA(仅告警,不阻断启动)。 try: from app.services.shipping_notice.rpa_worker_heartbeat import ( log_auto_upload_readiness_at_startup, ) log_auto_upload_readiness_at_startup(app) except Exception as exc: # pragma: no cover - 启动容忍 logger.warning('Failed to check freight upload RPA readiness at startup: %s', exc) @app.before_request def _sync_persisted_settings(): # TTL 内复用进程缓存,不每请求打 app_settings;跨 worker 最多延迟一个 TTL。 _apply_persisted_settings(app) incoming_request_id = (request.headers.get('X-Request-Id') or '').strip() g.request_id = incoming_request_id or f"req_{uuid.uuid4().hex[:16]}" @app.after_request def _wrap_success_response(resp): if not bool(app.config.get('ENABLE_API_ENVELOPE', False)): return resp if not request.path.startswith('/api/'): return resp if resp.is_streamed: return resp if resp.status_code < 200 or resp.status_code >= 300: return resp if not (resp.mimetype or '').startswith('application/json'): return resp try: payload = resp.get_json(silent=True) except Exception: payload = None if isinstance(payload, dict) and 'success' in payload: return resp wrapped = { 'success': True, 'data': payload, 'request_id': getattr(g, 'request_id', None), 'timestamp': utc_iso_now(), } wrapped_resp = jsonify(wrapped) wrapped_resp.status_code = resp.status_code for key, value in resp.headers.items(): lower = key.lower() if lower in ('content-length', 'content-type'): continue wrapped_resp.headers[key] = value return wrapped_resp def _should_return_json_error() -> bool: if request.path.startswith('/api/') or request.path == '/.well-known/jwks.json': return True accepted = request.headers.get('Accept', '') return 'application/json' in accepted.lower() def _log_api_error( *, code: str, message: str, status: int, details: dict | None = None, exc: Exception | None = None, ) -> None: request_id = getattr(g, 'request_id', None) log_kwargs = { 'method': request.method, 'path': request.path, 'status': status, 'code': code, 'message': message, 'request_id': request_id, 'details': details or {}, } log_text = ( 'API error %(method)s %(path)s status=%(status)s code=%(code)s ' 'message=%(message)s request_id=%(request_id)s details=%(details)s' ) if status >= 500: app.logger.error(log_text, log_kwargs, exc_info=exc) else: app.logger.warning(log_text, log_kwargs) @app.errorhandler(HTTPException) def _handle_http_exception(exc: HTTPException): if not _should_return_json_error(): return exc message = exc.description or exc.name or 'HTTP error' code_num = int(exc.code or 500) code_map = { 400: 'VALIDATION.INVALID_PARAM', 401: 'AUTH.UNAUTHORIZED', 403: 'AUTH.FORBIDDEN', 404: 'RESOURCE.NOT_FOUND', 409: 'RESOURCE.CONFLICT', 429: 'SYSTEM.RATE_LIMITED', } code = code_map.get(code_num, 'SYSTEM.HTTP_ERROR') _log_api_error(code=code, message=str(message), status=code_num, exc=exc) payload = error_payload( code=code, message=str(message), request_id=getattr(g, 'request_id', None), ) return jsonify(payload), code_num @app.errorhandler(AppError) def _handle_app_error(exc: AppError): """统一业务异常 → JSON error_payload(API 层应 raise AppError 而非 jsonify error)。""" _log_api_error( code=exc.code, message=exc.message, status=exc.http_status, details=exc.details, exc=exc, ) payload = error_payload( code=exc.code, message=exc.message, request_id=getattr(g, 'request_id', None), details=exc.details, retryable=exc.retryable, ) return jsonify(payload), exc.http_status @app.errorhandler(Exception) def _handle_unexpected_exception(exc: Exception): _log_api_error( code='SYSTEM.INTERNAL_ERROR', message='Internal server error', status=500, exc=exc, ) if not _should_return_json_error(): return '

Internal Server Error

', 500 payload = error_payload( code='SYSTEM.INTERNAL_ERROR', message='Internal server error', request_id=getattr(g, 'request_id', None), ) return jsonify(payload), 500 return app