""" backend/app/jobs/queue.py 用途:通用后台任务入队、领取与完成状态管理,并保留旧 KB 入队兼容入口。 依赖:models.Job、jobs.types、Flask app.config、knowledge_cleaning 队列适配层。 逻辑:业务服务调用 enqueue 写入 jobs;旧 KB 清洗入口委托 legacy KbJob 队列;worker 调用 claim/finish/fail 完成执行闭环。 """ from __future__ import annotations import socket from datetime import datetime, timedelta from typing import Any from flask import current_app from sqlalchemy.exc import OperationalError from app import db from app.core.errors import ValidationError from app.jobs.types import JobType from app.models import Job ACTIVE_STATUSES = ("queued", "running") TERMINAL_STATUSES = ("success", "failed", "dead", "cancelled") def _normalize_job_type(job_type: JobType | str) -> str: """把 JobType 或字符串统一成数据库保存值。""" return str(getattr(job_type, "value", job_type) or "").strip() def _worker_id() -> str: """生成当前 worker 标识,用于锁记录和排障。""" try: host = socket.gethostname() except Exception: host = "unknown-host" return f"{host}:{id(db.session)}" def _find_shipping_notice_job_id(task_no: str) -> int | None: """ 按 task_no 查找发货任务对应的 KbJob。 Args: task_no: 发货任务号;由 AI 或业务代码传入时可大小写混用。 Returns: 匹配到的最新 KbJob 主键;未找到返回 None。 """ from app import db from app.models import KbJob normalized_task_no = str(task_no or '').strip().upper() candidates = ( db.session.query(KbJob) .filter( KbJob.job_type == JobType.SHIPPING_NOTICE_RUN.value, KbJob.status.in_(('queued', 'running', 'success', 'failed')), ) .order_by(KbJob.id.desc()) .limit(50) .all() ) for job in candidates: payload_json = job.payload_json or {} if str(payload_json.get('task_no') or '').strip().upper() == normalized_task_no: return job.id return None def enqueue_kb_job(job_id: int) -> tuple[bool, str]: """ 兼容旧知识库后台任务入队入口。 Args: job_id: KbJob 主键;由清洗、路径上传、Dify 同步等知识库流程传入。 Returns: (是否接受入队, 队列状态说明)。 """ from app.services.knowledge_cleaning.queue_service import enqueue_kb_job as _enqueue_kb_job return _enqueue_kb_job(job_id) def enqueue_clean_job(job_id: int) -> tuple[bool, str]: """ 兼容旧清洗任务入队入口。 Args: job_id: clean 类型 KbJob 主键。 Returns: (是否接受入队, 队列状态说明)。 """ return enqueue_kb_job(job_id) def enqueue( job_type: JobType | str, payload: dict[str, Any], *, domain: str = "default", business_ref: str | None = None, created_by_id: int | None = None, priority: int = 0, max_attempts: int = 3, message: str | None = None, dedupe_active: bool = True, correlation_id: str | None = None, scheduled_at: Any = None, ) -> int: """ 将任务写入通用 jobs 队列并返回 job id。 Args: job_type: 任务类型。 payload: JSON payload。 domain: 业务域,如 shipping_notice。 business_ref: 业务幂等锚点,如发货任务号。 created_by_id: 创建人。 priority: 优先级,数值越大越先执行。 max_attempts: 最大尝试次数。 message: 初始状态说明。 dedupe_active: 是否复用 active 状态的同业务任务。 correlation_id: 兼容旧接口;business_ref 为空时作为业务锚点。 scheduled_at: 未来时间则延迟到该时间后才可被 worker 领取。 """ normalized_type = _normalize_job_type(job_type) if normalized_type in {JobType.KB_CLEAN.value, JobType.KB_DIFY_SYNC.value}: raw_job_id = (payload or {}).get("job_id") if isinstance(payload, dict) else None if not raw_job_id: raise ValidationError("job_id is required") ok, message_text = enqueue_kb_job(int(raw_job_id)) if not ok: raise ValidationError(message_text or "enqueue kb job failed") return int(raw_job_id) normalized_domain = str(domain or "").strip() or "default" normalized_ref = str(business_ref or correlation_id or "").strip() or None if not normalized_type: raise ValueError("job_type is required") if not isinstance(payload, dict): raise ValueError("payload must be a dict") if dedupe_active and normalized_ref: existing = ( db.session.query(Job) .filter( Job.domain == normalized_domain, Job.job_type == normalized_type, Job.business_ref == normalized_ref, Job.status.in_(ACTIVE_STATUSES), ) .order_by(Job.created_at.desc(), Job.id.desc()) .first() ) if existing: return int(existing.id) now = datetime.utcnow() queue_at = scheduled_at if isinstance(scheduled_at, datetime) else now job = Job( domain=normalized_domain, job_type=normalized_type, status="queued", priority=int(priority or 0), business_ref=normalized_ref, payload_json=payload, progress=0, message=message or "等待后台处理", attempts=0, max_attempts=max(1, int(max_attempts or 1)), created_by_id=created_by_id, created_at=queue_at, updated_at=now, ) db.session.add(job) db.session.commit() return int(job.id) def recover_stale_jobs(*, domain: str, timeout_seconds: float, job_type: str | JobType | None = None) -> int: """回收指定业务域内超时 running 的通用任务。""" cutoff = datetime.utcnow() - timedelta(seconds=float(timeout_seconds)) query = ( db.session.query(Job) .filter( Job.domain == domain, Job.status == "running", Job.started_at.isnot(None), Job.started_at < cutoff, ) ) normalized_type = _normalize_job_type(job_type) if job_type else "" if normalized_type: query = query.filter(Job.job_type == normalized_type) stale_jobs = query.order_by(Job.started_at.asc(), Job.id.asc()).all() if not stale_jobs: return 0 now = datetime.utcnow() for job in stale_jobs: if int(job.attempts or 0) < int(job.max_attempts or 1): job.status = "queued" job.message = "任务执行超时,已回收等待重试" job.locked_by = None job.locked_at = None job.started_at = None job.updated_at = now continue job.status = "failed" job.error_message = f"任务执行超时(超过 {int(timeout_seconds)}s)" job.message = job.error_message job.progress = 100 job.locked_by = None job.locked_at = None job.finished_at = now job.updated_at = now db.session.commit() return len(stale_jobs) def claim_next_job(*, domain: str, job_types: list[str | JobType] | None = None, worker_id: str | None = None) -> Job | None: """原子领取指定业务域下一条 queued 任务。""" normalized_types = [_normalize_job_type(item) for item in (job_types or []) if _normalize_job_type(item)] now = datetime.utcnow() try: query = db.session.query(Job).filter( Job.domain == domain, Job.status == "queued", Job.created_at <= now, ) if normalized_types: query = query.filter(Job.job_type.in_(normalized_types)) job = ( query.order_by(Job.priority.desc(), Job.created_at.asc(), Job.id.asc()) .with_for_update(skip_locked=True) .first() ) except OperationalError: db.session.rollback() raise if not job: db.session.rollback() return None job.status = "running" job.started_at = job.started_at or now job.locked_at = now job.locked_by = worker_id or _worker_id() job.attempts = int(job.attempts or 0) + 1 job.progress = max(int(job.progress or 0), 1) job.message = "worker 已领取任务" job.updated_at = now db.session.commit() return job def finish_job(job: Job, *, result: dict[str, Any] | None = None, message: str | None = None) -> None: """标记任务成功完成。""" now = datetime.utcnow() job.status = "success" job.progress = 100 job.result_json = result or {} job.message = message or "任务处理完成" job.error_message = None job.locked_by = None job.locked_at = None job.finished_at = now job.updated_at = now db.session.commit() def fail_job(job: Job, *, error: str, result: dict[str, Any] | None = None, retryable: bool = False) -> None: """标记任务失败;retryable 且未达上限时重新排队。""" now = datetime.utcnow() can_retry = retryable and int(job.attempts or 0) < int(job.max_attempts or 1) job.status = "queued" if can_retry else "failed" job.progress = 0 if can_retry else 100 job.result_json = result or {} job.error_message = str(error or "job failed")[:1000] job.message = "任务失败,等待重试" if can_retry else job.error_message job.locked_by = None job.locked_at = None job.finished_at = None if can_retry else now job.updated_at = now db.session.commit() def process_next_job( *, ctx: Any, domain: str, job_types: list[str | JobType] | None = None, timeout_config_key: str | None = None, default_timeout_seconds: float = 300, ) -> tuple[bool, str]: """领取并分发一条通用任务。""" import app.jobs.handlers # noqa: F401 from app.jobs.registry import get_handler timeout_seconds = float( current_app.config.get(timeout_config_key, default_timeout_seconds) if timeout_config_key else default_timeout_seconds ) recover_stale_jobs(domain=domain, timeout_seconds=timeout_seconds) job = claim_next_job(domain=domain, job_types=job_types) if not job: return False, "no_job" job_id = int(job.id) job_type_value = str(job.job_type or "").strip() payload = dict(job.payload_json or {}) payload.setdefault("job_id", job_id) handler = get_handler(JobType(job_type_value)) if handler is None: fail_job(job, error=f"no handler registered for {job.job_type}") return True, "missing_handler" try: handler(ctx, payload) refreshed = db.session.get(Job, job_id) if refreshed and refreshed.status == "running": finish_job(refreshed, message="任务处理完成") return True, job_type_value except Exception as exc: db.session.rollback() refreshed = db.session.get(Job, job_id) if refreshed: fail_job(refreshed, error=str(exc), retryable=True) raise