""" backend/worker.py 用途:统一后台 worker 入口(方案 D)。 依赖:app.create_app、app.jobs.runner、app.jobs.handlers。 逻辑:--queues kb,shipping,contract,schedule;经 jobs.runner 统一 poll → dispatch。 启动诊断按队列打印,避免 schedule worker 误刷合同付款预警 ERP 配置。 """ from __future__ import annotations import argparse import logging import os import sys from typing import Callable 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(label: str = 'main') -> logging.Logger: logger = logging.getLogger(f'hxops.worker.{label}') if not logger.handlers: handler = logging.StreamHandler(sys.stdout) handler.setFormatter(logging.Formatter(f'{_LOG_FORMAT} [worker={label}]')) logger.addHandler(handler) logger.setLevel(logging.INFO) logger.propagate = False return logger def _resolve_config_name() -> str: """ 与 worker_kb 对齐的环境配置解析。 FLASK_ENV=test 表示测试部署主机(.env.test),非 pytest;testing 仅 APP_CONFIG 显式指定时使用。 """ explicit = (os.getenv('APP_CONFIG') or '').strip().lower() if explicit: if explicit in ('testing', 'test'): return 'test' return explicit env_name = (os.getenv('ENV_NAME') or os.getenv('FLASK_ENV') or 'production').strip().lower() mapping = { 'dev': 'development', 'development': 'development', 'test': 'production', 'env': 'production', 'prod': 'production', 'production': 'production', 'testing': 'test', } return mapping.get(env_name, 'production') def _log_queue_startup_diagnostics(logger: logging.Logger, app, queue_names: list[str]) -> None: """ 按实际消费队列打印启动诊断,避免 schedule worker 刷出合同付款预警配置造成误判。 核心逻辑:contract 队列才打印合同付款 ERP 就绪状态;schedule 队列说明 jobs 表身份字段。 只标记配置是否就绪,不输出密码或连接串。 Args: logger: worker logger。 app: Flask 应用,读取 config。 queue_names: 本次启动消费的队列名。 """ if 'contract' in queue_names: erp_dsn = str(app.config.get('CONTRACT_PAYMENT_ERP_DSN') or '').strip() erp_user = str(app.config.get('CONTRACT_PAYMENT_ERP_USERNAME') or '').strip() erp_pwd = str(app.config.get('CONTRACT_PAYMENT_ERP_PASSWORD') or '') logger.info( '合同付款预警 ERP 回查配置: dsn=%s 用户名=%s 密码=%s', '✓就绪' if erp_dsn else '✗缺失', '✓就绪' if erp_user else '✗缺失', '✓就绪' if erp_pwd else '✗缺失', ) if 'schedule' in queue_names: logger.info( 'schedule 队列身份:domain/job_type 固定为 schedule/schedule_run;' '立账凭证检核看 business_ref 后缀 accounting-voucher-check 或 payload.platform_api_path' ) def main( *, queues: list[str] | None = None, config_name: str | None = None, recovery_callback: Callable[[], int] | None = None, recovery_interval_seconds: float = 60.0, ) -> None: """ 启动 worker 主循环。 Args: queues: 消费的队列名列表,如 ['kb'] 或 ['kb', 'shipping']。 config_name: Flask 配置名;默认 _resolve_config_name()。 recovery_callback: 恢复回调函数,返回本轮处理计数;默认 None 关闭。 recovery_interval_seconds: 两次 recovery tick 的最小间隔秒数;默认 60。 """ resolved_config = config_name or _resolve_config_name() logger = _configure_logging() app = create_app(resolved_config) queue_names = queues or ['kb'] _log_queue_startup_diagnostics(logger, app, queue_names) if queue_names == ['schedule'] and not bool(app.config.get('SCHEDULE_WORKER_ENABLED', True)): logger.info('Schedule worker disabled by SCHEDULE_WORKER_ENABLED=false') return with app.app_context(): import app.jobs.handlers # noqa: F401 — 触发 @register_handler ctx = JobContext( config=dict(app.config), logger=logger, extras={'queues': queue_names}, ) logger.info('Worker starting config=%s queues=%s recovery=%s', resolved_config, queue_names, recovery_callback is not None) run_forever( ctx, recovery_callback=recovery_callback, recovery_interval_seconds=recovery_interval_seconds, ) if __name__ == '__main__': parser = argparse.ArgumentParser(description='HXOPS unified background worker') parser.add_argument('--queues', default='kb', help='Comma-separated queue names (kb, shipping, contract, schedule)') parser.add_argument('--config', default=None, dest='config_name', help='Flask config name (optional)') 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)