Merge branch 'dev' into hugo-shipping-notice

This commit is contained in:
hugo committed 2026-08-11 14:33:56 +08:00
commit 472b530be3
397 files changed
+46450 -34171

No files matched your search

@@ -81,7 +81,10 @@ def _run_platform_job_in_process(task: ScheduleTask, run: ScheduleRun) -> Schedu
from app.services.schedule.job_registry import run_platform_job
key = normalize_platform_api_path(task.platform_api_path)
# [STEP 1] 合并而非覆盖:保留会话触发写入的 run_options 等字段
existing = run.api_request_json if isinstance(run.api_request_json, dict) else {}
payload = {
**existing,
"run_no": run.run_no,
"schedule_task_id": task.id,
"schedule_name": task.name,
@@ -0,0 +1,346 @@
"""
backend/app/services/schedule/queue_service.py
用途:把手动与 Cron 排程统一写入通用 Job 队列,并维护 ScheduleRun 业务状态。
依赖:models.ScheduleTask/ScheduleRun、jobs.queue、schedule timezone 与 RPA 收口服务。
逻辑:API 只创建 queued run;独立 schedule worker 扫描到期任务、领取 Job 后执行 scheduler_service。
"""
from __future__ import annotations
from datetime import datetime
from flask import current_app
from app import db
from app.jobs.queue import enqueue, fail_job, finish_job, recover_stale_jobs
from app.jobs.types import JobType
from app.models import Job, ScheduleRun, ScheduleTask
from app.services.schedule.shipping_inventory_rpa_finalize import (
recover_all_stale_awaiting_rpa_schedule_runs,
recover_stale_awaiting_rpa_schedule_runs,
)
from app.services.schedule.timezone_util import compute_next_run_at, utc_now_naive
_worker_initialized = False
def _active_run(task_id: int) -> ScheduleRun | None:
"""返回同一排程当前 queued/running 的运行记录,防止并发重复执行。"""
return (
db.session.query(ScheduleRun)
.filter(
ScheduleRun.schedule_task_id == int(task_id),
ScheduleRun.status.in_(("queued", "running")),
)
.order_by(ScheduleRun.id.asc())
.first()
)
def _advance_next_run(task: ScheduleTask) -> None:
"""Cron 触发入队后立即推进下次执行时间;无后续时间时停用任务。"""
if task.cron_expr:
task.next_run_at = compute_next_run_at(
task.cron_expr,
timezone_name=getattr(task, "schedule_timezone", None),
)
if task.next_run_at is None:
task.enabled = False
else:
task.next_run_at = None
def _create_queued_run(
task: ScheduleTask,
*,
trigger_type: str,
triggered_by_user_id: int | None,
) -> tuple[ScheduleRun, int]:
"""
在当前事务创建 ScheduleRun 与对应通用 Job。
Args:
task: 已由调用方锁定的排程任务。
trigger_type: `manual` 或 `cron`,禁止传入未知触发类型。
triggered_by_user_id: 手动触发用户 ID;Cron 为 None。
Returns:
`(ScheduleRun, job_id)`;调用方负责提交事务。
"""
normalized_trigger = str(trigger_type or "").strip().lower()
if normalized_trigger not in {"manual", "cron"}:
raise ValueError(f"unsupported schedule trigger_type={trigger_type!r}")
from app.services.schedule.scheduler_service import _generate_run_no
run = ScheduleRun(
run_no=_generate_run_no(),
schedule_task_id=task.id,
trigger_type=normalized_trigger,
triggered_by_user_id=triggered_by_user_id,
started_at=None,
status="queued",
)
db.session.add(run)
db.session.flush()
job_id = enqueue(
JobType.SCHEDULE_RUN,
{
"schedule_task_id": task.id,
"schedule_run_id": run.id,
"trigger_type": normalized_trigger,
"triggered_by_user_id": triggered_by_user_id,
},
domain="schedule",
business_ref=f"schedule_run:{run.id}",
created_by_id=triggered_by_user_id,
max_attempts=3,
message="排程等待后台执行",
dedupe_active=False,
commit=False,
)
return run, job_id
def enqueue_manual_schedule_run(
task_id: int,
*,
triggered_by_user_id: int | None,
) -> tuple[ScheduleRun, int, bool]:
"""
手动触发排程并写入 schedule 队列。
核心逻辑:锁定 ScheduleTask 后复检 queued/running;已有活动记录时直接返回,
否则同事务创建 ScheduleRun 与 Job,避免接口线程承担长耗时执行。
Returns:
`(run, job_id, created)`;created=False 表示已有活动 run。
"""
task = (
db.session.query(ScheduleTask)
.filter(ScheduleTask.id == int(task_id))
.with_for_update()
.first()
)
if task is None:
raise LookupError(f"schedule task {task_id} not found")
recover_stale_awaiting_rpa_schedule_runs(task)
active = _active_run(task.id)
if active is not None:
job = (
db.session.query(Job)
.filter(
Job.domain == "schedule",
Job.job_type == JobType.SCHEDULE_RUN.value,
Job.status.in_(("queued", "running")),
Job.business_ref == f"schedule_run:{active.id}",
)
.order_by(Job.id.asc())
.first()
)
return active, int(job.id) if job else 0, False
run, job_id = _create_queued_run(
task,
trigger_type="manual",
triggered_by_user_id=triggered_by_user_id,
)
db.session.commit()
return run, job_id, True
def enqueue_due_schedule_runs(*, limit: int = 5) -> int:
"""
扫描到期排程并入队,供独立 schedule worker 每轮轮询调用。
核心逻辑:`FOR UPDATE SKIP LOCKED` 保证多 worker 不会重复调度;同任务已有
queued/running 时保留原到期时间,待该 run 完成后立即补跑;无活动 run 时同事务
创建 run/job 并推进时间。
Returns:
本轮新建的 schedule Job 数量。
"""
now = utc_now_naive()
tasks = (
db.session.query(ScheduleTask)
.filter(
ScheduleTask.enabled.is_(True),
ScheduleTask.next_run_at.isnot(None),
ScheduleTask.next_run_at <= now,
)
.order_by(ScheduleTask.next_run_at.asc(), ScheduleTask.id.asc())
.limit(max(1, int(limit or 1)))
.with_for_update(skip_locked=True)
.all()
)
if not tasks:
db.session.rollback()
return 0
created = 0
for task in tasks:
if _active_run(task.id) is None:
_create_queued_run(task, trigger_type="cron", triggered_by_user_id=None)
_advance_next_run(task)
created += 1
db.session.commit()
return created
def _sync_run_after_stale_job(job: Job) -> None:
"""通用 Job 超时回收后同步 ScheduleRun,避免业务状态永久停留在 running。"""
payload = job.payload_json if isinstance(job.payload_json, dict) else {}
run_id = int(payload.get("schedule_run_id") or 0)
run = db.session.get(ScheduleRun, run_id) if run_id else None
if run is None or run.status not in {"queued", "running"}:
return
if job.status == "queued":
run.status = "queued"
run.started_at = None
run.error_message = "后台执行超时,等待重试"
elif job.status in {"failed", "dead", "cancelled"}:
run.status = "failed"
run.finished_at = datetime.utcnow()
run.error_message = job.error_message or "后台执行超时"
def prepare_schedule_queue() -> int:
"""
执行 schedule worker 的恢复维护、到期扫描和超时 Job 回收。
Returns:
本轮新入队的到期排程数量。
"""
global _worker_initialized
timeout_seconds = float(current_app.config.get("SCHEDULE_JOB_RUNNING_TIMEOUT_SECONDS", 7200))
recover_stale_jobs(
domain="schedule",
timeout_seconds=timeout_seconds,
job_type=JobType.SCHEDULE_RUN,
on_recovered=_sync_run_after_stale_job,
)
if not _worker_initialized:
# [STEP 1] 兼容升级前由 Web 线程留下的 running 记录;无活动 Job 承接时标记中断。
from app.services.schedule.shipping_inventory_rpa_finalize import is_awaiting_rpa_schedule_run
legacy_running = db.session.query(ScheduleRun).filter(ScheduleRun.status == "running").all()
interrupted = 0
for run in legacy_running:
if is_awaiting_rpa_schedule_run(run):
continue
active_job = (
db.session.query(Job.id)
.filter(
Job.domain == "schedule",
Job.job_type == JobType.SCHEDULE_RUN.value,
Job.business_ref == f"schedule_run:{run.id}",
Job.status.in_(("queued", "running")),
)
.first()
)
if active_job is None:
run.status = "failed"
run.finished_at = datetime.utcnow()
run.error_message = "排程 worker 升级重启,旧执行已中断"
interrupted += 1
if interrupted:
db.session.commit()
current_app.logger.warning("[schedule-worker] closed %d legacy running schedule runs", interrupted)
# [STEP 2] 恢复等待 RPA 的运行与回调清理任务。
recovered = recover_all_stale_awaiting_rpa_schedule_runs()
if recovered:
current_app.logger.info("[schedule-worker] recovered %d stale awaiting RPA runs", recovered)
from app.services.shipping_notice.inventory_rpa_callback_cleanup import (
recover_pending_rpa_callback_cleanup_jobs,
)
cleanup_count, cleanup_warnings = recover_pending_rpa_callback_cleanup_jobs()
if cleanup_count:
current_app.logger.info("[schedule-worker] processed %d RPA cleanup jobs", cleanup_count)
if cleanup_warnings:
current_app.logger.warning("[schedule-worker] RPA cleanup warnings: %s", "; ".join(cleanup_warnings[:5]))
_worker_initialized = True
try:
from app.services.shipping_notice.rpa_worker_heartbeat_alert import maybe_alert_rpa_worker_status
maybe_alert_rpa_worker_status(force=False)
except Exception as exc:
db.session.rollback()
current_app.logger.warning("[schedule-worker] RPA heartbeat alert check failed: %s", exc)
return enqueue_due_schedule_runs()
def execute_schedule_job(*, job_id: int, run_id: int, logger) -> ScheduleRun | None:
"""
执行已领取的排程 Job,并同步 Job 与 ScheduleRun 终态。
Args:
job_id: 通用 Job 主键。
run_id: ScheduleRun 主键。
logger: worker logger。
Returns:
已执行的 ScheduleRun;业务记录已被删除时返回 None 并将 Job 正常收口。
"""
run = db.session.get(ScheduleRun, int(run_id))
if run is None:
finish_job(job_id, result={"schedule_run_id": run_id, "status": "deleted"}, message="排程已删除")
return None
task = db.session.get(ScheduleTask, run.schedule_task_id)
if task is None:
finish_job(job_id, result={"schedule_run_id": run_id, "status": "task_deleted"}, message="排程已删除")
return None
if run.status in {"success", "failed", "partial_failed"}:
finish_job(
job_id,
result={"schedule_run_id": run.id, "status": run.status},
message="排程已处于终态",
)
return run
from app.services.schedule.scheduler_service import run_task_now
try:
run.status = "running"
run.started_at = run.started_at or datetime.utcnow()
run.error_message = None
db.session.commit()
result_run = run_task_now(
task,
trigger_type=run.trigger_type,
triggered_by_user_id=run.triggered_by_user_id,
run=run,
)
finish_job(
job_id,
result={"schedule_run_id": result_run.id, "status": result_run.status},
message="排程执行完成",
)
return result_run
except Exception as exc:
db.session.rollback()
job = db.session.get(Job, int(job_id))
run = db.session.get(ScheduleRun, int(run_id))
retrying = bool(job and int(job.attempts or 0) < int(job.max_attempts or 1))
if run and run.status in {"queued", "running"} and not (
run.status == "running" and isinstance(run.response_summary_json, dict) and run.response_summary_json.get("awaiting_rpa")
):
run.status = "queued" if retrying else "failed"
run.started_at = None if retrying else run.started_at
run.finished_at = None if retrying else datetime.utcnow()
run.error_message = str(exc)[:1000]
db.session.commit()
owned_attempt = int(job.attempts or 0) if job is not None else None
fail_job(
job_id,
error=str(exc),
retryable=True,
owned_attempt=owned_attempt,
)
logger.exception("schedule run failed run_id=%s job_id=%s", run_id, job_id)
return run
@@ -1,15 +1,14 @@
"""
backend/app/services/schedule/scheduler_service.py
用途:排程任务生命周期(创建/更新/立即执行)与后台调度 worker。
用途:排程任务生命周期(创建/更新)与单次运行执行器。
依赖:schedule_contract、job_params、cron_util、timezone_util、excel_service、wecom_notify、kb_sync。
逻辑:api/schedule/tasks.py 与 import_service 调用 create_task/update_task/enable_task;
job_params 在本层经 normalize_job_params_for_contract 唯一归一化(含切换 platform_api_path
未传参时重置默认值);run_task_now 经 resolve_schedule_executor 分发 handler。
未传参时重置默认值);schedule worker 调用 run_task_now 并经 resolve_schedule_executor 分发 handler。
"""
from __future__ import annotations
import threading
import time
import uuid
from datetime import datetime
@@ -26,33 +25,54 @@ from app.services.schedule import resolve_schedule_executor, resolve_schedule_he
from app.services.schedule.shipping_inventory_rpa_finalize import (
apply_deferred_schedule_run_state,
is_awaiting_rpa_schedule_run,
recover_all_stale_awaiting_rpa_schedule_runs,
recover_stale_awaiting_rpa_schedule_runs,
should_defer_schedule_run_finalization,
)
from app.services.schedule.job_params import normalize_job_params_for_contract
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id
from app.services.schedule.timezone_util import compute_next_run_at, normalize_schedule_timezone, utc_now_naive
_worker_started = False
_worker_lock = threading.Lock()
_cancelled_runs: set[int] = set()
_cancel_lock = threading.Lock()
from app.services.schedule.timezone_util import compute_next_run_at, normalize_schedule_timezone
def request_cancel_run(run_id: int) -> None:
with _cancel_lock:
_cancelled_runs.add(run_id)
"""
持久化取消指定排程运行,供 Web 与独立 worker 跨进程协作。
核心逻辑:将对应 queued/running 通用 Job 标记为 cancelled;执行器通过
ScheduleRun 状态/存在性复检停止可中断的长循环。
"""
from app.jobs.types import JobType
from app.models import Job
now = datetime.utcnow()
jobs = (
db.session.query(Job)
.filter(
Job.domain == "schedule",
Job.job_type == JobType.SCHEDULE_RUN.value,
Job.business_ref == f"schedule_run:{int(run_id)}",
Job.status.in_(("queued", "running")),
)
.all()
)
for job in jobs:
job.status = "cancelled"
job.message = "排程已取消"
job.error_message = "排程已删除,执行中断"
job.locked_by = None
job.locked_at = None
job.finished_at = now
job.updated_at = now
def is_run_cancelled(run_id: int) -> bool:
with _cancel_lock:
return run_id in _cancelled_runs
"""通过数据库业务状态判断运行是否已被跨进程取消或删除。"""
run = db.session.get(ScheduleRun, int(run_id))
return run is None or str(run.status or "") not in {"queued", "running"}
def clear_cancelled_run(run_id: int) -> None:
with _cancel_lock:
_cancelled_runs.discard(run_id)
"""兼容旧调用;取消状态已持久化,无需清理进程内内存。"""
return None
def _generate_schedule_no() -> str:
@@ -122,6 +142,11 @@ def _build_schedule_run_wecom_description(run: ScheduleRun) -> str:
def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
"""
排程完成后的通用企微通知。
核心逻辑:若 response_summary_json.domain_notification_managed=true(如立账凭证检核),
则跳过以免与领域缺件/失败告警重复。
"""
from app.services.wecom_notify import (
upload_wecom_temp_media,
send_wecom_file_message,
@@ -131,6 +156,12 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
_get_enabled_events,
)
# 领域自行管理通知时跳过通用完成通知,避免重复刷屏
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if summary.get('domain_notification_managed'):
run.wecom_notify_error = 'domain_notification_managed'
return
if not current_app.config.get('WECOM_NOTIFY_ENABLED', True):
run.wecom_notify_error = 'WECOM_NOTIFY_ENABLED=false'
return
@@ -610,129 +641,3 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
current_app.logger.error("[schedule-run] wecom notify failed: %s", wecom_exc)
return run
def start_scheduler(app):
global _worker_started
with _worker_lock:
if _worker_started:
return
_worker_started = True
if not bool(app.config.get("SCHEDULE_WORKER_ENABLED", True)):
return
import os
if os.environ.get('WERKZEUG_RUN_MAIN') == 'true' or not app.debug:
pass
else:
_worker_started = False
return
def _loop():
with app.app_context():
stale = db.session.query(ScheduleTask).filter(
ScheduleTask.enabled.is_(True),
ScheduleTask.next_run_at.isnot(None),
ScheduleTask.next_run_at <= utc_now_naive(),
).all()
for t in stale:
if t.cron_expr:
t.next_run_at = compute_next_run_at(t.cron_expr, timezone_name=getattr(t, "schedule_timezone", None))
if t.next_run_at is None:
t.enabled = False
else:
t.next_run_at = None
if stale:
db.session.commit()
current_app.logger.info("[schedule-worker] reset %d stale next_run_at on startup", len(stale))
stuck = db.session.query(ScheduleRun).filter(
ScheduleRun.status == "running",
).all()
cleaned = 0
for r in stuck:
if is_awaiting_rpa_schedule_run(r):
continue
r.status = "failed"
r.error_message = "服务重启,执行中断"
r.finished_at = datetime.utcnow()
cleaned += 1
if cleaned:
db.session.commit()
current_app.logger.info(
"[schedule-worker] cleaned %d stuck running runs on startup (skipped awaiting RPA)",
cleaned,
)
recovered_awaiting = recover_all_stale_awaiting_rpa_schedule_runs()
if recovered_awaiting:
current_app.logger.info(
"[schedule-worker] recovered %d stale awaiting RPA runs on startup",
recovered_awaiting,
)
from app.services.shipping_notice.inventory_rpa_callback_cleanup import (
recover_pending_rpa_callback_cleanup_jobs,
)
cleanup_count, cleanup_warnings = recover_pending_rpa_callback_cleanup_jobs()
if cleanup_count:
current_app.logger.info(
"[schedule-worker] processed %d RPA callback cleanup job(s) on startup",
cleanup_count,
)
if cleanup_warnings:
current_app.logger.warning(
"[schedule-worker] RPA callback cleanup warnings: %s",
"; ".join(cleanup_warnings[:5]),
)
from app.services.shipping_notice.rpa_worker_heartbeat_alert import maybe_alert_rpa_worker_status
maybe_alert_rpa_worker_status(force=True)
while True:
try:
from app.services.shipping_notice.rpa_worker_heartbeat_alert import (
maybe_alert_rpa_worker_status,
)
maybe_alert_rpa_worker_status()
now = utc_now_naive()
due_tasks = db.session.query(ScheduleTask).filter(
ScheduleTask.enabled.is_(True),
ScheduleTask.next_run_at.isnot(None),
ScheduleTask.next_run_at <= now,
).limit(5).with_for_update(skip_locked=True).all()
for task in due_tasks:
recover_stale_awaiting_rpa_schedule_runs(task)
has_running = db.session.query(ScheduleRun).filter(
ScheduleRun.schedule_task_id == task.id,
ScheduleRun.status == "running",
).first()
if has_running:
if task.cron_expr:
task.next_run_at = compute_next_run_at(task.cron_expr, timezone_name=getattr(task, "schedule_timezone", None))
db.session.commit()
continue
try:
run_task_now(task, trigger_type="cron", triggered_by_user_id=None)
except Exception as e:
current_app.logger.error("[schedule-worker] task_id=%s run failed: %s", task.id, e, exc_info=True)
db.session.rollback()
if task.cron_expr:
task.next_run_at = compute_next_run_at(task.cron_expr, timezone_name=getattr(task, "schedule_timezone", None))
if task.next_run_at is None:
task.enabled = False
else:
task.next_run_at = None
db.session.commit()
except Exception:
db.session.rollback()
time.sleep(30)
t = threading.Thread(target=_loop, daemon=True, name="schedule-worker")
t.start()
@@ -0,0 +1,44 @@
"""
backend/app/services/schedule/voucher_check_job.py
用途:立账凭证检核 platform_job 薄封装。
依赖:voucher_check.runner、excel_rows 表头注册。
逻辑:job_registry 注册 accounting-voucher-check 后由 schedule worker / 会话触发调用。
"""
from __future__ import annotations
from typing import Any
from app.models import ScheduleRun, ScheduleTask
from app.services.schedule import register_schedule_header
from app.services.voucher_check.excel_rows import (
VOUCHER_CHECK_HEADER_LABELS,
VOUCHER_CHECK_HEADER_ORDER,
)
from app.services.voucher_check.runner import run_voucher_check_batch
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
_HEADERS_REGISTERED = False
def _ensure_headers() -> None:
global _HEADERS_REGISTERED
if _HEADERS_REGISTERED:
return
register_schedule_header(
"accounting-voucher-check",
VOUCHER_CHECK_HEADER_ORDER,
VOUCHER_CHECK_HEADER_LABELS,
)
_HEADERS_REGISTERED = True
def run_voucher_check_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""
执行立账凭证检核排程。
核心逻辑:注册 Excel 表头后委托 runner;日批默认 incremental。
"""
_ensure_headers()
return run_voucher_check_batch(task, run)