feat(shipping-notice): 完善发货通知自动推进与多库存源复核闭环
This commit is contained in:
1 parent
cfa19a0b7b
commit
8e0bbf7a81
180 files changed
+31210
-1864
No files matched your search
@@ -15,9 +15,11 @@ from app.jobs.handlers import ( # noqa: F401
|
||||
shipping_notice_run,
|
||||
shipping_order_extraction,
|
||||
shipping_process_gate,
|
||||
shipping_auto_progress,
|
||||
shipping_stp_auto_create,
|
||||
shipping_line_auto_fulfill,
|
||||
shipping_post_ot_wave_progress,
|
||||
shipping_review_revalidate_progress,
|
||||
shipping_xfa_ocr_automark,
|
||||
wecom_directory_sync,
|
||||
)
|
||||
@@ -0,0 +1,26 @@
|
||||
"""
|
||||
jobs/handlers/shipping_auto_progress.py
|
||||
|
||||
用途:消费 P0-3 Task 级 AutoProgress Job。
|
||||
依赖:JobContext、auto_progress_controller。
|
||||
逻辑:Job 已由通用队列领取为 running;本 Handler 只委托正式控制器执行一个 Gate,不再调用旧全链路 facade。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.registry import register_handler
|
||||
from app.jobs.types import JobType
|
||||
from app.services.shipping_notice.auto_progress_controller import run_auto_progress_job
|
||||
|
||||
|
||||
@register_handler(JobType.SHIPPING_AUTO_PROGRESS)
|
||||
def run_shipping_auto_progress(ctx: JobContext, payload: dict) -> None:
|
||||
"""执行一个正式 Gate;payload 必须含队列注入的 job_id。"""
|
||||
raw_job_id = payload.get('job_id')
|
||||
if not raw_job_id:
|
||||
raise RuntimeError('missing_job_id_for_shipping_auto_progress')
|
||||
run_auto_progress_job(
|
||||
job_id=int(raw_job_id),
|
||||
worker_id=str(ctx.extras.get('worker_label') or f'shipping-auto-progress-{raw_job_id}'),
|
||||
)
|
||||
@@ -0,0 +1,300 @@
|
||||
"""
|
||||
backend/app/jobs/handlers/shipping_review_revalidate_progress.py
|
||||
|
||||
用途:消费 Review Revalidate Job,在 Case 字段变更后异步刷新校验、
|
||||
重跑 STP 资格判定、推进自动入队协调。
|
||||
依赖:JobContext、order_review_auto_progress_coordinator.reconcile_single_case_for_auto_progress、
|
||||
jobs.queue finish/fail、recovery_contract.is_tech_retryable_error。
|
||||
逻辑:由 shipping worker 领取;按 business_ref(case_no)+ 部分唯一索引保证同 Case 不重复入队;
|
||||
成功 finish 写 result_json(包含 enqueue_status / customer_step_status / validate_status);
|
||||
失败统一走错误分类:
|
||||
- AppError.is_tech_retryable_error 命中 → fail_job(retryable=True)
|
||||
- 其它 AppError 业务阻断 → fail_job(retryable=False)
|
||||
- 非预期 Exception → category_hint=temporary_storage_error,默认 retryable=True
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import AppError
|
||||
from app.extensions import db
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.queue import fail_job, finish_job
|
||||
from app.jobs.registry import register_handler
|
||||
from app.jobs.types import JobType
|
||||
from app.models import Job
|
||||
from app.services.shipping_notice.recovery_contract import is_tech_retryable_error
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
_SUCCESS_ENQUEUE_STATUSES: frozenset[str] = frozenset({
|
||||
'queued',
|
||||
'already_queued',
|
||||
'already_running',
|
||||
'reused',
|
||||
'enqueued',
|
||||
'already_confirmed_or_terminal',
|
||||
})
|
||||
|
||||
|
||||
def _classify_revalidate_error(
|
||||
*,
|
||||
error_code: str,
|
||||
message: str,
|
||||
category_hint: str | None = None,
|
||||
) -> tuple[bool, dict[str, Any]]:
|
||||
"""
|
||||
将 Revalidate Job 执行失败按 recovery_contract 统一分类,输出 retryable、合并后的 result。
|
||||
|
||||
【AI 触发时机】:Handler 的两条 fail 路径(AppError 兜底、非预期 Exception 兜底)
|
||||
统一调用,确保 Job.result_json schema 一致。
|
||||
|
||||
核心逻辑(fail-closed):
|
||||
[STEP 1] is_tech_retryable_error(error_code, category_hint) 命中白名单或前缀
|
||||
→ result.status=failed_transient,retryable=True。
|
||||
[STEP 2] 否则 result.status=blocked_manual,retryable=False。
|
||||
[STEP 3] 返回二元组(retryable, normalized_result_dict)。
|
||||
|
||||
Args:
|
||||
error_code: 业务错误码(SHIPPING.* 或顶层 reason_code)。
|
||||
message: 人类可读描述。
|
||||
category_hint: 可选;调用方已知的技术分类(temporary_storage_error 等)。
|
||||
|
||||
Returns:
|
||||
(retryable: bool, normalized_result: dict)。
|
||||
"""
|
||||
tech = is_tech_retryable_error(error_code, category_hint=category_hint)
|
||||
result_status = 'failed_transient' if tech else 'blocked_manual'
|
||||
normalized: dict[str, Any] = {
|
||||
'contract_version': 'shipping-recovery-v1-phase1',
|
||||
'status': result_status,
|
||||
'error_code': str(error_code or ''),
|
||||
'message': str(message or ''),
|
||||
'retryable': bool(tech),
|
||||
'decision_trace': {
|
||||
'contract_version': 'shipping-recovery-v1-phase1',
|
||||
'stage': 'revalidate_classify_error',
|
||||
'retryable': bool(tech),
|
||||
'matched_rule': 'tech_retryable_whitelist' if tech else 'business_blocking_default',
|
||||
'category_hint': category_hint,
|
||||
},
|
||||
}
|
||||
return bool(tech), normalized
|
||||
|
||||
|
||||
@register_handler(JobType.SHIPPING_REVIEW_REVALIDATE_PROGRESS)
|
||||
def handle_shipping_review_revalidate_progress(ctx: JobContext, payload: dict) -> None:
|
||||
"""
|
||||
执行 Review Revalidate Job(字段变更后异步协调)。
|
||||
|
||||
核心逻辑:
|
||||
[STEP 0] 读取 Job 记录,冻结 payload,解析 case_no / draft_version / operation_id。
|
||||
[STEP 1] 加行锁加载 Case,Case 不存在或已终态 → finish_job(status='skipped')。
|
||||
[STEP 2] Draft 版本冲突检测:冻结版本与 Case.current_draft 不一致 →
|
||||
result.draft_version_superseded,finish_job(status='skipped')。
|
||||
[STEP 3] 调用 reconcile_single_case_for_auto_progress(case, trigger='review_revalidate_job', refresh_validation=True)。
|
||||
[STEP 4] 按 enqueue_status / customer_step_status / validate_status 分类:
|
||||
- 全部成功 → finish_job,写 result_json。
|
||||
[STEP 5] AppError:is_tech_retryable_error 命中 → fail_job(retryable=True),否则 retryable=False。
|
||||
[STEP 6] 非预期 Exception:category_hint=temporary_storage_error,retryable=True,最终 re-raise 保持 Worker 心跳。
|
||||
|
||||
Args:
|
||||
ctx: Worker 上下文;当前执行体不依赖请求上下文。
|
||||
payload: Worker 载荷,必须含 job_id;业务字段以 Job.payload_json 为准。
|
||||
|
||||
Returns:
|
||||
None。
|
||||
"""
|
||||
_ = ctx
|
||||
raw_job_id = payload.get('job_id') if isinstance(payload, dict) else None
|
||||
job = db.session.get(Job, int(raw_job_id)) if raw_job_id else None
|
||||
if job is None:
|
||||
raise RuntimeError('missing_review_revalidate_job_id')
|
||||
|
||||
job_id = int(job.id)
|
||||
owned_attempt = int(job.attempts or 0)
|
||||
frozen = dict(job.payload_json or {})
|
||||
frozen.setdefault('job_id', job_id)
|
||||
try:
|
||||
case_no = str(frozen.get('case_no') or '').strip() or None
|
||||
draft_version_raw = frozen.get('draft_version')
|
||||
draft_version = int(draft_version_raw) if draft_version_raw is not None else None
|
||||
operation_id = frozen.get('operation_id')
|
||||
if operation_id is not None:
|
||||
operation_id = str(operation_id).strip() or None
|
||||
if not case_no:
|
||||
fail_job(
|
||||
job_id,
|
||||
error='missing_case_no_in_payload',
|
||||
result={
|
||||
'status': 'payload_invalid',
|
||||
'error_code': 'SHIPPING.REVALIDATE_MISSING_CASE_NO',
|
||||
'message': 'payload 缺少 case_no',
|
||||
'retryable': False,
|
||||
},
|
||||
retryable=False,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
|
||||
from app.models.shipping_order_review import ShippingOrderReviewCase
|
||||
|
||||
case = (
|
||||
ShippingOrderReviewCase.query
|
||||
.filter_by(case_no=case_no)
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
TERMINAL_CASE_STATUSES = frozenset({
|
||||
'confirmed',
|
||||
'non_order',
|
||||
'quality_issue',
|
||||
'superseded',
|
||||
})
|
||||
if case is None or case.status in TERMINAL_CASE_STATUSES:
|
||||
finish_job(
|
||||
job_id,
|
||||
result={
|
||||
'status': 'skipped',
|
||||
'reason': 'case_not_found_or_terminal',
|
||||
'case_no': case_no,
|
||||
'case_status': case.status if case is not None else None,
|
||||
'operation_id': operation_id,
|
||||
},
|
||||
message='Case 不存在或已终态,跳过 Review Revalidate',
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
|
||||
if case.current_draft is None or (
|
||||
draft_version is not None
|
||||
and int(case.current_draft.draft_version) != int(draft_version)
|
||||
):
|
||||
current_draft_version = (
|
||||
int(case.current_draft.draft_version)
|
||||
if case.current_draft is not None
|
||||
else None
|
||||
)
|
||||
finish_job(
|
||||
job_id,
|
||||
result={
|
||||
'status': 'draft_version_superseded',
|
||||
'reason': 'newer_draft_version_exists',
|
||||
'frozen_draft_version': draft_version,
|
||||
'current_draft_version': current_draft_version,
|
||||
'case_no': case_no,
|
||||
'operation_id': operation_id,
|
||||
},
|
||||
message='Draft 版本已被更新,新版本将有自己的 Revalidate Job',
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
|
||||
from app.services.shipping_notice.order_review_auto_progress_coordinator import (
|
||||
reconcile_single_case_for_auto_progress,
|
||||
)
|
||||
|
||||
result = reconcile_single_case_for_auto_progress(
|
||||
case=case,
|
||||
trigger='review_revalidate_job',
|
||||
refresh_validation=True,
|
||||
)
|
||||
|
||||
enqueue_status = str(result.get('enqueue_status') or '').strip() or None
|
||||
step_status = str(result.get('customer_step_status') or '').strip() or None
|
||||
validate_status = str(result.get('validate_status') or '').strip() or None
|
||||
all_ok = (
|
||||
enqueue_status in _SUCCESS_ENQUEUE_STATUSES
|
||||
or enqueue_status == 'skipped'
|
||||
or enqueue_status == 'not_scheduled'
|
||||
)
|
||||
extra: dict[str, Any] = {
|
||||
'contract_version': 'shipping-recovery-v1-phase1',
|
||||
'status': 'ok' if all_ok else 'partial_or_failed',
|
||||
'enqueue_status': enqueue_status,
|
||||
'customer_step_status': step_status,
|
||||
'validate_status': validate_status,
|
||||
'case_no': case_no,
|
||||
'draft_version': draft_version,
|
||||
'operation_id': operation_id,
|
||||
}
|
||||
if isinstance(result, dict):
|
||||
for pass_key in {
|
||||
'task_no',
|
||||
'stp_job_id',
|
||||
'auto_progress_job_id',
|
||||
'validation_summary',
|
||||
'can_auto_create',
|
||||
'can_build',
|
||||
}:
|
||||
if pass_key in result:
|
||||
extra[pass_key] = result[pass_key]
|
||||
finish_job(
|
||||
job_id,
|
||||
result={**dict(result or {}), **extra},
|
||||
message=str(
|
||||
result.get('message')
|
||||
or (
|
||||
f'Review Revalidate 协调完成(enqueue={enqueue_status}, validate={validate_status}'
|
||||
)
|
||||
)[:2000],
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
except AppError as exc:
|
||||
raw_code = str(getattr(exc, 'code', '') or 'SHIPPING.REVALIDATE_APP_ERROR')
|
||||
raw_message = str(getattr(exc, 'message', str(exc) or '') or 'Revalidate 执行失败')[:1500]
|
||||
details: dict[str, Any] = {
|
||||
'case_no': str(frozen.get('case_no') or ''),
|
||||
'draft_version': frozen.get('draft_version'),
|
||||
'operation_id': frozen.get('operation_id'),
|
||||
'error_details': dict(getattr(exc, 'details', None) or {}),
|
||||
}
|
||||
retryable, normalized = _classify_revalidate_error(
|
||||
error_code=raw_code,
|
||||
message=raw_message,
|
||||
)
|
||||
if details:
|
||||
normalized['blocking_reason_details'] = {
|
||||
**dict(normalized.get('blocking_reason_details') or {}),
|
||||
**details,
|
||||
}
|
||||
fail_job(
|
||||
job_id,
|
||||
error=str(normalized.get('message') or raw_message)[:2000],
|
||||
result=normalized,
|
||||
retryable=retryable,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
except Exception as exc: # noqa: BLE001
|
||||
raw_message = str(exc)[:1500]
|
||||
raw_code = 'SHIPPING.REVALIDATE_UNEXPECTED'
|
||||
details = {
|
||||
'exception_type': type(exc).__name__,
|
||||
'case_no': str(frozen.get('case_no') or ''),
|
||||
'draft_version': frozen.get('draft_version'),
|
||||
'operation_id': frozen.get('operation_id'),
|
||||
}
|
||||
category_hint = 'temporary_storage_error'
|
||||
retryable, normalized = _classify_revalidate_error(
|
||||
error_code=raw_code,
|
||||
message=raw_message,
|
||||
category_hint=category_hint,
|
||||
)
|
||||
if details:
|
||||
normalized['blocking_reason_details'] = {
|
||||
**dict(normalized.get('blocking_reason_details') or {}),
|
||||
**details,
|
||||
}
|
||||
fail_job(
|
||||
job_id,
|
||||
error=str(normalized.get('message') or raw_message)[:2000],
|
||||
result=normalized,
|
||||
retryable=retryable,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
raise
|
||||
@@ -1,15 +1,25 @@
|
||||
"""
|
||||
backend/app/jobs/handlers/shipping_stp_auto_create.py
|
||||
|
||||
用途:消费 STP 自动建单 Job,执行 confirm_review_case 与确认后自动推进入队。
|
||||
用途:消费 STP 自动建单 Job,执行 confirm_review_case 与确认后自动推进入队;
|
||||
按 recovery_contract 统一错误分类,业务阻断(如 NOTICE_EXACT_DUPLICATE)
|
||||
retryable=false + blocked_manual,技术失败白名单 retryable=true。
|
||||
依赖:JobContext、order_stp_auto_create_service.execute_stp_auto_create_job、
|
||||
jobs.queue finish/fail。
|
||||
jobs.queue finish/fail、recovery_contract(is_tech_retryable_error、
|
||||
build_stp_job_blocked_manual_result / build_stp_job_failed_transient_result、
|
||||
derive_blocking_next_actions)、fulfillment_audit.emit_stp_auto_create_blocked_manual_audit。
|
||||
逻辑:由 shipping worker 领取;幂等键保证同一 Case/draft 不重复建单;
|
||||
失败标记 Job failed,供 Projection 显示 retryable。
|
||||
成功 finish,附加 task_no / idempotent_replay;
|
||||
失败统一走 _classify_stp_result:
|
||||
- 技术白名单 → retryable=true(failed_transient)
|
||||
- 业务阻断 → retryable=false(blocked_manual + 注入 next_action + 写阻断审计)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from app.extensions import db
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.queue import fail_job, finish_job
|
||||
@@ -19,6 +29,128 @@ from app.models import Job
|
||||
from app.services.shipping_notice.order_stp_auto_create_service import (
|
||||
execute_stp_auto_create_job,
|
||||
)
|
||||
from app.services.shipping_notice.recovery_contract import (
|
||||
build_stp_job_blocked_manual_result,
|
||||
build_stp_job_failed_transient_result,
|
||||
derive_blocking_next_actions,
|
||||
is_tech_retryable_error,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _classify_stp_job_result(
|
||||
*,
|
||||
error_code: str,
|
||||
message: str,
|
||||
details: dict[str, Any] | None = None,
|
||||
category_hint: str | None = None,
|
||||
) -> tuple[bool, dict[str, Any], str | None]:
|
||||
"""
|
||||
将 STP 执行失败按 recovery_contract 统一分类,输出 retryable、合并后的 result、next_action。
|
||||
|
||||
【AI 触发时机】:Handler 的三条 fail 路径(业务拒绝 ok=False、AppError 兜底、
|
||||
非预期 Exception 兜底)统一调用,确保 Job.result_json schema 一致。
|
||||
|
||||
核心逻辑(fail-closed):
|
||||
[STEP 1] is_tech_retryable_error(error_code, category_hint) 命中白名单或前缀
|
||||
→ build_stp_job_failed_transient_result,retryable=True。
|
||||
[STEP 2] 否则 build_stp_job_blocked_manual_result:
|
||||
derive_blocking_next_actions 取第一个动作作 next_action,默认 open_order_review;
|
||||
details 合并至 blocking_reason_details。
|
||||
[STEP 3] 返回三元组(retryable, normalized_result_dict, next_action)。
|
||||
|
||||
Args:
|
||||
error_code: 业务错误码(SHIPPING.* 或顶层 reason_code)。
|
||||
message: 人类可读描述。
|
||||
details: 业务上下文(case_no、existing_task_no、idempotency_key 等),
|
||||
合并至 blocking_reason_details。
|
||||
category_hint: 可选;调用方已知的技术分类(worker_timeout 等)。
|
||||
|
||||
Returns:
|
||||
(retryable: bool, normalized_result: dict, next_action: str | None)。
|
||||
"""
|
||||
tech = is_tech_retryable_error(error_code, category_hint=category_hint)
|
||||
if tech:
|
||||
transient: dict[str, Any] = build_stp_job_failed_transient_result(
|
||||
error_code=error_code,
|
||||
message=message,
|
||||
category_hint=category_hint,
|
||||
)
|
||||
if details:
|
||||
transient['blocking_reason_details'] = {
|
||||
**dict(transient.get('blocking_reason_details') or {}),
|
||||
**dict(details),
|
||||
}
|
||||
return True, transient, transient.get('next_action')
|
||||
|
||||
actions = derive_blocking_next_actions(blocking_reason=error_code)
|
||||
next_action = actions[0] if actions else 'open_order_review'
|
||||
blocked: dict[str, Any] = build_stp_job_blocked_manual_result(
|
||||
error_code=error_code,
|
||||
message=message,
|
||||
next_action=next_action,
|
||||
details=details,
|
||||
)
|
||||
return False, blocked, next_action
|
||||
|
||||
|
||||
def _emit_blocked_manual_audit_if_needed(
|
||||
*,
|
||||
job_id: int,
|
||||
retryable: bool,
|
||||
error_code: str,
|
||||
next_action: str | None,
|
||||
payload: dict[str, Any],
|
||||
details: dict[str, Any] | None,
|
||||
) -> None:
|
||||
"""
|
||||
Phase 1-5:业务阻断时写入 stp_auto_create_blocked_manual 顶层审计。
|
||||
审计失败只告警,不阻断 Job fail。
|
||||
"""
|
||||
if retryable:
|
||||
return
|
||||
if not error_code:
|
||||
return
|
||||
case_no = str(payload.get('case_no') or '').strip() or None
|
||||
try:
|
||||
from app.services.shipping_notice.fulfillment_audit import (
|
||||
emit_stp_auto_create_blocked_manual_audit,
|
||||
)
|
||||
from app.models import ShippingOrderReviewCase
|
||||
|
||||
case = None
|
||||
if case_no:
|
||||
case = (
|
||||
ShippingOrderReviewCase.query
|
||||
.filter_by(case_no=case_no)
|
||||
.order_by(ShippingOrderReviewCase.id.desc())
|
||||
.with_entities(ShippingOrderReviewCase)
|
||||
.first()
|
||||
)
|
||||
emit_stp_auto_create_blocked_manual_audit(
|
||||
case=case,
|
||||
job_id=int(job_id),
|
||||
error_code=str(error_code or ''),
|
||||
next_action=str(next_action or ''),
|
||||
details={
|
||||
'payload_case_no': case_no,
|
||||
**(dict(details) if details else {}),
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
except Exception: # noqa: BLE001
|
||||
logger.warning(
|
||||
'stp_blocked_manual_audit_failed|job_id=%s|case_no=%s|error_code=%s',
|
||||
int(job_id),
|
||||
case_no,
|
||||
str(error_code or ''),
|
||||
exc_info=True,
|
||||
)
|
||||
try:
|
||||
db.session.rollback()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
@register_handler(JobType.SHIPPING_STP_AUTO_CREATE)
|
||||
@@ -26,8 +158,14 @@ def handle_shipping_stp_auto_create(ctx: JobContext, payload: dict) -> None:
|
||||
"""
|
||||
执行 STP 自动建单 Job。
|
||||
|
||||
核心逻辑:按 Worker 传入的 job_id 读取冻结 payload 与执行代次;委托
|
||||
execute_stp_auto_create_job;成功 finish,业务拒绝/异常按当前代次 fail。
|
||||
核心逻辑:
|
||||
[STEP 1] 按 job_id 读取冻结 payload 与执行代次(owned_attempt)。
|
||||
[STEP 2] 委托 execute_stp_auto_create_job 执行业务确认。
|
||||
[STEP 3] 成功:finish_job,保留 task_no / idempotent_replay / contract_version。
|
||||
[STEP 4] 业务拒绝 ok=False:_classify_stp_job_result 分类 → 阻断审计 → fail_job。
|
||||
[STEP 5] AppError 兜底:同上分类 + 审计。
|
||||
[STEP 6] 非预期 Exception:category_hint=temporary_storage_error(fail-open 倾向重试),
|
||||
同上分类后 fail_job;最终 re-raise 保持 Worker 心跳。
|
||||
|
||||
Args:
|
||||
ctx: Worker 上下文;当前执行体不依赖请求上下文。
|
||||
@@ -49,26 +187,105 @@ def handle_shipping_stp_auto_create(ctx: JobContext, payload: dict) -> None:
|
||||
try:
|
||||
result = execute_stp_auto_create_job(payload=frozen, job_id=job_id)
|
||||
if result.get('ok'):
|
||||
extra: dict[str, Any] = {
|
||||
'contract_version': 'shipping-recovery-v1-phase1',
|
||||
'status': 'ok',
|
||||
}
|
||||
if result.get('task_no'):
|
||||
extra['task_no'] = str(result.get('task_no') or '')
|
||||
if result.get('idempotent_replay'):
|
||||
extra['idempotent_replay'] = True
|
||||
if result.get('auto_progress_status'):
|
||||
extra['auto_progress_status'] = str(result.get('auto_progress_status') or '')
|
||||
finish_job(
|
||||
job_id,
|
||||
result=result,
|
||||
result={**dict(result), **extra},
|
||||
message=str(result.get('message') or 'STP 自动建单完成'),
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
|
||||
message = str(
|
||||
result.get('message')
|
||||
or result.get('error')
|
||||
or result.get('error_code')
|
||||
or 'STP 自动建单失败'
|
||||
) or 'STP 自动建单失败'
|
||||
error_code = str(
|
||||
result.get('error_code')
|
||||
or result.get('code')
|
||||
or 'SHIPPING.STP_AUTO_CREATE_FAILED'
|
||||
) or 'SHIPPING.STP_AUTO_CREATE_FAILED'
|
||||
details: dict[str, Any] = {
|
||||
k: v for k, v in result.items() if k in {
|
||||
'task_no',
|
||||
'existing_task_no',
|
||||
'existing_notice_no',
|
||||
'source_content_hash',
|
||||
'duplicate_of',
|
||||
'confirmation_mode',
|
||||
'reused_task_id',
|
||||
'reused_notice_id',
|
||||
'idempotency_key',
|
||||
'case_no',
|
||||
'run_no',
|
||||
'details',
|
||||
}
|
||||
}
|
||||
details.setdefault('payload_case_no', str(frozen.get('case_no') or ''))
|
||||
details.setdefault('payload_run_no', str(frozen.get('run_no') or ''))
|
||||
retryable, normalized, next_action = _classify_stp_job_result(
|
||||
error_code=error_code,
|
||||
message=message,
|
||||
details=details,
|
||||
)
|
||||
_emit_blocked_manual_audit_if_needed(
|
||||
job_id=job_id,
|
||||
retryable=retryable,
|
||||
error_code=error_code,
|
||||
next_action=next_action,
|
||||
payload=frozen,
|
||||
details=details,
|
||||
)
|
||||
fail_job(
|
||||
job_id,
|
||||
error=str(result.get('message') or result.get('error_code') or 'STP 自动建单失败'),
|
||||
result=result,
|
||||
retryable=True,
|
||||
error=str(normalized.get('message') or message)[:2000],
|
||||
result=normalized,
|
||||
retryable=retryable,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
except Exception as exc: # noqa: BLE001
|
||||
raw_message = str(exc)[:1500]
|
||||
raw_code = 'SHIPPING.STP_AUTO_CREATE_UNEXPECTED'
|
||||
details = {
|
||||
'exception_type': type(exc).__name__,
|
||||
'payload_case_no': str(frozen.get('case_no') or ''),
|
||||
'payload_run_no': str(frozen.get('run_no') or ''),
|
||||
}
|
||||
# [PARAM_TUNING] 非预期异常默认归类为临时存储/基础设施失败,
|
||||
# 倾向可重试;若是业务阻断性异常(如 IntegrityError 唯一冲突),
|
||||
# 真实错误码已在业务层捕获并走 ok=False 路径,不会流入此兜底。
|
||||
category_hint = 'temporary_storage_error'
|
||||
retryable, normalized, next_action = _classify_stp_job_result(
|
||||
error_code=raw_code,
|
||||
message=raw_message,
|
||||
details=details,
|
||||
category_hint=category_hint,
|
||||
)
|
||||
_emit_blocked_manual_audit_if_needed(
|
||||
job_id=job_id,
|
||||
retryable=retryable,
|
||||
error_code=raw_code,
|
||||
next_action=next_action,
|
||||
payload=frozen,
|
||||
details=details,
|
||||
)
|
||||
fail_job(
|
||||
job_id,
|
||||
error=str(exc)[:500],
|
||||
result={'status': 'failed', 'error_code': 'SHIPPING.STP_AUTO_CREATE_FAILED'},
|
||||
retryable=True,
|
||||
error=str(normalized.get('message') or raw_message)[:2000],
|
||||
result=normalized,
|
||||
retryable=retryable,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
raise
|
||||
@@ -387,6 +387,11 @@ def enqueue(
|
||||
commit: bool = True,
|
||||
correlation_id: str | None = None,
|
||||
scheduled_at: Any = None,
|
||||
task_id: int | None = None,
|
||||
execution_id: int | None = None,
|
||||
gate_id: int | None = None,
|
||||
candidate_set_id: int | None = None,
|
||||
fencing_token: str | None = None,
|
||||
) -> int:
|
||||
"""
|
||||
将任务写入通用 jobs 队列并返回 job id。
|
||||
@@ -411,6 +416,9 @@ def enqueue(
|
||||
commit: False 时仅 flush,由调用方与业务行同一事务提交。
|
||||
correlation_id: 兼容旧接口;business_ref 为空时作为业务锚点。
|
||||
scheduled_at: 未来时间则延迟到该时间后才可被 worker 领取。
|
||||
task_id / execution_id / gate_id / candidate_set_id: 正式业务作用域;AutoProgress
|
||||
使用这些列实施 Task 级活动唯一与版本围栏。
|
||||
fencing_token: Worker 领取前写入的代次围栏;迟到副作用必须比对。
|
||||
"""
|
||||
normalized_type = _normalize_job_type(job_type)
|
||||
if normalized_type in {JobType.KB_CLEAN.value, JobType.KB_DIFY_SYNC.value}:
|
||||
@@ -464,6 +472,11 @@ def enqueue(
|
||||
attempts=0,
|
||||
max_attempts=max(1, int(max_attempts or 1)),
|
||||
created_by_id=created_by_id,
|
||||
task_id=task_id,
|
||||
execution_id=execution_id,
|
||||
gate_id=gate_id,
|
||||
candidate_set_id=candidate_set_id,
|
||||
fencing_token=fencing_token,
|
||||
created_at=queue_at,
|
||||
updated_at=now,
|
||||
)
|
||||
|
||||
@@ -7,7 +7,7 @@ backend/app/jobs/runner.py
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import TYPE_CHECKING
|
||||
from typing import TYPE_CHECKING, Callable
|
||||
|
||||
from app.jobs import store
|
||||
from app.jobs.registry import get_handler
|
||||
@@ -24,21 +24,49 @@ def _resolve_poll_seconds(ctx: JobContext) -> float:
|
||||
return float(ctx.config.get('KB_WORKER_POLL_SECONDS', 2))
|
||||
|
||||
|
||||
def run_forever(ctx: JobContext, *, poll_interval_seconds: float | None = None) -> None:
|
||||
def run_forever(
|
||||
ctx: JobContext,
|
||||
*,
|
||||
poll_interval_seconds: float | None = None,
|
||||
recovery_callback: Callable[[], int] | None = None,
|
||||
recovery_interval_seconds: float = 60.0,
|
||||
) -> None:
|
||||
"""
|
||||
持续轮询并执行任务。
|
||||
核心逻辑:claim_next → get_handler → handler(ctx, payload);异常时 mark_failed。
|
||||
支持 recovery_callback:启动立即执行一次,空闲睡眠和 claim 后检查 tick。
|
||||
Args:
|
||||
ctx: Worker 上下文(extras.queues 指定消费队列)。
|
||||
poll_interval_seconds: 无任务时的休眠秒数;默认按队列读 config。
|
||||
recovery_callback: 恢复回调函数,返回本轮处理计数;默认 None 关闭。
|
||||
recovery_interval_seconds: 两次 recovery tick 的最小间隔秒数;默认 60。
|
||||
"""
|
||||
queues = ctx.extras.get('queues') or ['kb']
|
||||
poll = poll_interval_seconds if poll_interval_seconds is not None else _resolve_poll_seconds(ctx)
|
||||
ctx.logger.info('Job runner started queues=%s poll_seconds=%s', queues, poll)
|
||||
ctx.logger.info('Job runner started queues=%s poll_seconds=%s recovery=%s',
|
||||
queues, poll, recovery_callback is not None)
|
||||
|
||||
if recovery_callback is not None:
|
||||
try:
|
||||
recovery_callback()
|
||||
except Exception:
|
||||
ctx.logger.exception('Recovery callback failed on BOOT')
|
||||
finally:
|
||||
last_recovery_ts = time.monotonic()
|
||||
else:
|
||||
last_recovery_ts = time.monotonic()
|
||||
|
||||
while True:
|
||||
job = store.claim_next(queues=queues)
|
||||
if not job:
|
||||
current_ts = time.monotonic()
|
||||
if recovery_callback is not None and (current_ts - last_recovery_ts) >= recovery_interval_seconds:
|
||||
try:
|
||||
recovery_callback()
|
||||
except Exception:
|
||||
ctx.logger.exception('Recovery callback failed during idle poll')
|
||||
finally:
|
||||
last_recovery_ts = current_ts
|
||||
time.sleep(poll)
|
||||
continue
|
||||
|
||||
@@ -52,6 +80,15 @@ def run_forever(ctx: JobContext, *, poll_interval_seconds: float | None = None)
|
||||
message=f'no handler for {job.get("job_type")}',
|
||||
owned_attempt=owned_attempt_int,
|
||||
)
|
||||
if recovery_callback is not None:
|
||||
current_ts = time.monotonic()
|
||||
if (current_ts - last_recovery_ts) >= recovery_interval_seconds:
|
||||
try:
|
||||
recovery_callback()
|
||||
except Exception:
|
||||
ctx.logger.exception('Recovery callback failed after no-handler job')
|
||||
finally:
|
||||
last_recovery_ts = current_ts
|
||||
continue
|
||||
|
||||
try:
|
||||
@@ -63,3 +100,13 @@ def run_forever(ctx: JobContext, *, poll_interval_seconds: float | None = None)
|
||||
message=str(exc),
|
||||
owned_attempt=owned_attempt_int,
|
||||
)
|
||||
finally:
|
||||
if recovery_callback is not None:
|
||||
current_ts = time.monotonic()
|
||||
if (current_ts - last_recovery_ts) >= recovery_interval_seconds:
|
||||
try:
|
||||
recovery_callback()
|
||||
except Exception:
|
||||
ctx.logger.exception('Recovery callback failed after job execution')
|
||||
finally:
|
||||
last_recovery_ts = current_ts
|
||||
@@ -20,6 +20,8 @@ class JobType(StrEnum):
|
||||
SHIPPING_ORDER_EXTRACTION = 'shipping_order_extraction'
|
||||
SHIPPING_DOCUMENT_LAYOUT = 'shipping_document_layout'
|
||||
SHIPPING_PROCESS_GATE = 'shipping_process_gate'
|
||||
# Task 级正式决策器:一个 Job 只处理一个 ProcessGate。
|
||||
SHIPPING_AUTO_PROGRESS = 'shipping_auto_progress'
|
||||
# XFA 合成预览就绪后的 OCR 自动标记(Job.job_type 为字符串列,无需 DB enum 迁移)
|
||||
SHIPPING_XFA_OCR_AUTOMARK = 'shipping_xfa_ocr_automark'
|
||||
# 资格达标后的 STP 自动建单入队(先 queued,再由 worker 执行 confirm)
|
||||
@@ -28,6 +30,8 @@ class JobType(StrEnum):
|
||||
SHIPPING_LINE_AUTO_FULFILL = 'shipping_line_auto_fulfill'
|
||||
# post-OT wave 专用 Excel/RPA 推进(禁止复用 confirm 后整单推进)
|
||||
SHIPPING_POST_OT_WAVE_PROGRESS = 'shipping_post_ot_wave_progress'
|
||||
# Case 字段变更后异步协调:刷新校验、重跑 STP 资格判定、推进自动入队
|
||||
SHIPPING_REVIEW_REVALIDATE_PROGRESS = 'shipping_review_revalidate_progress'
|
||||
SCHEDULE_RUN = 'schedule_run'
|
||||
FILE_CHECK_RUN = 'file_check_run'
|
||||
WECOM_DIRECTORY_SYNC = 'wecom_directory_sync'
|
||||
@@ -64,8 +68,9 @@ QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = {
|
||||
'shipping': frozenset({
|
||||
'shipping_notice_run', 'shipping_notice_parse', 'shipping_order_extraction',
|
||||
'shipping_document_layout', 'shipping_process_gate', 'shipping_xfa_ocr_automark',
|
||||
'shipping_auto_progress',
|
||||
'shipping_stp_auto_create', 'shipping_line_auto_fulfill',
|
||||
'shipping_post_ot_wave_progress',
|
||||
'shipping_post_ot_wave_progress', 'shipping_review_revalidate_progress',
|
||||
}),
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user