Files
syops/backend/app/__init__.py
T

213 lines
7.8 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 默认排程(覆盖空库先迁移后建用户)。
"""
import logging
import uuid
from flask import Flask, jsonify, request, g
from flask_cors import CORS
from werkzeug.exceptions import HTTPException
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 _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()
from app.services.schedule.scheduler_service import start_scheduler
start_scheduler(app)
# 空库先迁移后建用户:启动补建 + User commit 钩子即时补建,消除无排程窗口
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()
except Exception as exc: # pragma: no cover - 表未就绪时容忍
logger.warning('Failed to ensure file-asset-cleanup schedule: %s', exc)
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
FixedAssetsSnapshotService.start_worker(app)
@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