定时任务后台:三张表、输入模板、调度循环和 Webhook 推送,设置加「通知」一组

- 表:schedules(Webhook 地址和签名密钥加密存放、next_run_at 存 UTC、version 乐观锁)、schedule_fires((任务,
  fire_at, kind) 唯一)、webhook_deliveries;新表由 create_all 建,不用迁移
- 输入模板:{{ schedule.yesterday }} 这类变量按计划触发时间在任务时区算(不按「现在」:补发晚了、零点前后立即
  运行,「昨天」都是那次触发的昨天),上一次计划触发时间按 cron 往前找,同一次触发永远渲染出同一份输入;未知
  变量、未知过滤器、{{ }} 不成对都拦下,声明了入口字段的工作流还对照字段名和必填项
- 调度循环:每 15 秒一拍,条件 UPDATE 认领到点的任务并推进到下一次,两拍并发只有一拍认领得到,触发记录的唯一
  约束是第二道保险;上一次运行没结束(含停在审批、服务重启挂起的)记跳过;错过的只看最近一次,在宽限内补一次、
  超出记跳过,积压不补;发起走 launch_run,拒绝的原话记成未能发起,别的异常记通用说明、详情进日志;stop 等手上
  这一拍收尾,开关关着时 start 不起循环
- Webhook:通用 JSON(可选 HMAC 签名头)、飞书文本、企业微信 markdown、钉钉 markdown,按各平台算法签名;运行
  结束、失败、确有待审批时按订阅推一次,结束的等封存好再推,没订阅、没配 Webhook 的也记下已处理,之后配上不会
  补推旧的;10 秒超时、失败重试 3 次(4xx 不重试),每次推送记一条记录;通知里没有报告数字和原始报错,日志和
  错误里只有主机名(httpx 自己的请求日志也换成主机名)
- 设置 notify.public_base_url:通知里的运行链接 = 它 + /runs/{id},只收 http(s) 地址,末尾的 / 去掉
This commit is contained in:
ThearchyHelios
2026-10-05 08:37:57 +08:00
parent b51a686f53
commit a2a19df9df
11 changed files with 2253 additions and 7 deletions
+1 -1
View File
@@ -38,7 +38,7 @@ def test_unrecognized_value_fails_at_startup(monkeypatch):
async def test_start_and_stop_are_safe_noops():
"""调度循环还没实现:start / stop 什么都不做,没 start 过直接 stop 也不出错"""
"""测试环境关着调度(conftest):start 不起循环,没 start 过直接 stop 也不出错。开着时的循环见 test_scheduler_loop"""
await scheduler.stop()
await scheduler.start()
await scheduler.stop()
+182
View File
@@ -0,0 +1,182 @@
"""定时任务的输入模板(app/scheduler/service.py):日期变量按触发时间在任务时区算,模板写错就说出来。
- 变量都按 fire_at(计划触发时间)在任务时区算,不按「现在」:补跑晚了一小时,昨天还是计划那天的昨天
- 跨月、跨年、跨时区(同一时刻在上海已经是周一,在纽约还是周日);周从周一算起
- schedule.last_fire_time 是上一次计划触发的时间(按 cron 往前找),和本次一样写成带偏移的 ISO 时间
- 模板写错(未知变量、未知过滤器、{{ }} 不成对、空的 {{ }}、值不是文本)抛 TemplateError,中文说明哪个输入
- 声明了入口字段的工作流:模板里多出来的字段名、缺的必填输入(没有默认值)都拦下
夹具的工作流、字段名都是虚构的。
"""
from __future__ import annotations
from datetime import datetime, timezone
import pytest
from app.scheduler import service
from app.scheduler.service import TemplateError
UTC = timezone.utc
def values(fire_at: datetime, tz: str = "Asia/Shanghai", cron: str = "0 9 * * 1") -> dict[str, str]:
return service.template_values(fire_at, tz, cron)
# --------------------------------------------------------------------------
# 变量按 fire_at 在任务时区算
# --------------------------------------------------------------------------
def test_monday_morning_in_shanghai():
v = values(datetime(2026, 10, 5, 1, 0, tzinfo=UTC)) # 上海 2026-10-05(周一)09:00
assert v == {
"today": "2026-10-05",
"yesterday": "2026-10-04",
"this_week_start": "2026-10-05",
"last_week_start": "2026-09-28",
"last_week_end": "2026-10-04",
"this_month_start": "2026-10-01",
"last_month_start": "2026-09-01",
"last_month_end": "2026-09-30",
"fire_time": "2026-10-05T09:00:00+08:00",
"last_fire_time": "2026-09-28T09:00:00+08:00",
}
def test_across_a_month_boundary():
# 上海 2026-03-01(周日)00:30,UTC 还是 2 月 28 日
v = values(datetime(2026, 2, 28, 16, 30, tzinfo=UTC), cron="30 0 * * *")
assert (v["today"], v["yesterday"]) == ("2026-03-01", "2026-02-28")
assert (v["this_week_start"], v["last_week_start"], v["last_week_end"]) == ("2026-02-23", "2026-02-16", "2026-02-22")
assert (v["this_month_start"], v["last_month_start"], v["last_month_end"]) == ("2026-03-01", "2026-02-01", "2026-02-28")
assert v["last_fire_time"] == "2026-02-28T00:30:00+08:00"
def test_across_a_year_boundary():
v = values(datetime(2027, 1, 1, 0, 0, tzinfo=UTC), cron="0 8 1 * *") # 上海 2027-01-01(周五)08:00
assert (v["today"], v["yesterday"]) == ("2027-01-01", "2026-12-31")
assert (v["this_week_start"], v["last_week_start"], v["last_week_end"]) == ("2026-12-28", "2026-12-21", "2026-12-27")
assert (v["this_month_start"], v["last_month_start"], v["last_month_end"]) == ("2027-01-01", "2026-12-01", "2026-12-31")
assert v["last_fire_time"] == "2026-12-01T08:00:00+08:00"
def test_leap_february_ends_on_the_29th():
v = values(datetime(2028, 3, 1, 1, 0, tzinfo=UTC), cron="0 9 1 * *")
assert (v["last_month_start"], v["last_month_end"]) == ("2028-02-01", "2028-02-29")
def test_same_moment_in_two_timezones():
"""UTC 2026-10-04 20:00:上海已经是周一 04:00,纽约还是周日 16:00"""
moment = datetime(2026, 10, 4, 20, 0, tzinfo=UTC)
shanghai = values(moment, "Asia/Shanghai", "0 4 * * *")
new_york = values(moment, "America/New_York", "0 16 * * *")
assert (shanghai["today"], shanghai["this_week_start"]) == ("2026-10-05", "2026-10-05")
assert (new_york["today"], new_york["this_week_start"]) == ("2026-10-04", "2026-09-28")
assert shanghai["fire_time"] == "2026-10-05T04:00:00+08:00"
assert new_york["fire_time"] == "2026-10-04T16:00:00-04:00"
def test_fire_time_drops_sub_seconds():
"""立即运行的触发时间是点下去的那一刻,写进输入时只到秒"""
v = values(datetime(2026, 10, 5, 3, 4, 5, 678901, tzinfo=UTC))
assert v["fire_time"] == "2026-10-05T11:04:05+08:00"
# --------------------------------------------------------------------------
# 渲染与校验
# --------------------------------------------------------------------------
def test_render_inputs():
v = values(datetime(2026, 10, 5, 1, 0, tzinfo=UTC))
out = service.render_inputs({
"stat_date": "{{ schedule.yesterday }}",
"week": "{{schedule.last_week_start}}~{{ schedule.last_week_end }}",
"region": "华东",
"tag": "{{ schedule.today | upper }}",
}, v)
assert out == {"stat_date": "2026-10-04", "week": "2026-09-28~2026-10-04", "region": "华东", "tag": "2026-10-05"}
def test_valid_templates_pass():
assert service.check_template({"a": "{{ schedule.today }}", "b": "固定值", "c": "{{ schedule.fire_time | trim }}"}) == {
"a": "{{ schedule.today }}", "b": "固定值", "c": "{{ schedule.fire_time | trim }}"}
assert service.check_template(None) == {}
@pytest.mark.parametrize("template, fragments", [
({"stat_date": "{{ schedule.yesterdy }}"}, ["stat_date", "schedule.yesterdy", "schedule.yesterday"]),
({"stat_date": "{{ input.day }}"}, ["stat_date", "input.day"]),
({"stat_date": "{{ schedule.today"}, ["stat_date", "成对"]),
({"stat_date": "schedule.today }}"}, ["stat_date", "成对"]),
({"stat_date": "{{ }}"}, ["stat_date", "空的"]),
({"stat_date": "{{ schedule.today | shout }}"}, ["stat_date", "shout", "过滤器"]),
({"stat_date": 20261005}, ["stat_date", "文本"]),
({"": "{{ schedule.today }}"}, ["字段名"]),
(["{{ schedule.today }}"], ["输入模板"]),
])
def test_bad_templates_explain_in_chinese(template, fragments):
with pytest.raises(TemplateError) as caught:
service.check_template(template)
for fragment in fragments:
assert fragment in str(caught.value), str(caught.value)
def test_variable_catalog():
items = service.variables(datetime(2026, 10, 5, 1, 0, tzinfo=UTC), "Asia/Shanghai")
names = [i["name"] for i in items]
assert names == [f"schedule.{key}" for key in (
"today", "yesterday", "this_week_start", "last_week_start", "last_week_end",
"this_month_start", "last_month_start", "last_month_end", "fire_time", "last_fire_time")]
by_name = {i["name"]: i for i in items}
assert by_name["schedule.yesterday"] == {"name": "schedule.yesterday", "label": "昨天(YYYY-MM-DD)",
"example": "2026-10-04"}
assert all(i["label"] and i["example"] for i in items)
# --------------------------------------------------------------------------
# 和工作流入口字段对照
# --------------------------------------------------------------------------
def graph(*fields: dict) -> dict:
return {
"nodes": [
{"id": "start", "type": "input", "position": {"x": 0, "y": 0},
"data": {"label": "输入", "config": {"fields": list(fields)}}},
{"id": "out", "type": "output", "position": {"x": 300, "y": 0},
"data": {"label": "成果", "config": {"fields": [{"name": "r", "value": "完成"}]}}},
],
"edges": [{"source": "start", "target": "out"}],
}
def test_fields_of_a_graph():
g = graph({"name": "stat_date", "required": True}, {"name": "region", "default": "华东"})
assert [f["name"] for f in service.input_fields(g)] == ["stat_date", "region"]
assert service.input_fields({"nodes": "坏掉的图"}) == []
def test_unknown_field_names_are_refused():
fields = service.input_fields(graph({"name": "stat_date"}, {"name": "region"}))
with pytest.raises(TemplateError) as caught:
service.check_fields({"stat_dat": "{{ schedule.yesterday }}"}, fields, "门店周报")
assert "stat_dat" in str(caught.value) and "门店周报" in str(caught.value) and "stat_date" in str(caught.value)
def test_missing_required_inputs_are_refused_only_when_asked():
fields = service.input_fields(graph({"name": "stat_date", "required": True},
{"name": "region", "required": True, "default": "华东"}))
with pytest.raises(TemplateError) as caught:
service.check_fields({}, fields, "门店周报")
assert "stat_date" in str(caught.value) and "必填" in str(caught.value)
# 预览时还在填,不查缺的;有默认值的必填项不算缺
service.check_fields({}, fields, "门店周报", require=False)
service.check_fields({"stat_date": "{{ schedule.yesterday }}"}, fields, "门店周报")
def test_graph_without_declared_fields_accepts_any_name():
"""入口没声明字段时输入是开放的:运行时传什么键都收"""
service.check_fields({"anything": "x"}, service.input_fields(graph()), "门店周报")
+341
View File
@@ -0,0 +1,341 @@
"""定时任务的调度循环(app/scheduler/loop.py、service.fire_once)。
- 到点只发起一次:条件 UPDATE 认领(WHERE next_run_at = 旧值)并推进到下一次,两拍并发也只有一拍认领得到;
触发记录 (任务, fire_at, kind) 唯一,撞上约束的不再发起
- 发起走 engine/launch.py 的 launch_run:记在「定时任务:<名字>」名下、带 schedule_id,输入按 fire_at 渲染;
正式运行用当前发布版本,没有发布版本被拒,拒绝的原话记成 failed_to_start;别的异常记通用说明、详情进日志
- 上一次的运行还没结束(排队、运行中、停在审批 / 挂起都算)记 skipped_overlap
- 错过的触发:最近一次在宽限内补一次(kind=misfire),更早的积压只记一条跳过;最近一次也超出宽限就记一条
skipped_misfire,推进到未来的下一次,不补积压
- start / stop:起一个 asyncio 任务按拍执行,stop 干净地停下;AGENTLAB_SCHEDULER 关着时 start 不起循环
工作流、字段、任务名都是虚构的。
"""
from __future__ import annotations
import asyncio
import logging
import uuid
from datetime import datetime, timedelta, timezone
import pytest
from sqlalchemy import delete, func, select
from app import scheduler
from app.core.config import Settings
from app.db.base import SessionLocal
from app.db.models import Run, Schedule, ScheduleFire, Workflow, WorkflowVersion
from app.engine.runner import run_manager
from app.scheduler import loop, service
UTC = timezone.utc
#: 上海 2026-10-05(周一)09:00
NINE = datetime(2026, 10, 5, 1, 0, tzinfo=UTC)
@pytest.fixture(autouse=True)
async def engine_up():
await run_manager.setup()
async with SessionLocal() as session:
await session.execute(delete(Schedule))
await session.commit()
yield
await run_manager.shutdown()
def node(nid, ntype, **config):
return {"id": nid, "type": ntype, "position": {"x": 0, "y": 0}, "data": {"label": nid, "config": config}}
def graph(text: str) -> dict:
return {
"nodes": [node("start", "input", fields=[{"name": "stat_date", "required": True}]),
node("out", "output", fields=[{"name": "r", "value": f"{text} {{{{ input.stat_date }}}}"}])],
"edges": [{"source": "start", "target": "out"}],
}
async def workflow(*, published: bool = True, canvas: str = "画布", snapshot: str = "发布版") -> str:
async with SessionLocal() as session:
wf = Workflow(name=f"门店周报-{uuid.uuid4().hex[:6]}", graph=graph(canvas),
status="published" if published else "draft", published_version=1 if published else None)
session.add(wf)
await session.flush()
session.add(WorkflowVersion(workflow_id=wf.id, version=1, graph=graph(snapshot)))
await session.commit()
return wf.id
async def schedule(workflow_id: str, *, cron: str = "0 9 * * *", next_run_at: datetime | None = NINE,
run_class: str = "formal", grace: int = 3600, enabled: bool = True, name: str = "周一早报") -> str:
async with SessionLocal() as session:
row = Schedule(name=name, workflow_id=workflow_id, cron=cron, timezone="Asia/Shanghai", run_class=run_class,
input_template={"stat_date": "{{ schedule.yesterday }}"}, enabled=enabled,
misfire_grace_s=grace, next_run_at=next_run_at)
session.add(row)
await session.commit()
return row.id
async def fires(schedule_id: str) -> list[ScheduleFire]:
async with SessionLocal() as session:
return list((await session.execute(
select(ScheduleFire).where(ScheduleFire.schedule_id == schedule_id).order_by(ScheduleFire.created_at)
)).scalars())
async def runs_of(schedule_id: str) -> list[Run]:
async with SessionLocal() as session:
return list((await session.execute(select(Run).where(Run.schedule_id == schedule_id))).scalars())
async def next_of(schedule_id: str) -> datetime | None:
async with SessionLocal() as session:
return (await session.get(Schedule, schedule_id)).next_run_at
async def settle(run_id: str) -> Run:
for _ in range(400):
async with SessionLocal() as session:
row = await session.get(Run, run_id)
if row.status in ("succeeded", "failed", "cancelled") and row.manifest_seq is not None:
await run_manager.wait_idle(run_id)
return row
await asyncio.sleep(0.03)
raise AssertionError(f"运行 {run_id} 停在 {row.status}")
# --------------------------------------------------------------------------
# 到点发起
# --------------------------------------------------------------------------
async def test_due_schedule_launches_once_and_moves_on():
sid = await schedule(await workflow())
await loop.fire_due(NINE + timedelta(seconds=10))
[fire] = await fires(sid)
assert (fire.kind, fire.status, fire.fire_at, fire.reason) == ("scheduled", "started", NINE, None)
assert fire.inputs == {"stat_date": "2026-10-04"}
run = await settle(fire.run_id)
assert run.schedule_id == sid and run.run_class == "formal" and run.status == "succeeded"
assert run.started_by == "定时任务:周一早报"
assert run.input == {"stat_date": "2026-10-04"}
# 正式运行用的是发布版本,不是画布
assert run.version == 1 and run.output == {"r": "发布版 2026-10-04"}
assert await next_of(sid) == NINE + timedelta(days=1)
# 同一拍再来一次:已经推进到明天,不再发起
await loop.fire_due(NINE + timedelta(seconds=20))
assert len(await fires(sid)) == 1 and len(await runs_of(sid)) == 1
async def test_exploratory_schedule_uses_the_canvas():
sid = await schedule(await workflow(published=False), run_class="exploratory")
await loop.fire_due(NINE + timedelta(seconds=5))
[fire] = await fires(sid)
run = await settle(fire.run_id)
assert run.run_class == "exploratory" and run.output == {"r": "画布 2026-10-04"}
async def test_two_concurrent_ticks_launch_only_once():
sid = await schedule(await workflow())
now = NINE + timedelta(seconds=3)
await asyncio.gather(loop.fire_due(now), loop.fire_due(now), loop.fire_due(now))
assert len(await fires(sid)) == 1
[run] = await runs_of(sid)
await settle(run.id)
async def test_concurrent_ticks_with_different_clocks_claim_once():
"""一拍准点、一拍晚了两分钟(会被当成补发、kind 不同、撞不上唯一约束):只有认领到的那一拍处理"""
sid = await schedule(await workflow())
await asyncio.gather(loop.fire_due(NINE + timedelta(seconds=3)), loop.fire_due(NINE + timedelta(minutes=2)))
[fire] = await fires(sid)
[run] = await runs_of(sid)
assert fire.run_id == run.id
await settle(run.id)
async def test_a_fire_already_recorded_is_not_launched_again():
"""认领之外的第二道保险:同一 (任务, fire_at, kind) 已有记录,fire_once 交回那一条,不再发起"""
sid = await schedule(await workflow())
first = await service.fire_once(sid, NINE, "scheduled")
again = await service.fire_once(sid, NINE, "scheduled")
assert again.id == first.id and len(await fires(sid)) == 1
[run] = await runs_of(sid)
await settle(run.id)
async def test_disabled_schedule_is_not_fired():
sid = await schedule(await workflow(), enabled=False)
await loop.fire_due(NINE + timedelta(seconds=5))
assert await fires(sid) == [] and await runs_of(sid) == []
@pytest.mark.parametrize("status", ["queued", "running", "interrupted"])
async def test_previous_run_still_going_means_skip(status):
wf = await workflow()
sid = await schedule(wf)
async with SessionLocal() as session:
busy = Run(workflow_id=wf, workflow_name="门店周报", status=status, schedule_id=sid, run_class="formal")
session.add(busy)
await session.commit()
await loop.fire_due(NINE + timedelta(seconds=5))
[fire] = await fires(sid)
assert (fire.status, fire.run_id) == ("skipped_overlap", None)
assert busy.id[:8] in fire.reason and "跳过" in fire.reason
assert [r.id for r in await runs_of(sid)] == [busy.id]
assert await next_of(sid) == NINE + timedelta(days=1)
# --------------------------------------------------------------------------
# 错过的触发
# --------------------------------------------------------------------------
async def test_missed_within_grace_is_caught_up_once_with_inputs_of_its_own_day():
"""服务停到 00:30(上海 10 月 6 日)才起来:补一次 9 点那一次,昨天还是 10 月 4 日"""
sid = await schedule(await workflow(), grace=86400)
late = NINE + timedelta(hours=15, minutes=30)
await loop.fire_due(late)
[fire] = await fires(sid)
assert (fire.kind, fire.status, fire.fire_at) == ("misfire", "started", NINE)
assert fire.inputs == {"stat_date": "2026-10-04"}
await settle(fire.run_id)
assert await next_of(sid) == NINE + timedelta(days=1)
async def test_backlog_is_skipped_and_only_the_latest_is_caught_up():
"""每小时一次,停了三个多小时:01–03 点的积压记一条跳过,04 点那次在宽限内补发"""
sid = await schedule(await workflow(), cron="0 * * * *", grace=3600)
await loop.fire_due(NINE + timedelta(hours=3, minutes=20))
skipped, caught_up = await fires(sid)
assert (skipped.kind, skipped.status, skipped.fire_at, skipped.run_id) == ("misfire", "skipped_misfire", NINE, None)
assert "2026-10-05 09:00" in skipped.reason and "2026-10-05 11:00" in skipped.reason
assert (caught_up.kind, caught_up.status, caught_up.fire_at) == ("misfire", "started", NINE + timedelta(hours=3))
assert len(await runs_of(sid)) == 1
await settle(caught_up.run_id)
assert await next_of(sid) == NINE + timedelta(hours=4)
async def test_missed_beyond_grace_is_skipped_without_launching():
sid = await schedule(await workflow(), grace=600)
await loop.fire_due(NINE + timedelta(hours=2))
[fire] = await fires(sid)
assert (fire.kind, fire.status, fire.fire_at, fire.run_id) == ("misfire", "skipped_misfire", NINE, None)
assert "10 分钟" in fire.reason and "2026-10-05 09:00" in fire.reason
assert await runs_of(sid) == []
assert await next_of(sid) == NINE + timedelta(days=1)
async def test_days_of_downtime_leave_one_skip_record():
sid = await schedule(await workflow(), grace=600, next_run_at=NINE - timedelta(days=4))
await loop.fire_due(NINE + timedelta(hours=2))
[fire] = await fires(sid)
assert (fire.status, fire.fire_at) == ("skipped_misfire", NINE)
assert "2026-10-01 09:00" in fire.reason and "2026-10-05 09:00" in fire.reason
assert await runs_of(sid) == [] and await next_of(sid) == NINE + timedelta(days=1)
async def test_on_time_fire_ignores_a_small_grace():
"""宽限写 0 也不影响准点的触发:拍与拍之间的十几秒不算错过"""
sid = await schedule(await workflow(), grace=0)
await loop.fire_due(NINE + timedelta(seconds=14))
[fire] = await fires(sid)
assert (fire.kind, fire.status) == ("scheduled", "started")
await settle(fire.run_id)
# --------------------------------------------------------------------------
# 发起被拒、出错
# --------------------------------------------------------------------------
async def test_formal_schedule_without_published_version_records_the_refusal():
wf = await workflow(published=False)
sid = await schedule(wf)
await loop.fire_due(NINE + timedelta(seconds=5))
[fire] = await fires(sid)
async with SessionLocal() as session:
name = (await session.get(Workflow, wf)).name
assert (fire.status, fire.run_id) == ("failed_to_start", None)
assert fire.reason == f"「{name}」还没有发布版本,请先在编排页发布"
assert await runs_of(sid) == []
assert await next_of(sid) == NINE + timedelta(days=1)
async def test_deleted_workflow_records_the_refusal():
sid = await schedule(f"gone{uuid.uuid4().hex[:8]}")
await loop.fire_due(NINE + timedelta(seconds=5))
[fire] = await fires(sid)
assert (fire.status, fire.reason) == ("failed_to_start", "工作流不存在,可能已被删除")
async def test_unexpected_errors_record_a_generic_reason(monkeypatch, caplog):
from app.engine import launch
async def explode(*args, **kwargs):
raise RuntimeError("库连接断开:sqlite busy")
monkeypatch.setattr(launch, "launch_run", explode)
sid = await schedule(await workflow())
with caplog.at_level(logging.ERROR):
await loop.fire_due(NINE + timedelta(seconds=5))
[fire] = await fires(sid)
assert (fire.status, fire.reason) == ("failed_to_start", service.GENERIC_REASON)
assert "库连接断开" in caplog.text
assert await next_of(sid) == NINE + timedelta(days=1)
async def test_broken_cron_in_the_database_stops_the_schedule():
sid = await schedule(await workflow(), cron="0 25 * * *")
await loop.fire_due(NINE + timedelta(seconds=5))
[fire] = await fires(sid)
assert fire.status == "failed_to_start" and "「时」" in fire.reason
assert await next_of(sid) is None
# --------------------------------------------------------------------------
# start / stop
# --------------------------------------------------------------------------
async def test_start_does_nothing_when_switched_off():
"""测试环境 AGENTLAB_SCHEDULER=0(conftest):start 不起循环,stop 照样能调"""
assert await scheduler.start() is False
assert scheduler.running() is False
await scheduler.stop()
async def test_loop_ticks_until_stopped():
sid = await schedule(await workflow(), next_run_at=datetime.now(UTC) - timedelta(seconds=1), cron="* * * * *")
on = Settings(_env_file=None, scheduler=True)
assert await scheduler.start(interval=0.05, config=on) is True
assert scheduler.running()
for _ in range(200):
if await fires(sid):
break
await asyncio.sleep(0.02)
await scheduler.stop()
assert scheduler.running() is False
[fire] = await fires(sid)
assert fire.status == "started"
await settle(fire.run_id)
# 停下之后不再有拍:把下一次拨回过去也不会再发起
async with SessionLocal() as session:
await session.execute(Schedule.__table__.update().where(Schedule.id == sid)
.values(next_run_at=datetime.now(UTC) - timedelta(seconds=1)))
await session.commit()
await asyncio.sleep(0.2)
async with SessionLocal() as session:
assert await session.scalar(select(func.count()).select_from(ScheduleFire)
.where(ScheduleFire.schedule_id == sid)) == 1
async def test_start_twice_keeps_one_loop():
on = Settings(_env_file=None, scheduler=True)
await scheduler.start(interval=0.05, config=on)
first = loop.runner.task
await scheduler.start(interval=0.05, config=on)
assert loop.runner.task is first
await scheduler.stop()
assert first.done()
+399
View File
@@ -0,0 +1,399 @@
"""定时任务的 Webhook(app/scheduler/webhook.py):运行结束、失败、停在审批时推送一次。
- 四种格式的请求体和签名:通用 JSON(配了密钥时 X-AgentLab-Signature = HMAC-SHA256(密钥, 时间戳.请求体))、
飞书文本(timestamp + sign,sign 是以「时间戳\\n密钥」为键的 HMAC-SHA256)、企业微信 markdown(key 在地址里)、
钉钉 markdown(地址上加 timestamp 和 sign)
- 通知里有任务名、状态、出具档位、缺口条数、运行链接(对外访问地址 + /runs/{id})、封存哈希前 12 位、开始结束
时间;不放报告里的具体数字,不放失败的原始报错
- 每一拍查已发起的触发:运行状态变了、任务订阅了这个事件、这个状态还没处理过才推送;停在审批只在确有待审批时
算;结束的运行等封存好再推;没订阅、没配 Webhook 的也记下已处理,之后再配上不会补发旧的
- 失败重试 3 次(4xx 不重试),每次推送记一条 WebhookDelivery;日志和错误里只有主机名,没有地址、key、
access_token、密钥(httpx 自己的请求日志也一样)
用 httpx.MockTransport 接住请求,不连外网。任务名、地址、密钥、数字都是虚构的。
"""
from __future__ import annotations
import base64
import hashlib
import hmac
import json
import logging
import uuid
from datetime import datetime, timedelta, timezone
from urllib.parse import parse_qs, quote_plus, urlsplit
import httpx
import pytest
from sqlalchemy import delete, select
from app.core.crypto import encrypt
from app.db.base import SessionLocal
from app.db.models import Approval, Run, Schedule, ScheduleFire, Setting, WebhookDelivery
from app.scheduler import webhook
UTC = timezone.utc
NOW = datetime(2026, 10, 5, 1, 2, 3, tzinfo=UTC)
FEISHU = "https://open.feishu.cn/open-apis/bot/v2/hook/0f1e2d3c-aaaa-bbbb-cccc-9d8e7f6a5b4c"
WECOM = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=6a7b8c9d-1111-2222-3333-444455556666"
DINGTALK = "https://oapi.dingtalk.com/robot/send?access_token=f00dfacecafebabe0123456789abcdef"
GENERIC = "https://hooks.example.com/agentlab/inbox-7f3a"
SECRET = "SECdemo-not-a-real-secret-42"
class Recorder:
"""MockTransport 的处理函数:记下每个请求,按 replies 依次回应(用完了就一直回最后一个)。"""
def __init__(self, *replies):
self.requests: list[httpx.Request] = []
self.replies = list(replies) or [httpx.Response(200, json={"code": 0, "errcode": 0})]
def __call__(self, request: httpx.Request) -> httpx.Response:
self.requests.append(request)
reply = self.replies[min(len(self.requests), len(self.replies)) - 1]
if isinstance(reply, Exception):
raise reply
return reply
@pytest.fixture
def recorder(monkeypatch):
rec = Recorder()
monkeypatch.setattr(webhook, "_transport", httpx.MockTransport(rec))
monkeypatch.setattr(webhook, "RETRY_DELAYS", (0, 0, 0))
return rec
@pytest.fixture(autouse=True)
async def clean():
async with SessionLocal() as session:
await session.execute(delete(Schedule))
await session.execute(delete(Setting).where(Setting.key == "notify"))
await session.commit()
yield
def notice(**over) -> webhook.Notice:
base = dict(event="finished", schedule_id="s1", schedule_name="门店周报", timezone="Asia/Shanghai",
fire_id="f1", fire_at=datetime(2026, 10, 5, 1, 0, tzinfo=UTC), fire_kind="scheduled",
run_id="r0123456789abcdef", status="succeeded", tier="degraded", gaps=2,
run_url="https://agentlab.example.com/runs/r0123456789abcdef",
manifest_hash="a1b2c3d4e5f60718293a", started_at=datetime(2026, 10, 5, 1, 0, 3, tzinfo=UTC),
finished_at=datetime(2026, 10, 5, 1, 1, 10, tzinfo=UTC), reason=None, pending_approvals=None)
base.update(over)
return webhook.Notice(**base)
# --------------------------------------------------------------------------
# 请求体和签名
# --------------------------------------------------------------------------
def test_generic_json_carries_the_agreed_fields():
url, headers, body = webhook.build_request("generic", GENERIC, None, notice(), now=NOW)
data = json.loads(body)
assert url == GENERIC and headers["Content-Type"] == "application/json"
assert {k: data[k] for k in ("event", "schedule_name", "run_id", "status", "tier", "tier_label", "gaps",
"run_url", "manifest_hash")} == {
"event": "finished", "schedule_name": "门店周报", "run_id": "r0123456789abcdef", "status": "succeeded",
"tier": "degraded", "tier_label": "降档出具", "gaps": 2,
"run_url": "https://agentlab.example.com/runs/r0123456789abcdef", "manifest_hash": "a1b2c3d4e5f6"}
assert data["started_at"] == "2026-10-05T01:00:03+00:00" and data["finished_at"] == "2026-10-05T01:01:10+00:00"
assert "X-AgentLab-Signature" not in headers
def test_generic_signature_when_a_secret_is_set():
_, headers, body = webhook.build_request("generic", GENERIC, SECRET, notice(), now=NOW)
ts = headers["X-AgentLab-Timestamp"]
assert ts == str(int(NOW.timestamp()))
expected = hmac.new(SECRET.encode(), f"{ts}.".encode() + body, hashlib.sha256).hexdigest()
assert headers["X-AgentLab-Signature"] == f"sha256={expected}"
def test_feishu_text_and_signature():
url, _, body = webhook.build_request("feishu", FEISHU, SECRET, notice(), now=NOW)
data = json.loads(body)
assert url == FEISHU and data["msg_type"] == "text"
ts = data["timestamp"]
assert ts == str(int(NOW.timestamp()))
# 飞书的签名:以「timestamp + 换行 + 密钥」为键,对空串做 HMAC-SHA256,再 base64
key = f"{ts}\n{SECRET}".encode()
assert data["sign"] == base64.b64encode(hmac.new(key, b"", hashlib.sha256).digest()).decode()
text = data["content"]["text"]
for fragment in ("门店周报", "降档出具", "缺口 2 条", "a1b2c3d4e5f6", "/runs/r0123456789abcdef",
"2026-10-05 09:00", "2026-10-05 09:00:03", "2026-10-05 09:01:10"):
assert fragment in text, text
def test_feishu_without_secret_has_no_sign():
_, _, body = webhook.build_request("feishu", FEISHU, None, notice(), now=NOW)
assert "sign" not in json.loads(body) and "timestamp" not in json.loads(body)
def test_wecom_markdown_keeps_the_key_in_the_address():
url, _, body = webhook.build_request("wecom", WECOM, None, notice(), now=NOW)
data = json.loads(body)
assert url == WECOM and data["msgtype"] == "markdown"
assert "门店周报" in data["markdown"]["content"] and "降档出具" in data["markdown"]["content"]
def test_dingtalk_markdown_and_signed_address():
url, _, body = webhook.build_request("dingtalk", DINGTALK, SECRET, notice(), now=NOW)
data = json.loads(body)
assert data["msgtype"] == "markdown" and "门店周报" in data["markdown"]["title"]
assert "降档出具" in data["markdown"]["text"]
query = parse_qs(urlsplit(url).query)
ts = str(int(NOW.timestamp() * 1000))
assert query["access_token"] == ["f00dfacecafebabe0123456789abcdef"] and query["timestamp"] == [ts]
sign = base64.b64encode(hmac.new(SECRET.encode(), f"{ts}\n{SECRET}".encode(), hashlib.sha256).digest()).decode()
assert query["sign"] == [sign]
assert f"sign={quote_plus(sign)}" in url
def test_awaiting_approval_and_failed_to_start_texts():
waiting = webhook.message(notice(event="awaiting_approval", status="interrupted", tier=None, gaps=None,
pending_approvals=2, finished_at=None))
assert "等待审批" in waiting[0] and any("2 项" in value for _, value in waiting[1])
refused = webhook.message(notice(event="failed", status="failed_to_start", run_id=None, run_url=None,
tier=None, gaps=None, manifest_hash=None, started_at=None, finished_at=None,
reason="「门店周报」还没有发布版本,请先在编排页发布"))
assert "未能发起" in refused[0] and any("还没有发布版本" in value for _, value in refused[1])
def test_url_hint_shows_only_host_and_last_four():
assert webhook.url_hint(FEISHU) == "open.feishu.cn/…5b4c"
assert webhook.url_hint(WECOM) == "qyapi.weixin.qq.com/…6666"
assert webhook.url_hint("http://127.0.0.1:8794/hook") == "127.0.0.1:8794/…hook"
@pytest.mark.parametrize("url", ["", "open.feishu.cn/hook", "ftp://x.example.com/a", "https://", "https://a b.com/x"])
def test_bad_addresses_are_refused(url):
with pytest.raises(ValueError) as caught:
webhook.check_url(url)
assert "Webhook 地址" in str(caught.value)
# --------------------------------------------------------------------------
# 推送与重试
# --------------------------------------------------------------------------
async def test_success_on_first_try(recorder):
outcome = await webhook.send("feishu", FEISHU, SECRET, notice())
assert (outcome.ok, outcome.http_status, outcome.attempts, outcome.error) == (True, 200, 1, None)
assert len(recorder.requests) == 1 and str(recorder.requests[0].url) == FEISHU
async def test_server_errors_are_retried(recorder):
recorder.replies = [httpx.Response(502), httpx.ReadTimeout("timed out"), httpx.Response(200, json={"code": 0})]
outcome = await webhook.send("feishu", FEISHU, None, notice())
assert (outcome.ok, outcome.attempts) == (True, 3)
async def test_gives_up_after_three_retries(recorder):
recorder.replies = [httpx.Response(500)]
outcome = await webhook.send("generic", GENERIC, None, notice())
assert (outcome.ok, outcome.http_status, outcome.attempts) == (False, 500, 4)
assert "HTTP 500" in outcome.error
async def test_client_errors_are_not_retried(recorder):
recorder.replies = [httpx.Response(404)]
outcome = await webhook.send("generic", GENERIC, None, notice())
assert (outcome.ok, outcome.http_status, outcome.attempts) == (False, 404, 1)
async def test_platform_error_code_counts_as_failure(recorder):
recorder.replies = [httpx.Response(200, json={"code": 19021, "msg": "sign match fail or timestamp is not within one hour"})]
outcome = await webhook.send("feishu", FEISHU, SECRET, notice())
assert not outcome.ok and outcome.error.startswith("open.feishu.cn 返回错误码 19021:sign match fail")
recorder.replies = [httpx.Response(200, json={"errcode": 310000, "errmsg": "sign not match"})]
assert "310000" in (await webhook.send("dingtalk", DINGTALK, SECRET, notice())).error
async def test_connection_errors_name_only_the_host(recorder):
recorder.replies = [httpx.ConnectError(f"cannot reach {WECOM}")]
outcome = await webhook.send("wecom", WECOM, None, notice())
assert not outcome.ok and outcome.attempts == 4
assert "qyapi.weixin.qq.com" in outcome.error and "6a7b8c9d" not in outcome.error
async def test_logs_never_contain_the_address_key_or_secret(recorder, caplog):
caplog.set_level(logging.DEBUG)
recorder.replies = [httpx.Response(500, json={"errmsg": f"bad token {DINGTALK}"}), httpx.Response(200, json={"errcode": 0})]
await webhook.send("dingtalk", DINGTALK, SECRET, notice())
await webhook.send("feishu", FEISHU, SECRET, notice())
text = caplog.text
assert "oapi.dingtalk.com" in text and "open.feishu.cn" in text # 主机名照常记
for leaked in (DINGTALK, FEISHU, "f00dfacecafebabe0123456789abcdef", "0f1e2d3c-aaaa", SECRET, "access_token="):
assert leaked not in text, leaked
# --------------------------------------------------------------------------
# 每一拍的通知扫描
# --------------------------------------------------------------------------
async def make(*, run_status: str | None = "succeeded", events=("finished", "failed", "awaiting_approval"),
fmt: str = "generic", url: str | None = GENERIC, secret: str | None = None, sealed: bool = True,
fire_status: str = "started", output: dict | None = None, reason: str | None = None):
"""建一个配了 Webhook 的任务、一次触发和它发起的运行(运行不真的执行,状态直接写库)。"""
async with SessionLocal() as session:
sched = Schedule(name="门店周报", workflow_id="wf-demo", cron="0 9 * * 1", timezone="Asia/Shanghai",
webhook_format=fmt if url else None, webhook_url=encrypt(url) if url else None,
webhook_secret=encrypt(secret) if secret else None, webhook_events=list(events))
session.add(sched)
await session.flush()
run = None
if run_status:
now = datetime.now(UTC)
run = Run(workflow_id=None, workflow_name="门店周报", status=run_status, schedule_id=sched.id,
run_class="formal", started_at=now - timedelta(minutes=1),
finished_at=now if run_status in ("succeeded", "failed", "cancelled") else None,
manifest_hash=("c0ffee" * 10) if sealed else None,
output=output if output is not None else {
"report": "本周销售额 98765.43 元,同比增长 12.5%",
"_issuance": {"tier": "formal", "gaps": []}})
session.add(run)
await session.flush()
fire = ScheduleFire(schedule_id=sched.id, fire_at=datetime.now(UTC).replace(microsecond=0),
kind="scheduled", status=fire_status, run_id=run.id if run else None, reason=reason)
session.add(fire)
await session.commit()
return sched.id, fire.id, run.id if run else None
async def fire_row(fire_id: str) -> ScheduleFire:
async with SessionLocal() as session:
return await session.get(ScheduleFire, fire_id)
async def deliveries(fire_id: str) -> list[WebhookDelivery]:
async with SessionLocal() as session:
return list((await session.execute(
select(WebhookDelivery).where(WebhookDelivery.fire_id == fire_id).order_by(WebhookDelivery.created_at)
)).scalars())
async def set_run(run_id: str, **values) -> None:
async with SessionLocal() as session:
await session.execute(Run.__table__.update().where(Run.id == run_id).values(**values))
await session.commit()
async def test_finished_run_is_pushed_once(recorder):
async with SessionLocal() as session:
session.add(Setting(key="notify", value={"public_base_url": "https://agentlab.example.com"}))
await session.commit()
_, fire_id, run_id = await make()
assert await webhook.notify_due() == 1
[req] = recorder.requests
data = json.loads(req.content)
assert (data["event"], data["status"], data["tier"], data["gaps"]) == ("finished", "succeeded", "formal", 0)
assert data["run_url"] == f"https://agentlab.example.com/runs/{run_id}"
assert data["manifest_hash"] == ("c0ffee" * 2)
# 报告里的数字不进通知
assert "98765.43" not in req.content.decode() and "12.5" not in req.content.decode()
[delivery] = await deliveries(fire_id)
assert (delivery.event, delivery.status, delivery.http_status, delivery.attempts, delivery.run_id) == (
"finished", "ok", 200, 1, run_id)
assert (await fire_row(fire_id)).notified_status == "succeeded"
# 下一拍:同一状态不再推送
assert await webhook.notify_due() == 0
assert len(recorder.requests) == 1
async def test_no_public_address_means_no_link(recorder):
await make()
await webhook.notify_due()
assert json.loads(recorder.requests[0].content)["run_url"] is None
async def test_failed_run_and_failed_to_start(recorder):
_, failed_fire, _ = await make(run_status="failed", output={})
_, refused_fire, _ = await make(run_status=None, fire_status="failed_to_start",
reason="「门店周报」还没有发布版本,请先在编排页发布")
assert await webhook.notify_due() == 2
bodies = sorted((json.loads(r.content) for r in recorder.requests), key=lambda b: b["status"])
assert [(b["event"], b["status"]) for b in bodies] == [("failed", "failed"), ("failed", "failed_to_start")]
assert bodies[1]["run_id"] is None and "还没有发布版本" in bodies[1]["reason"]
assert (await fire_row(failed_fire)).notified_status == "failed"
assert (await fire_row(refused_fire)).notified_status == "failed_to_start"
async def test_unsubscribed_event_is_marked_but_not_pushed(recorder):
_, fire_id, _ = await make(events=("failed",))
assert await webhook.notify_due() == 0
assert recorder.requests == [] and await deliveries(fire_id) == []
assert (await fire_row(fire_id)).notified_status == "succeeded"
async def test_without_webhook_old_fires_are_not_pushed_later(recorder):
sid, fire_id, _ = await make(url=None)
await webhook.notify_due()
assert (await fire_row(fire_id)).notified_status == "succeeded"
async with SessionLocal() as session:
await session.execute(Schedule.__table__.update().where(Schedule.id == sid).values(
webhook_format="generic", webhook_url=encrypt(GENERIC), webhook_events=["finished"]))
await session.commit()
assert await webhook.notify_due() == 0 and recorder.requests == []
async def test_cancelled_run_is_not_pushed(recorder):
_, fire_id, _ = await make(run_status="cancelled")
await webhook.notify_due()
assert recorder.requests == [] and (await fire_row(fire_id)).notified_status == "cancelled"
async def test_waits_for_the_seal_before_pushing(recorder):
_, fire_id, run_id = await make(sealed=False)
assert await webhook.notify_due() == 0 and (await fire_row(fire_id)).notified_status is None
await set_run(run_id, manifest_hash="beef" * 16)
assert await webhook.notify_due() == 1
assert json.loads(recorder.requests[0].content)["manifest_hash"] == "beef" * 3
async def test_awaiting_approval_only_with_a_real_pending_approval(recorder):
"""服务重启挂起的运行也是 interrupted,但没有待审批:不推。有了待审批推一次,批完跑完再推完成"""
_, fire_id, run_id = await make(run_status="interrupted")
assert await webhook.notify_due() == 0 and (await fire_row(fire_id)).notified_status is None
async with SessionLocal() as session:
session.add(Approval(run_id=run_id, node_id="gate", title="审核周报", status="pending"))
await session.commit()
assert await webhook.notify_due() == 1
data = json.loads(recorder.requests[0].content)
assert (data["event"], data["status"], data["pending_approvals"]) == ("awaiting_approval", "interrupted", 1)
assert await webhook.notify_due() == 0
await set_run(run_id, status="succeeded", finished_at=datetime.now(UTC), manifest_hash="ab" * 32)
assert await webhook.notify_due() == 1
assert [json.loads(r.content)["event"] for r in recorder.requests] == ["awaiting_approval", "finished"]
assert [d.event for d in await deliveries(fire_id)] == ["awaiting_approval", "finished"]
async def test_failed_delivery_is_recorded_without_secrets(recorder):
recorder.replies = [httpx.Response(503, text=f"upstream {DINGTALK} down")]
_, fire_id, _ = await make(fmt="dingtalk", url=DINGTALK, secret=SECRET)
await webhook.notify_due()
[delivery] = await deliveries(fire_id)
assert (delivery.status, delivery.http_status, delivery.attempts) == ("failed", 503, 4)
assert "HTTP 503" in delivery.error
for leaked in (DINGTALK, "f00dfacecafebabe", SECRET):
assert leaked not in delivery.error
# 推送失败也算这个状态处理过了:不会每一拍都再试一遍
assert (await fire_row(fire_id)).notified_status == "succeeded"
async def test_test_message(recorder):
sid, _, _ = await make(fmt="feishu", url=FEISHU, secret=SECRET, run_status=None, fire_status="skipped_overlap")
result = await webhook.send_test(sid)
assert result == {"ok": True, "http_status": 200, "message": "测试消息已送达(HTTP 200)"}
data = json.loads(recorder.requests[0].content)
assert "测试" in data["content"]["text"] and "门店周报" in data["content"]["text"] and data["sign"]
async with SessionLocal() as session:
[row] = (await session.execute(select(WebhookDelivery).where(WebhookDelivery.schedule_id == sid))).scalars()
assert (row.event, row.status, row.fire_id, row.attempts) == ("test", "ok", None, 1)
recorder.replies = [httpx.ConnectError("refused")]
failed = await webhook.send_test(sid)
assert failed["ok"] is False and failed["http_status"] is None and "open.feishu.cn" in failed["message"]
+77
View File
@@ -0,0 +1,77 @@
"""通知设置(api/settings.py 的 notify 一组):定时任务的 Webhook 里拼运行链接用的对外访问地址。
- 默认没填(null),通知里就不附运行链接
- 只收 http(s) 开头的完整地址;末尾的 / 去掉、首尾空白去掉,空串当没填;带 ? 或 # 的拒收
- 写错整个请求回 422、detail 是中文,一项都不落库
"""
from __future__ import annotations
import pytest
from httpx import ASGITransport, AsyncClient
from sqlalchemy import delete
from app.api.settings import NOTIFY_GROUP, notify_settings, notify_values
from app.db.base import SessionLocal
from app.db.models import Setting
from app.main import app
@pytest.fixture(autouse=True)
async def clean():
async with SessionLocal() as session:
await session.execute(delete(Setting).where(Setting.key.in_([NOTIFY_GROUP, "run"])))
await session.commit()
yield
def client() -> AsyncClient:
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
async def test_default_is_no_link():
async with client() as c:
body = (await c.get("/api/settings")).json()
assert body["notify"] == {"public_base_url": None}
async with SessionLocal() as session:
assert await notify_settings(session) == {"public_base_url": None}
@pytest.mark.parametrize("given, stored", [
("https://agentlab.example.com/", "https://agentlab.example.com"),
(" http://10.20.30.40:8080 ", "http://10.20.30.40:8080"),
("https://intra.example.com/agentlab/", "https://intra.example.com/agentlab"),
("", None),
(None, None),
])
async def test_saved_and_normalized(given, stored):
async with client() as c:
put = await c.put("/api/settings", json={"values": {NOTIFY_GROUP: {"public_base_url": given}}})
assert put.status_code == 200, put.text
assert put.json()["notify"] == {"public_base_url": stored}
assert (await c.get("/api/settings")).json()["notify"] == {"public_base_url": stored}
async with SessionLocal() as session:
assert await notify_settings(session) == {"public_base_url": stored}
@pytest.mark.parametrize("value, fragment", [
({"public_base_url": "agentlab.example.com"}, "http:// 或 https://"),
({"public_base_url": "ftp://files.example.com"}, "http:// 或 https://"),
({"public_base_url": "https://"}, "http:// 或 https://"),
({"public_base_url": 8080}, "http:// 或 https://"),
({"public_base_url": "https://agentlab.example.com/?from=bot"}, "? 或 #"),
({"public_url": "https://agentlab.example.com"}, "不支持「public_url」"),
("https://agentlab.example.com", "格式有误"),
])
async def test_invalid_values_are_refused_in_chinese(value, fragment):
async with client() as c:
put = await c.put("/api/settings", json={"values": {NOTIFY_GROUP: value, "run": {"stream_tokens": False}}})
assert put.status_code == 422
assert fragment in put.json()["detail"]
assert "对外访问地址" in put.json()["detail"] or "通知" in put.json()["detail"]
# 先查后写:同一请求里别的组也没有落库
assert (await c.get("/api/settings")).json()["run"]["stream_tokens"] is True
def test_broken_stored_value_reads_as_unset():
assert notify_values({"public_base_url": "不是地址"}) == {"public_base_url": None}
assert notify_values("坏掉的") == {"public_base_url": None}