Files
syops/backend/app/__init__.py
T

267 lines
11 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
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) -> None:
"""Pull the latest runtime-editable settings into ``app.config``.
Reads from the database first, then ``backend/.env``. Tolerates the
common case where the table does not yet exist (fresh deploy before
``flask db upgrade`` runs).
"""
from app.core.config.env_persistence import apply_env_settings
try:
applied = apply_env_settings()
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)
# Eagerly load persisted runtime settings so the very first request after
# a worker boot already sees the admin-saved configuration (otherwise the
# window between worker boot and the first ``before_request`` would still
# serve the defaults baked into config.py / the image).
with app.app_context():
_apply_persisted_settings(app)
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,
register_voucher_check_schedule_hooks,
)
register_voucher_check_schedule_hooks()
ensure_default_voucher_check_schedule()
except Exception as exc: # pragma: no cover - 表未就绪时容忍
logger.warning('Failed to ensure accounting-voucher-check schedule: %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.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')
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
FixedAssetsSnapshotService.start_worker(app)
# 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():
_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 '<h1><p>Internal Server Error</p></h1>', 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