Files
syops/backend/app/jobs/queue.py
T
2026-06-29 20:05:13 +08:00

148 lines
5.0 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/jobs/queue.py
用途:任务入队 API(Wave 2:adapter 至 KbJob + 域内 enqueue 函数)。
逻辑:API / services 在创建 KbJob 后调用 enqueue;sync 模式仍由域内函数同步执行。
"""
from __future__ import annotations
from typing import Any
from app.core.errors import ValidationError
from app.jobs.types import JobType
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(
job_type: JobType,
payload: dict[str, Any],
*,
correlation_id: str | None = None,
scheduled_at: Any = None,
) -> int:
"""
将任务提交执行并返回 job id(Wave 2 要求 payload 含已持久化的 KbJob id 或发货参数)。
核心逻辑:KB/发货任务委托既有 queue_service;未创建 KbJob 的调用方须先写库再 enqueue。
Args:
job_type: 任务类型。
payload: 任务参数;KB 类须含 job_id,发货类须含 task_no。
correlation_id: 关联业务 id(预留,当前未写入 KbJob)。
scheduled_at: 延迟执行时间(预留)。
Returns:
KbJob 主键。
Raises:
ValidationError: 参数缺失或域 enqueue 失败。
"""
_ = correlation_id, scheduled_at # Wave 4 通用 Job 表再使用
if job_type in (JobType.KB_CLEAN, JobType.KB_DIFY_SYNC):
job_id = payload.get('job_id')
if not job_id:
raise ValidationError('enqueue KB job 须在 payload 中提供 job_id(先创建 KbJob)')
from app.services.knowledge_cleaning.queue_service import enqueue_kb_job
ok, msg = enqueue_kb_job(int(job_id))
if not ok:
raise ValidationError(f'KB job enqueue failed: {msg}')
return int(job_id)
if job_type == JobType.SHIPPING_NOTICE_RUN:
task_no = str(payload.get('task_no') or '').strip()
if not task_no:
raise ValidationError('enqueue shipping job 须在 payload 中提供 task_no')
from app.services.shipping_notice.queue_service import enqueue_shipping_notice_job
ok, msg = enqueue_shipping_notice_job(
task_no=task_no,
created_by_id=payload.get('created_by_id'),
batch_no=payload.get('batch_no'),
)
if not ok:
raise ValidationError(f'shipping job enqueue failed: {msg}')
# sync/worker/already_queued 均需按 task_no 精确回查,避免返回其他发货任务的 id。
if payload.get('job_id'):
return int(payload['job_id'])
job_id = _find_shipping_notice_job_id(task_no)
if job_id:
return job_id
raise ValidationError(f'shipping job enqueue ambiguous: {msg}')
raise ValidationError(f'JobType {job_type} enqueue not implemented in Wave 2')
def enqueue_kb_job(job_id: int) -> tuple[bool, str]:
"""
提交 KB 类 KbJob 执行(兼容旧 queue_service 签名)。
核心逻辑:委托 knowledge_cleaning.queue_service;返回域内 (ok, message) 供 API 写 queue_result。
Args:
job_id: 已持久化的 KbJob 主键。
Returns:
(是否成功, 队列结果说明,如 queued_for_worker / queued_manual)。
"""
from app.services.knowledge_cleaning.queue_service import enqueue_kb_job as _enqueue_kb_job
return _enqueue_kb_job(int(job_id))
def enqueue_clean_job(job_id: int) -> tuple[bool, str]:
"""
提交 clean/path_upload 类 KbJob(enqueue_kb_job 别名)。
Args:
job_id: KbJob 主键。
Returns:
同 enqueue_kb_job。
"""
return enqueue_kb_job(job_id)
def enqueue_shipping_notice_job(
*,
task_no: str,
created_by_id: int | None = None,
batch_no: str | None = None,
) -> tuple[bool, str]:
"""
持久化并提交单票发货后台任务。
Args:
task_no: 发货 task 编号。
created_by_id: 创建人 user id(可选)。
batch_no: 所属批次号(可选)。
Returns:
(是否成功, 结果说明)。
"""
from app.services.shipping_notice.queue_service import enqueue_shipping_notice_job as _enqueue_shipping
return _enqueue_shipping(
task_no=task_no,
created_by_id=created_by_id,
batch_no=batch_no,
)