feat(schedule):cron支持图形,RoHS检核增加进度显示

This commit is contained in:
hugo committed 2026-06-15 13:42:15 +08:00
1 parent 6d0e78be81
commit f5aac9c893
46 files changed
+1987 -221

No files matched your search

+97 -29
View File
@@ -508,6 +508,7 @@ class DifyService:
conversation_id: str = None,
request_id: str | None = None,
session_id: str | None = None,
hxops_turn_id: str | None = None,
files: list[dict[str, Any]] | None = None,
inputs: dict[str, Any] | None = None,
):
@@ -571,14 +572,47 @@ class DifyService:
attribution_parts: List[str] = []
chat_persist_started = False
has_sent_answer = False
chat_log_id_persisted: int | None = None
run_id_persisted: int | None = None
def _resolve_persist_run_id() -> int | None:
try:
from app.services.rohs_check_tools.agent_resolver import is_rohs_check_chat_agent
from app.services.rohs_check_tools.chat_log_run_binding import resolve_run_id_for_chat_log
if not is_rohs_check_chat_agent(agent):
return None
return resolve_run_id_for_chat_log(
session_id=session_id,
query=query,
turn_id=hxops_turn_id,
)
except Exception:
return None
def persist_stream_chat(data: dict, event_name: str) -> None:
persist_stream_chat_async(data, event_name)
result = persist_stream_chat_async(data, event_name)
if isinstance(result, dict):
if result.get("chat_log_id") is not None:
data["chat_log_id"] = result["chat_log_id"]
if result.get("run_id") is not None:
data["run_id"] = result["run_id"]
def persist_stream_chat_async(data: dict, event_name: str) -> dict | None:
nonlocal chat_persist_started, chat_log_id_persisted, run_id_persisted
if chat_persist_started and event_name == "workflow_finished" and chat_log_id_persisted:
run_id = _resolve_persist_run_id()
if run_id and run_id != run_id_persisted:
from app.services.rohs_check_tools.chat_log_run_binding import update_chat_log_run_id
if update_chat_log_run_id(chat_log_id_persisted, run_id):
run_id_persisted = run_id
return {"chat_log_id": chat_log_id_persisted, "run_id": run_id_persisted}
def persist_stream_chat_async(data: dict, event_name: str) -> None:
nonlocal chat_persist_started
if chat_persist_started:
return
return {"chat_log_id": chat_log_id_persisted, "run_id": run_id_persisted} if chat_log_id_persisted else None
chat_persist_started = True
app_obj = current_app._get_current_object() if current_app else None
@@ -587,27 +621,33 @@ class DifyService:
attribution_snapshot = list(attribution_parts)
answer_snapshot = build_final_answer_text(persist_data, event_name)
latency_snapshot = int((time.time() - start_time) * 1000)
message_payload = persist_data.get('message_payload')
def _persist() -> None:
if not app_obj:
return
with app_obj.app_context():
DifyService._persist_stream_chat_record(
data=persist_data,
event_name=event_name,
request_id=request_id,
user_id=user_id,
agent_id=agent.id,
session_id=session_id,
normalized_conversation_id=normalized_conversation_id,
query=query,
answer_text=answer_snapshot,
latency=latency_snapshot,
retriever_resources=resources_snapshot,
attribution_parts=attribution_snapshot,
)
Thread(target=_persist, daemon=True, name=f"dify-chat-persist-{request_id or 'unknown'}").start()
if not app_obj:
return None
with app_obj.app_context():
result = DifyService._persist_stream_chat_record(
data=persist_data,
event_name=event_name,
request_id=request_id,
user_id=user_id,
agent=agent,
session_id=session_id,
hxops_turn_id=hxops_turn_id,
normalized_conversation_id=normalized_conversation_id,
query=query,
answer_text=answer_snapshot,
latency=latency_snapshot,
retriever_resources=resources_snapshot,
attribution_parts=attribution_snapshot,
message_payload=message_payload if isinstance(message_payload, dict) else None,
)
if isinstance(result, dict):
if result.get("chat_log_id"):
chat_log_id_persisted = int(result["chat_log_id"])
if result.get("run_id"):
run_id_persisted = int(result["run_id"])
return result
def build_final_answer_text(data: dict, event_name: str) -> str:
answer_text = ''.join(full_answer).strip()
@@ -790,6 +830,8 @@ class DifyService:
latency,
retriever_resources=None,
attribution_parts=None,
payload=None,
run_id: int | None = None,
) -> Optional[int]:
"""
把最终问答和元数据写入 ChatLog
@@ -803,6 +845,7 @@ class DifyService:
latency: End-to-end latency in milliseconds.
retriever_resources: Source retrieval metadata list.
attribution_parts: Attribution/annotation list.
run_id: RoHS 检核批次 ID(按轮问答绑定,可选)。
"""
try:
chat_log = ChatLog(
@@ -816,6 +859,8 @@ class DifyService:
latency=latency or 0,
retriever_resources=retriever_resources or [],
attribution_parts=attribution_parts or [],
payload=payload if isinstance(payload, dict) else None,
run_id=run_id if run_id and run_id > 0 else None,
)
db.session.add(chat_log)
db.session.commit()
@@ -835,17 +880,19 @@ class DifyService:
event_name: str,
request_id: str | None,
user_id: int,
agent_id: int,
agent,
session_id: str | None,
hxops_turn_id: str | None,
normalized_conversation_id: str | None,
query: str,
answer_text: str,
latency: int,
retriever_resources: List[Any],
attribution_parts: List[str],
) -> None:
message_payload: dict | None = None,
) -> dict | None:
if not answer_text and not str(query or '').strip():
return
return None
if current_app:
current_app.logger.info(
@@ -863,9 +910,23 @@ class DifyService:
usage = metadata.get('usage', {}) or {}
db_write_started = time.time()
run_id = None
try:
from app.services.rohs_check_tools.agent_resolver import is_rohs_check_chat_agent
from app.services.rohs_check_tools.chat_log_run_binding import resolve_run_id_for_chat_log
if is_rohs_check_chat_agent(agent):
run_id = resolve_run_id_for_chat_log(
session_id=session_id,
query=query,
turn_id=hxops_turn_id,
)
except Exception:
run_id = None
chat_log_id = DifyService._log_chat(
user_id=user_id,
agent_id=agent_id,
agent_id=agent.id,
session_id=session_id,
conversation_id=data.get('conversation_id') or normalized_conversation_id,
query=query,
@@ -874,17 +935,24 @@ class DifyService:
latency=latency,
retriever_resources=retriever_resources,
attribution_parts=attribution_parts,
payload=message_payload,
run_id=run_id,
)
if chat_log_id and current_app:
current_app.logger.info(
"[chat-perf] persisted async request_id=%s event=%s total_ms=%s db_write_ms=%s answer_len=%s conversation_id=%s",
"[chat-perf] persisted async request_id=%s event=%s total_ms=%s db_write_ms=%s answer_len=%s conversation_id=%s chat_log_id=%s run_id=%s",
request_id,
event_name,
latency,
int((time.time() - db_write_started) * 1000),
len(answer_text),
data.get('conversation_id') or normalized_conversation_id,
chat_log_id,
run_id,
)
if not chat_log_id:
return None
return {"chat_log_id": chat_log_id, "run_id": run_id}
@staticmethod
def _normalize_resources(resources):
@@ -0,0 +1,188 @@
"""
services/rohs_check_tools/chat_log_run_binding.py
用途:将 RoHS 检核批次 ID 写入 ChatLog.run_id(按轮问答绑定)。
依赖:ChatLog、ScheduleRun、task_resolver.is_rohs_check_schedule_task。
逻辑:启动检核 API 写入 ScheduleRun.api_request_json;message_end 落 ChatLog 时解析并绑定 run_id。
"""
from __future__ import annotations
import re
from datetime import datetime, timedelta
from typing import Any
from flask import current_app
from app import db
from app.models import ChatLog, ScheduleRun
from app.services.rohs_check_tools.task_resolver import is_rohs_check_schedule_task
def _normalize_bind_text(text: str | None) -> str:
"""折叠空白,便于 user_message 与 ChatLog.query 对齐。"""
return re.sub(r"\s+", " ", str(text or "").strip())
def merge_chat_log_bind_context(run: ScheduleRun | None, data: dict[str, Any] | None) -> None:
"""
在 ScheduleRun 上记录本轮问答的绑定上下文,供 ChatLog 落库时匹配。
Args:
run: 新建或复用的检核批次。
data: 启动检核 HTTP Body。
"""
if not run:
return
payload = data if isinstance(data, dict) else {}
session_id = str(payload.get("hxops_session_id") or "").strip()
turn_id = str(payload.get("hxops_turn_id") or "").strip()
user_message = str(payload.get("user_message") or "").strip()
if not session_id and not turn_id and not user_message:
return
req = dict(run.api_request_json or {}) if isinstance(run.api_request_json, dict) else {}
if session_id:
req["bind_session_id"] = session_id
req["hxops_session_id"] = session_id
if turn_id:
req["bind_turn_id"] = turn_id
req["hxops_turn_id"] = turn_id
if user_message:
req["bind_user_message"] = user_message
req["user_message"] = user_message
if payload.get("conversation_id"):
req["conversation_id"] = payload.get("conversation_id")
req["bind_requested_at"] = datetime.utcnow().isoformat()
run.api_request_json = req
def resolve_run_id_for_chat_log(
*,
session_id: str | None = None,
query: str | None = None,
turn_id: str | None = None,
) -> int | None:
"""
匹配本轮问答应对绑定的 RoHS 检核批次 ID。
优先级:hxops_turn_id > session_id + 归一化 query > session_id + 近期 bind。
Args:
session_id: HXOPS ChatSession.session_id。
query: 本轮用户输入(ChatLog.query)。
turn_id: 本轮对话 turn 标识(HXOPS 注入 Dify inputs)。
Returns:
匹配到的 ScheduleRun.id,或 None。
"""
session_key = str(session_id or "").strip()
turn_key = str(turn_id or "").strip()
query_key = _normalize_bind_text(query)
rows = (
ScheduleRun.query.order_by(ScheduleRun.id.desc())
.limit(120)
.all()
)
def _req(run: ScheduleRun) -> dict:
return run.api_request_json if isinstance(run.api_request_json, dict) else {}
rohs_rows = [row for row in rows if is_rohs_check_schedule_task(row.task)]
if turn_key:
for run in rohs_rows:
req = _req(run)
bind_turn = str(req.get("bind_turn_id") or req.get("hxops_turn_id") or "").strip()
if bind_turn == turn_key:
return int(run.id)
if session_key and query_key:
for run in rohs_rows:
req = _req(run)
bind_session = str(req.get("bind_session_id") or req.get("hxops_session_id") or "").strip()
bind_query = _normalize_bind_text(req.get("bind_user_message") or req.get("user_message"))
if bind_session == session_key and bind_query == query_key:
return int(run.id)
if session_key and query_key:
for run in rohs_rows:
req = _req(run)
bind_session = str(req.get("bind_session_id") or req.get("hxops_session_id") or "").strip()
bind_query = _normalize_bind_text(req.get("bind_user_message") or req.get("user_message"))
if bind_session == session_key and bind_query and (
query_key in bind_query or bind_query in query_key
):
return int(run.id)
if session_key:
cutoff = datetime.utcnow() - timedelta(minutes=15)
for run in rohs_rows:
req = _req(run)
bind_session = str(req.get("bind_session_id") or req.get("hxops_session_id") or "").strip()
if bind_session != session_key:
continue
bind_at_raw = str(req.get("bind_requested_at") or run.started_at or "")
try:
bind_at = datetime.fromisoformat(bind_at_raw.replace("Z", ""))
except ValueError:
bind_at = run.started_at
if bind_at and bind_at >= cutoff and run.status == "running":
return int(run.id)
if current_app and (turn_key or session_key):
current_app.logger.warning(
"[rohs-bind] resolve run_id miss turn_id=%s session_id=%s query_len=%s",
turn_key or None,
session_key or None,
len(query_key),
)
return None
def update_chat_log_run_id(chat_log_id: int, run_id: int | None) -> bool:
"""
回写已有 ChatLog.run_id(workflow_finished 二次绑定)。
Returns:
是否成功更新。
"""
if not chat_log_id or not run_id or run_id <= 0:
return False
log = db.session.get(ChatLog, chat_log_id)
if not log:
return False
if log.run_id == run_id:
return True
run = db.session.get(ScheduleRun, run_id)
if not run or not is_rohs_check_schedule_task(run.task):
return False
log.run_id = run_id
db.session.commit()
return True
def bind_run_id_to_chat_log(*, chat_log: ChatLog | None, run_id: int | None) -> bool:
"""
将检核批次 ID 写入 ChatLog.run_id。
Returns:
是否成功写入并提交。
"""
if not chat_log or not run_id or run_id <= 0:
return False
run = db.session.get(ScheduleRun, run_id)
if not run or not is_rohs_check_schedule_task(run.task):
return False
chat_log.run_id = run_id
db.session.commit()
return True
__all__ = [
"bind_run_id_to_chat_log",
"merge_chat_log_bind_context",
"resolve_run_id_for_chat_log",
"update_chat_log_run_id",
]
@@ -0,0 +1,50 @@
"""
services/rohs_check_tools/chat_log_run_resolver.py
用途:按 ChatLog.run_id 解析 RoHS 检核进度(按轮问答)。
依赖:ChatLog、ScheduleRun、task_resolver.is_rohs_check_schedule_task。
逻辑:由 for-log API 调用;run_id 在 message_end 写入 chat_logs 表。
"""
from __future__ import annotations
from app import db
from app.models import ChatLog, ScheduleRun
from app.services.rohs_check_tools.task_resolver import is_rohs_check_schedule_task
def find_run_for_chat_log(
*,
task_id: int,
chat_log_id: int,
) -> ScheduleRun | None:
"""
查询某条问答记录绑定的 RoHS 检核批次。
Args:
task_id: ScheduleTask.id。
chat_log_id: ChatLog.id。
Returns:
绑定的 ScheduleRun,或 None。
"""
if chat_log_id <= 0 or task_id <= 0:
return None
log = db.session.get(ChatLog, chat_log_id)
if not log or not log.run_id:
return None
run = db.session.get(ScheduleRun, log.run_id)
if (
run
and run.schedule_task_id == task_id
and is_rohs_check_schedule_task(run.task)
):
return run
return None
__all__ = [
"find_run_for_chat_log",
]
@@ -4,14 +4,27 @@ from flask import current_app
from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE
from app.services.rohs_check_tools.agent_resolver import is_rohs_check_chat_agent
from app.services.rohs_check_tools.task_resolver import resolve_default_rohs_schedule_task_id
# Dify Chatflow「用户输入」变量名 — 须与画布 Start 节点配置一致(见 docs/rohs_chatflow_guide.md §3.1)
HXOPS_TOOLS_API_BASE_INPUT = "HXOPS_TOOLS_API_BASE"
HXOPS_TOOL_API_TOKEN_INPUT = "hxops_tool_api_token"
ROHS_TASK_ID_INPUT = "task_id"
HXOPS_SESSION_ID_INPUT = "hxops_session_id"
HXOPS_TURN_ID_INPUT = "hxops_turn_id"
def build_dify_chat_inputs() -> dict[str, str]:
"""Build Dify chat API inputs for RoHS Chatflow HTTP nodes."""
def build_dify_chat_inputs(
hxops_session_id: str | None = None,
hxops_turn_id: str | None = None,
) -> dict[str, str]:
"""
构建 RoHS Chatflow 的 Dify chat inputs(HTTP 节点与启动检核 Body 共用变量名)。
Args:
hxops_session_id: 当前 HXOPS ChatSession.session_id。
hxops_turn_id: 本轮对话 turn 标识,用于 ChatLog.run_id 精确回写。
"""
base = resolve_HXOPS_TOOLS_API_BASE()
key = str(
current_app.config.get("ROHS_TOOLS_API_KEY")
@@ -23,12 +36,24 @@ def build_dify_chat_inputs() -> dict[str, str]:
inputs[HXOPS_TOOLS_API_BASE_INPUT] = base
if key:
inputs[HXOPS_TOOL_API_TOKEN_INPUT] = key
task_id = resolve_default_rohs_schedule_task_id()
if task_id:
inputs[ROHS_TASK_ID_INPUT] = str(task_id)
session_id = str(hxops_session_id or "").strip()
if session_id:
inputs[HXOPS_SESSION_ID_INPUT] = session_id
turn_id = str(hxops_turn_id or "").strip()
if turn_id:
inputs[HXOPS_TURN_ID_INPUT] = turn_id
return inputs
__all__ = [
"HXOPS_TOOLS_API_BASE_INPUT",
"HXOPS_TOOL_API_TOKEN_INPUT",
"HXOPS_SESSION_ID_INPUT",
"HXOPS_TURN_ID_INPUT",
"ROHS_TASK_ID_INPUT",
"build_dify_chat_inputs",
"is_rohs_check_chat_agent",
]
@@ -0,0 +1,101 @@
"""
services/rohs_check_tools/task_resolver.py
用途:解析 RoHS Chatflow 绑定的 ScheduleTask.id,供 Dify inputs、Agent 进度能力与 active 轮询使用。
依赖:ScheduleTask、rohs_check_tools 任务识别逻辑。
逻辑:优先读 Agent extra_config;否则在仅有一个 RoHS 检核任务时自动选用。
"""
from __future__ import annotations
from flask import current_app
from app.models import ScheduleTask
_ROHS_TASK_KEYWORDS = ("rohs", "rohs文件检核", "rohs 文件检核")
def is_rohs_check_schedule_task(task: ScheduleTask | None) -> bool:
"""判断排程任务是否为 RoHS 文件检核任务。"""
if not task:
return False
values = (
getattr(task, "schedule_no", None),
getattr(task, "name", None),
getattr(task, "platform_api_path", None),
)
haystack = " ".join(str(item or "").lower() for item in values)
return any(keyword in haystack for keyword in _ROHS_TASK_KEYWORDS)
def list_rohs_schedule_tasks() -> list[ScheduleTask]:
"""列出全部 RoHS 检核排程任务。"""
rows = ScheduleTask.query.order_by(ScheduleTask.id.asc()).all()
return [task for task in rows if is_rohs_check_schedule_task(task)]
def resolve_schedule_task_id_from_mapping(mapping: dict | None) -> int | None:
"""从 tool_run_progress 或等价 dict 解析 schedule_task_id / task_id。"""
if not isinstance(mapping, dict):
return None
raw = mapping.get("schedule_task_id", mapping.get("task_id"))
try:
task_id = int(raw)
except (TypeError, ValueError):
return None
return task_id if task_id > 0 else None
def resolve_default_rohs_schedule_task_id() -> int | None:
"""
解析默认 RoHS 检核 ScheduleTask.id。
优先级:环境变量/配置 ROHS_CHATFLOW_SCHEDULE_TASK_ID → 库内唯一 RoHS 任务 → None。
"""
configured = current_app.config.get("ROHS_CHATFLOW_SCHEDULE_TASK_ID")
if configured not in (None, "", 0, "0"):
try:
task_id = int(configured)
if task_id > 0:
return task_id
except (TypeError, ValueError):
pass
tasks = list_rohs_schedule_tasks()
if len(tasks) == 1:
return int(tasks[0].id)
return None
def enrich_tool_run_progress_extra(extra_config: dict | None) -> dict:
"""
为 RoHS Agent 的 extra_config 补全 tool_run_progress.schedule_task_id(若缺失)。
Returns:
新的 extra_config 副本;无变更时返回原 dict 浅拷贝。
"""
extra = dict(extra_config or {})
tool_cfg = extra.get("tool_run_progress")
if not isinstance(tool_cfg, dict):
return extra
merged = dict(tool_cfg)
merged.setdefault("log_progress_url", "/api/workspace/rohs-check/runs/for-log")
merged.setdefault("detail_url_template", "/api/workspace/rohs-check/runs/{run_id}")
if not resolve_schedule_task_id_from_mapping(tool_cfg):
task_id = resolve_default_rohs_schedule_task_id()
if task_id:
merged["schedule_task_id"] = task_id
extra["tool_run_progress"] = merged
return extra
__all__ = [
"enrich_tool_run_progress_extra",
"is_rohs_check_schedule_task",
"list_rohs_schedule_tasks",
"resolve_default_rohs_schedule_task_id",
"resolve_schedule_task_id_from_mapping",
]
@@ -0,0 +1,24 @@
"""
backend/app/services/schedule/cron_util.py
排程 Cron 表达式规范化与校验辅助。
"""
from __future__ import annotations
def normalize_cron_expr(expr: str | None) -> str:
"""
修正常见笔误:* 12,17 * * *(小时内每分钟)→ 0 12,17 * * *(整点)。
"""
text = str(expr or '').strip()
parts = text.split()
if len(parts) == 5 and parts[0] == '*' and parts[1] != '*':
parts[0] = '0'
return ' '.join(parts)
return text
def is_risky_cron_expr(expr: str | None) -> bool:
"""分钟为 * 且小时已限定时,会在该小时内每分钟触发。"""
text = str(expr or '').strip()
parts = text.split()
return len(parts) == 5 and parts[0] == '*' and parts[1] != '*'
@@ -9,6 +9,17 @@ from sqlalchemy.orm import joinedload
from app import db
from app.models import ScheduleRun, ScheduleTask
from app.response_utils import utc_iso
from app.services.schedule.timezone_util import (
DEFAULT_SCHEDULE_TIMEZONE,
compute_next_run_at,
normalize_schedule_timezone,
)
def _schedule_timezone_label(task: ScheduleTask | None = None) -> str:
if task is not None:
return normalize_schedule_timezone(getattr(task, "schedule_timezone", None))
return DEFAULT_SCHEDULE_TIMEZONE
def _as_naive_utc(dt: datetime | None) -> datetime | None:
@@ -28,6 +39,7 @@ def serialize_task(task: ScheduleTask, *, last_status: str | None = None) -> dic
'owner_user_id': task.owner_user_id,
'owner_username': task.owner.username if task.owner else None,
'cron_expr': task.cron_expr,
'schedule_timezone': _schedule_timezone_label(task),
'wait_seconds': task.wait_seconds,
'dify_agent_id': task.dify_agent_id,
'platform_api_path': task.platform_api_path,
@@ -82,6 +94,17 @@ def serialize_run(run: ScheduleRun) -> dict:
}
def _repair_next_run_if_needed(task: ScheduleTask) -> bool:
"""启用中但 next_run_at 为空时补算,返回是否发生修改。"""
if not task.enabled or not str(task.cron_expr or '').strip():
return False
if task.next_run_at is not None:
return False
task.schedule_timezone = normalize_schedule_timezone(getattr(task, 'schedule_timezone', None))
task.next_run_at = compute_next_run_at(task.cron_expr, timezone_name=task.schedule_timezone)
return task.next_run_at is not None
def list_tasks() -> list[dict]:
latest_run_subquery = (
db.session.query(
@@ -99,6 +122,13 @@ def list_tasks() -> list[dict]:
.order_by(ScheduleTask.created_at.desc())
.all()
)
repaired = False
for task, _last_status in rows:
if _repair_next_run_if_needed(task):
repaired = True
if repaired:
db.session.commit()
return [serialize_task(task, last_status=last_status) for task, last_status in rows]
@@ -6,7 +6,6 @@ import uuid
from datetime import datetime
from typing import Any
from croniter import croniter
from flask import current_app
from app import db
@@ -15,6 +14,8 @@ from app.services.schedule import normalize_platform_api_path, resolve_schedule_
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id
from app.services.schedule.excel_service import export_schedule_result_excel
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
from app.services.schedule.cron_util import normalize_cron_expr
from app.services.schedule.timezone_util import compute_next_run_at, normalize_schedule_timezone, utc_now_naive
_worker_started = False
_worker_lock = threading.Lock()
@@ -160,6 +161,7 @@ def create_task(
schedule_type: str,
owner_user_id: int,
cron_expr: str,
schedule_timezone: str | None = None,
wait_seconds: int,
dify_agent_id: int | None,
platform_api_path: str | None,
@@ -168,12 +170,14 @@ def create_task(
enabled: bool,
actor_id: int | None,
) -> ScheduleTask:
cron_expr = normalize_cron_expr(cron_expr)
task = ScheduleTask(
schedule_no=_generate_schedule_no(),
name=name,
schedule_type="platform_app",
owner_user_id=owner_user_id,
cron_expr=cron_expr,
schedule_timezone=normalize_schedule_timezone(schedule_timezone),
wait_seconds=max(0, int(wait_seconds or 0)),
dify_agent_id=dify_agent_id,
platform_api_path=normalize_platform_api_path(platform_api_path) or None,
@@ -184,11 +188,8 @@ def create_task(
updated_by=actor_id,
)
if task.enabled and task.cron_expr:
try:
iter = croniter(task.cron_expr, datetime.utcnow())
task.next_run_at = iter.get_next(datetime)
except Exception:
task.next_run_at = None
task.next_run_at = compute_next_run_at(task.cron_expr, timezone_name=task.schedule_timezone)
if task.next_run_at is None:
task.enabled = False
db.session.add(task)
db.session.commit()
@@ -200,13 +201,20 @@ def update_task(task: ScheduleTask, *, payload: dict[str, Any], actor_id: int |
"name",
"owner_user_id",
"cron_expr",
"schedule_timezone",
"wait_seconds",
"dify_agent_id",
"notify_enabled",
"enabled",
]:
if key in payload:
setattr(task, key, payload[key])
if key == "schedule_timezone":
value = normalize_schedule_timezone(payload[key])
elif key == "cron_expr":
value = normalize_cron_expr(str(payload[key] or ""))
else:
value = payload[key]
setattr(task, key, value)
if "platform_api_path" in payload:
task.platform_api_path = normalize_platform_api_path(payload.get("platform_api_path")) or None
if "notify_user_ids_json" in payload and isinstance(payload.get("notify_user_ids_json"), list):
@@ -222,11 +230,8 @@ def update_task(task: ScheduleTask, *, payload: dict[str, Any], actor_id: int |
task.schedule_type = "platform_app"
if task.enabled and task.cron_expr:
try:
iter = croniter(task.cron_expr, datetime.utcnow())
task.next_run_at = iter.get_next(datetime)
except Exception:
task.next_run_at = None
task.schedule_timezone = normalize_schedule_timezone(getattr(task, "schedule_timezone", None))
task.next_run_at = compute_next_run_at(task.cron_expr, timezone_name=task.schedule_timezone)
else:
task.next_run_at = None
@@ -258,11 +263,7 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
db.session.commit()
if task.cron_expr and trigger_type == "cron":
try:
iter = croniter(task.cron_expr, datetime.utcnow())
task.next_run_at = iter.get_next(datetime)
except Exception:
task.next_run_at = None
task.next_run_at = compute_next_run_at(task.cron_expr, timezone_name=getattr(task, "schedule_timezone", None))
db.session.commit()
start_ts = time.time()
@@ -402,15 +403,12 @@ def start_scheduler(app):
stale = db.session.query(ScheduleTask).filter(
ScheduleTask.enabled.is_(True),
ScheduleTask.next_run_at.isnot(None),
ScheduleTask.next_run_at <= datetime.utcnow(),
ScheduleTask.next_run_at <= utc_now_naive(),
).all()
for t in stale:
if t.cron_expr:
try:
it = croniter(t.cron_expr, datetime.utcnow())
t.next_run_at = it.get_next(datetime)
except Exception:
t.next_run_at = None
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
@@ -431,7 +429,7 @@ def start_scheduler(app):
while True:
try:
now = datetime.utcnow()
now = utc_now_naive()
due_tasks = db.session.query(ScheduleTask).filter(
ScheduleTask.enabled.is_(True),
ScheduleTask.next_run_at.isnot(None),
@@ -444,11 +442,7 @@ def start_scheduler(app):
).first()
if has_running:
if task.cron_expr:
try:
iter = croniter(task.cron_expr, datetime.utcnow())
task.next_run_at = iter.get_next(datetime)
except Exception:
task.next_run_at = None
task.next_run_at = compute_next_run_at(task.cron_expr, timezone_name=getattr(task, "schedule_timezone", None))
db.session.commit()
continue
try:
@@ -458,11 +452,8 @@ def start_scheduler(app):
db.session.rollback()
if task.cron_expr:
try:
iter = croniter(task.cron_expr, datetime.utcnow())
task.next_run_at = iter.get_next(datetime)
except Exception:
task.next_run_at = None
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
@@ -0,0 +1,132 @@
"""
backend/app/services/schedule/timezone_util.py
排程 Cron 时区:优先按任务自己的 IANA 时区解析表达式,数据库存储 UTC naive。
"""
from __future__ import annotations
from datetime import datetime, timedelta, timezone, tzinfo
from zoneinfo import ZoneInfo
from croniter import croniter
from flask import current_app
DEFAULT_SCHEDULE_TIMEZONE = 'Asia/Shanghai'
# 环境未安装 tzdata 时,用固定 UTC 偏移回退(不含夏令时)
_FIXED_TZ_FALLBACKS: dict[str, tzinfo] = {
'Asia/Shanghai': timezone(timedelta(hours=8)),
'Asia/Taipei': timezone(timedelta(hours=8)),
'Asia/Hong_Kong': timezone(timedelta(hours=8)),
'UTC': timezone.utc,
}
def get_schedule_timezone_name(timezone_name: str | None = None) -> str:
"""解析排程时区名称;优先使用任务时区,其次回退到系统默认时区。"""
return (timezone_name or current_app.config.get('SCHEDULE_TIMEZONE') or DEFAULT_SCHEDULE_TIMEZONE).strip()
def resolve_schedule_tzinfo(timezone_name: str | None = None) -> tzinfo:
"""
将 IANA 时区名解析为 tzinfo。
优先使用 zoneinfo;若运行环境缺少 tzdata(常见于未 pip install tzdata 的容器/venv),
对常用业务时区回退到固定 UTC 偏移。
"""
name = get_schedule_timezone_name(timezone_name)
try:
return ZoneInfo(name)
except Exception:
fallback = _FIXED_TZ_FALLBACKS.get(name)
if fallback is not None:
_log_tz_fallback_once(name)
return fallback
default_fallback = _FIXED_TZ_FALLBACKS[DEFAULT_SCHEDULE_TIMEZONE]
_log_tz_fallback_once(name, fallback_to=DEFAULT_SCHEDULE_TIMEZONE)
return default_fallback
def get_schedule_timezone(timezone_name: str | None = None) -> tzinfo:
"""将排程时区名称转换为 tzinfo,供 croniter 计算当地执行时间。"""
return resolve_schedule_tzinfo(timezone_name)
def normalize_schedule_timezone(timezone_name: str | None) -> str:
"""校验并标准化 IANA 时区名;无法通过 zoneinfo 校验时仍保留可回退的名称。"""
text = get_schedule_timezone_name(timezone_name)
try:
ZoneInfo(text)
return text
except Exception:
if text in _FIXED_TZ_FALLBACKS:
return text
return DEFAULT_SCHEDULE_TIMEZONE
def utc_now_naive() -> datetime:
"""返回 UTC naive datetime,统一用于数据库字段比较。"""
return datetime.now(timezone.utc).replace(tzinfo=None)
def to_utc_naive(dt: datetime) -> datetime:
"""将 aware datetime 转为 UTC naive;naive 输入保持不变。"""
if dt.tzinfo is None:
return dt
return dt.astimezone(timezone.utc).replace(tzinfo=None)
def compute_next_run_at(
cron_expr: str,
*,
base_utc_naive: datetime | None = None,
timezone_name: str | None = None,
) -> datetime | None:
"""
按排程业务时区计算下次执行时刻,返回 UTC naive 供入库与 worker 比较。
:param cron_expr: 5 段标准 Cron
:param base_utc_naive: 基准时刻(UTC naive);默认取当前时刻
"""
text = str(cron_expr or '').strip()
if not text:
return None
tz_name = normalize_schedule_timezone(timezone_name)
try:
tz = resolve_schedule_tzinfo(tz_name)
if base_utc_naive is None:
base_aware = datetime.now(tz)
else:
base_aware = base_utc_naive.replace(tzinfo=timezone.utc).astimezone(tz)
itr = croniter(text, base_aware)
return to_utc_naive(itr.get_next(datetime))
except Exception as exc:
try:
current_app.logger.warning(
"compute_next_run_at failed: %s cron=%s tz=%s",
exc,
text,
tz_name,
)
except RuntimeError:
pass
return None
_logged_tz_fallbacks: set[str] = set()
def _log_tz_fallback_once(requested: str, *, fallback_to: str | None = None) -> None:
"""缺少 tzdata 时仅记录一次回退日志,避免刷屏。"""
key = f'{requested}->{fallback_to or requested}'
if key in _logged_tz_fallbacks:
return
_logged_tz_fallbacks.add(key)
try:
current_app.logger.warning(
"tzdata unavailable; using fixed UTC offset fallback for schedule timezone %s%s. "
"Install backend dependency tzdata (pip install tzdata).",
requested,
f' (fallback {fallback_to})' if fallback_to else '',
)
except RuntimeError:
pass