feat(sswflow): 实现 FlowSchedule 周期调度器(service+ticker+接口+前端页+单测)

- flowschedule.service.ts: 8 方法(listByFlow/setEnabled/listDue/previewNextFires/
  computeNextFire/triggerNow/fire/doFire),单条失败隔离,失败仍推进 nextFireTime
- flowschedule.ticker.ts: 30s 轮询(首 5s),到点自动 start run,与 Quartz 解耦
- flowschedule.controller.ts: 补 ListByFlow/SetEnabled/Preview/TriggerNow 四端点
- sswflow.module.ts: 注册 Ticker 为 provider
- schedule/spring-cron.ts: Spring 6 位 cron(秒 分 时 日 月 周)本地时区解析
- 前端 FlowSchedule.tsx: 定制页(启用停用/预览/立即触发/cron 录入)
- scripts/test-spring-cron.sh: 13 断言;sswflow-smoke.sh 增调度段 15 项
- MEMORY.md: 精简超限记忆,注明 FlowSchedule 已闭环
This commit is contained in:
admin committed 2026-11-11 17:35:43 +08:00
1 parent 5501a8a2f2
commit b3ff11dd6d
10 files changed
+863 -199

No files matched your search

+28 -178
View File
@@ -1,184 +1,34 @@
# ssw-mpc-flow 项目长期记忆
# ssw-mpc-flow 项目记忆(实测事实 + 坑)
> 范围:`/Users/xs/Desktop/workspace/ssw-mpc-flow`(隐私计算编排,JNPF Lite 框架)
> **远端**:`http://192.168.1.18:13300/ssw/ssw-mpc-flow`(Gitea 1.26.1,用户空间 `ssw`,分支 `main`)
> 推送凭据走 **xop**(`git_local_user`/`git_local_pass`)+ `GIT_ASKPASS`,**别把密码写进 remote URL**。
>
> ★ **架构 / 铁律 / API 契约 / 环境变量表 / 验证命令 一律看仓库根 `CLAUDE.md`**(本文件不重复)。
> 本文件只留 **实测事实与坑**。详细流水见 `.workbuddy/memory/YYYY-MM-DD.md`。
> 架构/铁律/API/环境变量/验证命令 见仓库根 CLAUDE.md。本文件只留实测事实与坑,不重复。
## 定位
## 远端 & 凭据
- 远端 `http://192.168.1.18:13300/ssw/ssw-mpc-flow`(Gitea,空间 ssw,分支 main)。
- 推送走 xop:`git_local_user`/`git_local_pass`(GIT_ASKPASS),密码别写进 remote URL。
`git_ssw_*`/`jnpf_git_*` 不通。
从 `../ssw-mvp` 抽 sswflow(隐私计算编排)域做独立项目:框架换 **JNPF Lite**
(NestJS + TypeORM + PGlite + React/Vite),执行底座换 **`../ssw-mpc`**(Rust CLI)。
**不修改 ssw-mpc Rust 源码**。设备注册 / 链上存证**不在 sswflow 域**,
本项目直接对接 ssw-mpc 真实接口,不是移植 ssw-mvp 旧实现。
## ★ 真机实测(2026-11-11)
三台:海光 192.168.1.102(bob,csv,兼控制面3020) / AMD 192.168.1.7(alice,snp) / zynq 192.168.1.233(carol,armv7,3011)。
- ★ zynq 已能注册节点(上游 f676a6a 修复 parse_kind 只认 snp/csv)。板端 `--node-platform none`(不写 optee,zynq 无 OP-TEE)。
- ★ 控制面二进制也必须升级(否则自报 400);macOS 交叉编译 `cargo zigbuild --target x86_64-unknown-linux-gnu --features vendored`(OPENSSL_STATIC=1 + `--config 'build.rustc-wrapper=""'`)。
- ★ 控制面重启必须带共享密钥:`export MPC_HOSTD_SHARED_SECRET="$(cat cluster.secret)"`(走 argv 会进 ps)。
- zynq 是 BusyBox 1.24.1:无 setsid/timeout/python3/base64/openssl;传二进制用 tar.gz 管道;后台起 `nohup … & </dev/null`;`head` 只支持 `-n`;不能用 `date +%s%N`。
- armv7 交叉:`--no-default-features --features host-only`(musl 静态;板子 glibc 2.26,gnu 产物跑不起来)。
- xop 纪律:stdin 必须 `</dev/null`(否则等 Touch ID→exit 137);zynq 登录名 `root`,SSH 用 `-l "$Z_USER"`。
## ★ 真机实测事实(2026-11-11)
### 三台主机
| 主机 | 平台 | 端口 | ssw-mpc | 备注 |
|---|---|---|---|---|
| 192.168.1.102 | 海光 csv | 3010/3020 | `/tmp/mpc-cluster/mpc`(8.06MB,**已升级**) | `--node-site bob`,兼控制面 3020 |
| 192.168.1.7 | AMD snp | 3010 | `/tmp/mpc-tee-run-attestpair/` | `--node-site alice`,含我们的 `serve.py` KBS |
| 192.168.1.233 | zynq armv7 | 3011 | `/tmp/mpc-hostd/mpc`(2.79MB armv7 静态) | `--node-site carol`,**platform=none** |
- **★ zynq 无 TEE 环境(实测)**:`# CONFIG_TEE is not set`、无 `/dev/tee0`、
无 `/lib/optee_armtz`、无 optee 内核模块、设备树无 secure/firmware 节点 ⇒
**OP-TEE 跑不了,要换启动链**(无第二台板子可试,风险极高)。
「之前跑通 OP-TEE」指的是 **`mpc` 二进制上板自检,不是 OP-TEE 本身**。
- **★ zynq 已能作为节点注册(已实测通过)**:上游 commit `f676a6a` 修复了
`schedule.rs::parse_kind` 只认 snp/csv 的问题 ⇒ `optee`/`none`/`tdx` 均可登记。
板端跑 `mpc hostd --node-platform none --node-site carol --node-host 192.168.1.233`
⇒ 控制面 `/nodes` 出现 `[email protected]`。
**平台写 `none` 不写 `optee`**:zynq 连 OP-TEE 都没有,写 optee 是谎报平台。
★ **控制面二进制也必须升级**(否则自报 400);macOS 交叉编译用
`cargo zigbuild --target x86_64-unknown-linux-gnu --features vendored`
(`OPENSSL_STATIC=1` + `--config 'build.rustc-wrapper=""'` 关 sccache)。
★ **控制面重启必须带共享密钥**:`export MPC_HOSTD_SHARED_SECRET="$(cat cluster.secret)"`
(密钥走 argv 会进 `ps`)。
- **★ zynq 板端硬坑**:① **必须用绝对路径**(SSH 非交互 PATH 只有 `/usr/bin:/bin`,
`mpc` 在 `/usr/local/bin/` ⇒ 直调 "command not found",且 `busybox time` 显示 0.00s 假数据);
② **不能用 `date +%s%N`**(BusyBox 不支持 `%N`);③ **`/proc/uptime` 只有 0.01s 精度**
⇒ 测性能要循环 N 次取总量。
- **★ zynq 是 BusyBox 1.24.1**:无 gcc/make/python3/base64/openssl/**setsid**/**timeout**
⇒ 传二进制用 **tar.gz 管道**(`cat x.tgz | ssh "cat > x.tgz && tar xzf x.tgz"`);
后台起进程用 **`nohup … &` + stdin /dev/null**(不是 setsid);`head` 只支持 `-n` 不支持 `-c`。
- **★ armv7 交叉编译**:`--no-default-features --features host-only`(hostd 不含 OpenSSL,
musl 静态链得出来;默认 `control-plane` 会被 `compile_error!` 硬拒)。
板子 glibc 2.26 ⇒ **gnu 动态产物在板子上跑不起来**(`GLIBC_2.28 not found`)。
- **★ 本机 `nc -z` 端口扫描会报假阴性/假阳性**(受代理影响)⇒ 用 **python socket** 实测。
### ★ 多方会话协议契约(实测踩过)
- **三方必须网状连接**:`--listen + --peers`(`--connect` 只连一个对端,n>2 非法)。
`--peers` 格式 `name=addr,`,**必须含全部站点**(含本方那格,本方那格被跳过)。
- **party 编号 = 站点名字典序**(alice=0/bob=1/carol=2);**小编号主动连大编号**
⇒ 启动顺序要 **carol → bob → alice**(先起最高编号,只 accept)。
填错编号**不报错**,只会把帧送到错误的人手里。
- **密态第二通道 = `--listen` 端口 +1**,`--peers` 表里每个地址也要 +1(`bump_peers`)。
- **LR 契约**:`--col-blocks` 一一对应铺满 `0..d_total`;`--data-x` 长度 = ids × 本方列数
⇒ **给全量行**,交集由 PSI 运行时求;**只有 `--label-owner` 能给 `--data-y`**。
- **真实实现是「先全发再全收」**(多方纪律;发一个收一个会在 socket 缓冲写满时互等)。
- **★ 本地密态基准搭法**:cargo 全工作区被 `mpc-chain→openssl` 卡死时,把
`mpc-core/vault/ir/proto/ml` 五个零依赖 crate 拷到 `/tmp/mpc-bench` 建独立 workspace。
★ **三方必须用 `MeshPipe::mesh(3)`**(`Pipe` 是两方专用,忽略 party 定向 ⇒ 会串会话挂死)。
- **★ 数据必须 z-score 标准化**(每方用自己列的均值/方差):原始量纲(负载 20~95、
电压 218~232)+ `lr=0.1` ⇒ 20 轮直接发散(w 到 5.2e5)。
- 数据生成脚本:`/tmp/mpc-real/gen-lr3.py`(三方)、`gen-lr.py`(两方)。
### ★ 真机验证已达成
报告:`docs/e2e/real-machine-verification.md`;脚本:`/tmp/mpc-real/`(两方)、`/tmp/mpc3/`(三方)。
- **两方**(AMD alice + 海光 bob):PSI 交集 95;权重双方逐位一致;密态 vs 明文 **0.69%**。
- **三方**(AMD alice + 海光 bob + **zynq carol**):PSI 交集 **84**(三方一致);
三方权重逐位一致 `[0.3898658752441406, 0.02921295166015625, 0.01927947998046875,
-0.03290557861328125]`;vs 本地密态基准 `1e-5`;vs 明文 **0.76%**。
- **节点注册三台**(alice/bob/carol)⇒ `Device/Sync` = `synced=3`。
- **诚实边界**:宿主端二进制执行(非 TEE guest 内);PSK 来自会话文件而非 KBS 证明后下发;
**未经 ssw-mpc-flow 编排层驱动**;zynq 无 TEE ⇒ 只是普通 armv7 参与方。
### ★ xop 使用纪律
- 凭据只存**键名**;输出被掩码成 `ro****…` ⇒ 必须在 `xop run` 内部直接用 `"$VAR"`。
- **★ `xop run` 的 stdin 必须 `</dev/null`**(否则等 Touch ID 超时 → SIGTERM exit 137)。
- xop 会掩码含敏感词的**文件名/路径**(`psk.hex`→`zk****`)⇒ 传输用无敏感词名字。
- 输出混有 ANSI `WARN NetworkGuard/FileGuard` 行 ⇒ `grep -vE` 过滤。
- Gitea API 凭据用 **`git_local_user`/`git_local_pass`**(`git_ssw_*`/`jnpf_git_*` **不通**)。
- 键名:AMD `tee_amd_7_user`/`tee_amd_7_pass`;海光 **`tee_hg_102_user`/`tee_hg_102_pass`**;
zynq `tee_zynq_user`/`tee_zynq_pass`。
- **★ zynq 登录名是 `root`**(`tee_zynq_user` 存的是 4 字符用户名)⇒ SSH 要用 `-l "$Z_USER"`,
不能写成 `user@host`。封装:`/tmp/amd-run.sh` `/tmp/hg-run.sh` `/tmp/zynq-run.sh`。
- **★ 远端后台进程纪律**:`setsid --fork cmd > log 2>&1 < /dev/null` ⇒ 立即返回、进程完全脱离 ✅;
`ssh "cmd &"` ⇒ SSH 挂起 ❌。点火前必须 `pkill` 旧实例。
- **★ `pkill -f mpc-host` 会连带杀掉常驻 hostd** ⇒ 重启用 `/tmp/mpc-real/restore-amd.sh`。
- **★ `scp` 到 AMD 认证失败**(sshd 没开 SFTP)⇒ 走 ssh stdin 管道。
## ★ 本项目自身的坑
- **事件流游标是 exclusive**:后端 `events()` 过滤 `sortCode > afterSeq`,
而 `sortCode` **从 0 开始编号** ⇒ 默认 `afterSeq` 必须 **-1** 不是 0,
否则**第一条事件永久丢失**(曾致 Overview 只返 5/6 条)。
service / controller / 前端 api 三处默认值必须同步改。
- **引擎状态值必须大写**:`SUCCESS`/`FAILED`/`SKIPPED`。
`flowrun.service.ts` 的 `stats` 只认大写 ⇒ 落库写小写会让前端显示「0 成功」。
- **`f_id VARCHAR(50)` 是硬上限**:主键派生前缀 + hex 必须 ≤ 50
(`tee-`+46hex=50 / `rcpt-`+45hex=50),超了报 `value too long for character varying(50)`。
- **两个兄弟模块是真接口对接,不许灌假数据**:真源不可达 ⇒ **0 条 + source=mock + 原因**。
设备真源 = ssw-mpc 控制面 `GET {url}/nodes`(Bearer **明文原文**密钥,非 hex);
链上真源 = ssw-mpc outbox + FISCO 国密链自有 RPC。
- **`f_online` 三态**:`1`=此刻在真源 `/nodes` 里 / `0`=真源里已消失(掉线或 TTL 过期)/
`null`=从未同步过(人工登记)。`/nodes` 是**当前在线清单**(TTL 90s 自动剔除)
⇒ 同步必须标下线,但**只有真源读取成功时**才标(不可达时 `offline` 恒 0)。
`save()` 剥掉 `online`/`source`/`sourceReason` ⇒ 人工登记不能篡改真源权威字段。
- **`platform` 原样透传 `PlatformKind`**(`sev-snp`/`hygon-csv`/`optee`/`tdx`/`none`),
不做白名单 ⇒ 真源加新平台不该被挡在适配层。
- **`TeeNode.measurement` 全零 ⇒ 永远选不中**(选节点靠 measurement 匹配)。
- **登录密文是 Hex 不是 base64**(写错编码 ⇒「账号或密码错误」)。
检验向量:`encryptPassword('123456') === 'd4958348e22108119b3ef57b022c83f4bf857dd0b247eaab15b9a43d47ee3c503900f7135bf0de255bc33620c3cdc02b'`
- 设备列表 = **`GET /api/ssw/sswdevice/Device/List`**(不是 POST);同步 = `POST .../Device/Sync`。
- **API 返回字段是 camelCase**(`key`/`site`/`online`/`source`),不是 `f_` 前缀。
- **PGlite 0.5.8 持久化模式起不来**(卡 `waitReady`),只有 `memory://` 能用
⇒ **每次重启后端数据清空**。⇒ 落库脚本必须**自带元数据重建**且**幂等**
(先 List 查复用,查不到才建),否则重跑就重复。
- 后端启动后 **5~8s 内登录会失败**(PGlite 初始化竞态)⇒ 等日志出现
「Nest application successfully started」再打 API。
- `./run.sh dev` 的 nohup 进程在工具 shell 里会被回收 ⇒ 用工具原生后台任务起进程。
- 浏览器自动化用 `agent-browser`(`aix` 软链已断);React 重渲染后 `@ref` 失效,
改用 `eval` + `element.click()` + 手动 dispatch `change`。
- macOS grep 无 `-P`;`npm bin -g` 已移除,用 `npm root -g`。
- `grep` 对本仓库文件常返回空(退出码 1)⇒ 改用 python 计数/`re` 读。
- `mpcSettings()` 仓库根解析是**多候选 + 存在性探测**,别改回单路径。
- `check-module.sh --all` 会把多词实体名拆错(`datasetauth`→`Datasetauth`),
**必须显式列实体名**。
## ★ ssw-mpc 侧真源(只读)
`crates/mpc-chain/src/objects.rs`(Receipt 布局)、`outbox.rs`(行格式 + 幂等键)、
`rpc.rs`(FISCO 自有端点 + 成功三件套)、`crates/mpc-hostd/src/auth.rs`(Bearer 口径)、
`crates/mpc-cli/src/chain.rs`(子命令)、`tools/selftest-fisco-contract.py`(真链门禁 22/22)、
`tools/fisco-realnode/example.chain.json`、`contracts/MpcHardRule.sol` +
`build/contracts/combined.json`、`deploy/tee/real-machine/`。
**★ CLI feature 门控**:`hostd`/`control-plane`/`link` 需 control-plane 或 host-only;
`chain` 需 control-plane(要 OpenSSL);`sql*`/`pg` 需 secure;
**`node`/`psi`/`lr`/`lr-vertical`/`fl`/`orch`/`plan` 无门控**(guest 静态版也有)。
## ★ 真链/真机关键事实(FISCO + 控制面)
1. **FISCO 成功三件套**:`status==0`(与 web3 的 0x1 **相反**)+ `transactionHash` 非空
+ `blockNumber>0`;字段缺失按「没有」处理。
2. **FISCO 自有端点**(非 web3):`getTransactionReceipt`/`call`/`sendTransaction` 都 4 参
`[groupID,nodeName,…]`;`getBlockNumber` **只接受 0 参**。HTTP 200 ≠ 成功。
3. **selector 是二元数组** `[keccak_u32, sm3_u32]`,国密链用 `SM3(signature)[0..4]`。
4. **合约 `recordHardRule` 的 orderId ≤ 16 字节**(17 起 revert status=16)。
5. **`chain contract deploy --bin` 被忽略**(实际读 `--abi`,要 combined.json);
`call --arg` 要 `TYPE:VALUE` + `--key <SM2 PEM>` + `--node node0`。
6. **控制面 Bearer 必须是密钥原文**(非 hex);outbox `Confirmed` 只代表已广播。
7. **Receipt 布局**:域分隔固定 25B 无长度前缀 → `push_field("receipt")` → `"v1"` → 字段。
8. **TeeNode**:`kbc`=`cc_kbc`/`offline_fs_kbc::null`;`kbs_endpoint` 只能从 descriptor 解析。
9. **`GET /nodes` 是「当前在线清单」**:控制面 `prune_stale()` 剔除超 `node_ttl_secs`
(**默认 90s**)未心跳的节点 ⇒ 同步要处理下线,但**只有真源读取成功时**才标。
## ★ 本项目坑
- 事件流游标 exclusive:`sortCode > afterSeq` 且从 0 编号 ⇒ 默认 afterSeq 必须 -1(曾致 Overview 丢首条)。
- 引擎状态值必须大写 SUCCESS/FAILED/SKIPPED。
- f_id VARCHAR(50) 硬上限:前缀+hex ≤ 50。
- 真源对接不许灌假数据:不可达 ⇒ 0 条 + source=mock + 原因。设备真源控制面 GET /nodes(Bearer 明文密钥);链上真源 outbox+FISCO。
- f_online 三态:1 在线 / 0 掉线(真源消失) / null 未同步。/nodes 是当前在线清单(TTL 90s),只有读取成功才标下线。
- platform 原样透传 PlatformKind(sev-snp/hygon-csv/optee/tdx/none),不做白名单。
- 登录密文是 Hex(非 base64);校验向量 encryptPassword('123456')==='d4958348e22108119b3ef57b022c83f4bf857dd0b247eaab15b9a43d47ee3c503900f7135bf0de255bc33620c3cdc02b'。
- API 返回 camelCase(非 f_ 前缀);设备列表 GET、同步 POST。
- PGlite 0.5.8 持久化起不来 ⇒ memory://,重启清空;启动后 5~8s 登录会失败。
- check-module.sh 必须显式列实体名(`--all` 拆错多词名)。
## 已知未实现
- **FlowSchedule 周期调度**:只有表和 CRUD,**调度器未实现**(到点不自动起 run)。
- **编排层仍不能自动驱动多方**:`mpc-engine.ts` 是单进程(`sites[0]` 作本方),
`sessionCapability()` 需 `MPC_SESSION_LISTEN`/`MPC_SESSION_CONNECT`/`MPC_AGENT_PRESENT=1`
才真下发,否则降级 partial + WARN 写明原因,不硬失败。
- **TEE guest 内运行 PSI/LR**:当前为**宿主端**二进制执行,PSK 来自会话文件而非
KBS 证明后下发。
- **AMD 侧 KBS 真实 SNP 证明流程**:strict 已起,但无 guest 提交过证明包。
- **设备注册无 mTLS 握手**:走 ssw-mpc 既有机制(TEE 节点经 hostd 向控制面自报),
本项目只做注册表的读取与呈现,不自建注册协议。
- **链上存证不是通用区块浏览器**:ssw-mpc `mpc chain` **没有**区块浏览命令,
链上对象只有 Receipt / Member / PolicyBundleRecord 三类。
- **KBS 架构结论**(已定):判定留真机 / 物料进 pod / 控制面进 pod / hostd 不变。
## ssw-mvp 原始落点(别再找错)
「设备注册」「区块链」**不在 sswflow 域**,是三个子项目三种语言:
`nax/nax/device/`(Python 设备登记)、`scard/code/connector/register/`(Go 注册连接器)、
`boot/ssw-tds/.../tds/chain/`(Java FISCO 链存证)。**没有现成 TS 版可搬**。
- 编排层不能自动驱动多方(mpc-engine 单进程);TEE guest 内跑 PSI/LR(当前宿主端);AMD KBS 真实 SNP 证明(无 guest 提交)。
- 链上存证非通用区块浏览器(链上只有 Receipt/Member/PolicyBundleRecord)。
- KBS 架构结论:判定留真机 / 物料进 pod / 控制面进 pod / hostd 不变。
+58
View File
@@ -219,6 +219,64 @@ check 200 "$(echo "$DEL" | pick 'j.code')" "删除流程"
LEFT=$(curl --noproxy '*' -s "$B/api/ssw/sswflow/Flow/List" -H "$AUTH" | pick "j.data.find(f=>f.id==='$FID')?'still-there':'gone'")
check "gone" "$LEFT" "软删后不再出现在 List"
echo "== 16) 周期调度(自建流程:cron 校验 + 启用/停用 + 立即触发)=="
printf '%s' '{"name":"调度冒烟流程","desc":"sswflow-smoke","steps":"[]","edges":"[]"}' > "$TMP/sf.json"
NSF=$(curl --noproxy '*' -s -X POST "$B/api/ssw/sswflow/Flow/Save" -H "$AUTH" -H 'Content-Type: application/json' -d @"$TMP/sf.json")
check 200 "$(echo "$NSF" | pick 'j.code')" "新建调度测试流程"
SFID=$(echo "$NSF" | pick 'j.data.id')
$NODE -e "
const steps=[
{stepId:'s1',operatorKey:'source.dataset',label:'数据集',x:40,y:60,params:{datasetId:'ds-001'}},
{stepId:'s2',operatorKey:'prep.sample',label:'抽样',x:260,y:60,params:{}},
{stepId:'s3',operatorKey:'model.lr.train',label:'逻辑回归',x:480,y:60,params:{labelColumn:'y'}},
{stepId:'s4',operatorKey:'sink.export',label:'导出',x:700,y:60,params:{targetParty:'alice',fileName:'out.csv'}}
];
const edges=[
{edgeId:'e1',sourceStepId:'s1',sourcePort:'out',targetStepId:'s2',targetPort:'in'},
{edgeId:'e2',sourceStepId:'s2',sourcePort:'out',targetStepId:'s3',targetPort:'in'},
{edgeId:'e3',sourceStepId:'s3',sourcePort:'model',targetStepId:'s4',targetPort:'in'}
];
require('fs').writeFileSync('$TMP/sf_canvas.json', JSON.stringify({id:'$SFID',steps,edges}));
"
curl --noproxy '*' -s -X POST "$B/api/ssw/sswflow/Flow/Canvas" -H "$AUTH" -H 'Content-Type: application/json' -d @"$TMP/sf_canvas.json" > /dev/null
printf '%s' '{"cron":"0 0 2 * * ?","count":3}' > "$TMP/prv.json"
PRV=$(curl --noproxy '*' -s -X POST "$B/api/ssw/sswflow/FlowSchedule/Preview" -H "$AUTH" -H 'Content-Type: application/json' -d @"$TMP/prv.json")
check 200 "$(echo "$PRV" | pick 'j.code')" "Preview 返回 200"
check "true" "$(echo "$PRV" | pick 'j.data.valid')" "合法 cron valid=true"
check 3 "$(echo "$PRV" | pick 'j.data.fires.length')" "预览 3 次触发"
printf '%s' '{"cron":"0 0 2 * *","count":3}' > "$TMP/prv2.json"
PRV2=$(curl --noproxy '*' -s -X POST "$B/api/ssw/sswflow/FlowSchedule/Preview" -H "$AUTH" -H 'Content-Type: application/json' -d @"$TMP/prv2.json")
check "false" "$(echo "$PRV2" | pick 'j.data.valid')" "非法 cron valid=false"
$NODE -e "require('fs').writeFileSync('$TMP/sched.json', JSON.stringify({name:'冒烟调度',flowId:'$SFID',cron:'0 0 2 * * ?',enabledMark:0,runScope:'{\"mode\":\"FULL\"}'}))"
SCH=$(curl --noproxy '*' -s -X POST "$B/api/ssw/sswflow/FlowSchedule/Save" -H "$AUTH" -H 'Content-Type: application/json' -d @"$TMP/sched.json")
check 200 "$(echo "$SCH" | pick 'j.code')" "新建调度"
SID=$(echo "$SCH" | pick 'j.data.id')
checkne 0 "${#SID}" "调度 id 非空 (${#SID} 位)"
printf '%s' "{\"id\":\"$SID\",\"enabled\":true}" > "$TMP/en.json"
EN=$(curl --noproxy '*' -s -X POST "$B/api/ssw/sswflow/FlowSchedule/SetEnabled" -H "$AUTH" -H 'Content-Type: application/json' -d @"$TMP/en.json")
check 200 "$(echo "$EN" | pick 'j.code')" "启用调度"
check 1 "$(echo "$EN" | pick 'j.data.enabledMark')" "enabledMark=1"
checkne 0 "$(echo "$EN" | pick 'j.data.nextFireTime.length')" "启用后算出 nextFireTime"
printf '%s' "{\"id\":\"$SID\"}" > "$TMP/tr.json"
TR=$(curl --noproxy '*' -s -X POST "$B/api/ssw/sswflow/FlowSchedule/TriggerNow" -H "$AUTH" -H 'Content-Type: application/json' -d @"$TMP/tr.json")
check 200 "$(echo "$TR" | pick 'j.code')" "立即触发返回 200"
checkne 0 "$(echo "$TR" | pick 'j.data.runId.length')" "触发产生 runId"
check "SUCCESS" "$(echo "$TR" | pick 'j.data.status')" "派发状态 SUCCESS"
LB=$(curl --noproxy '*' -s "$B/api/ssw/sswflow/FlowSchedule/ListByFlow?flowId=$SFID" -H "$AUTH")
check 200 "$(echo "$LB" | pick 'j.code')" "ListByFlow 返回 200"
checkne 0 "$(echo "$LB" | pick 'j.data.length')" "ListByFlow 含该调度"
# 清理:先停用调度,再软删流程(避免 Ticker 后续对软删流程点火刷 FAILED)
printf '%s' "{\"id\":\"$SID\",\"enabled\":false}" > "$TMP/dis.json"
curl --noproxy '*' -s -X POST "$B/api/ssw/sswflow/FlowSchedule/SetEnabled" -H "$AUTH" -H 'Content-Type: application/json' -d @"$TMP/dis.json" > /dev/null
curl --noproxy '*' -s -X DELETE "$B/api/ssw/sswflow/Flow/Delete?id=$SFID" -H "$AUTH" > /dev/null
echo
echo "--------------------"
echo "PASS=$PASS FAIL=$FAIL"
+71
View File
@@ -0,0 +1,71 @@
#!/usr/bin/env bash
# spring-cron 单测 —— 把 spring-cron.ts 单独编译后跑断言(不依赖后端 / 不依赖 PGlite)。
#
# 覆盖:6 位校验、? 互斥、日周取「或」、每周/每天、严格大于 from、非法 cron 返回 null、preview 数量。
# 用法:bash scripts/test-spring-cron.sh
# 退出码:0 全过 / 1 有失败
set -u
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT/src/backend" || exit 2
TS="src/sswflow/schedule/spring-cron.ts"
OUT="$(mktemp -d)"
trap 'rm -rf "$OUT"' EXIT
if ! npx tsc "$TS" --outDir "$OUT" --module commonjs --target es2020 --skipLibCheck --moduleResolution node --esModuleInterop >/tmp/spring-cron-tsc.log 2>&1; then
echo "❌ 编译 spring-cron.ts 失败:"
cat /tmp/spring-cron-tsc.log
exit 1
fi
CJS_OUT="$OUT" node -e '
const m = require(process.env.CJS_OUT + "/spring-cron.js");
const { parseSpringCron, isValidSpringCron, nextSpringCron, previewSpringCron } = m;
let pass = 0, fail = 0;
function eq(n, g, w) {
if (JSON.stringify(g) === JSON.stringify(w)) pass++;
else { fail++; console.error("FAIL " + n + ": got " + JSON.stringify(g) + " want " + JSON.stringify(w)); }
}
function ok(n, c) { if (c) pass++; else { fail++; console.error("FAIL " + n); } }
// ★ spring-cron 按「本地时区」计算(与 Spring CronExpression 一致),断言用本地字段比较,避免 UTC 偏移。
function parts(d){ return d ? [d.getFullYear(), d.getMonth()+1, d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds()] : null; }
function eqL(n, gotD, y,mo,d,h,mi,s){ eq(n, parts(gotD), [y,mo,d,h,mi,s]); }
// 1. 6 位校验
ok("合法 6 位", isValidSpringCron("0 0 2 * * ?"));
ok("非法 5 位被拒", !isValidSpringCron("0 0 2 * *"));
ok("非法 7 位被拒", !isValidSpringCron("0 0 2 * * ? *"));
// 2. 日与周 ? 互斥
ok("日周同时 ? 被拒", !isValidSpringCron("0 0 0 ? * ?"));
// 3. 每天 02:00:00(from 当地当天 03:00 → 次日 02:00)
eqL("每天 2am 下一次", nextSpringCron("0 0 2 * * ?", new Date(2026,0,1,3,0,0)), 2026,1,2,2,0,0);
// 4. 严格大于 from(from 恰好 02:00:00 → 跳到次日,不返回 from 本身)
eqL("严格大于 from", nextSpringCron("0 0 2 * * ?", new Date(2026,0,1,2,0,0)), 2026,1,2,2,0,0);
// 5. 日周取「或」:每月 1 号 或 周一 00:00:00(from=周四 00:00 → 下周一 01-05)
eqL("日周 OR", nextSpringCron("0 0 0 1 * MON", new Date(2026,0,1,0,0,0)), 2026,1,5,0,0,0);
// 6. 每周一 09:30:00(dom 用 ? 仅限定 dow;from=周四 → 下周一 01-05 09:30)
eqL("每周一 9:30", nextSpringCron("0 30 9 ? * MON", new Date(2026,0,1,0,0,0)), 2026,1,5,9,30,0);
// 7. 指定月份名:每年 3 月 1 日 00:00(from=当地 2026-01-01 → 2026-03-01)
eqL("月份名 MAR", nextSpringCron("0 0 0 1 MAR ?", new Date(2026,0,1,0,0,0)), 2026,3,1,0,0,0);
// 8. 非法 cron 不触发(返回 null,绝不退化成每分钟)
ok("非法 cron → null", nextSpringCron("bad cron expr", new Date()) === null);
// 9. preview 数量(与 TZ 无关)
eq("preview 3 次", previewSpringCron("0 0 2 * * ?", 3, new Date(2026,0,1,3,0,0)).length, 3);
ok("preview 非法 cron → []", previewSpringCron("0 0 2 * *", 3).length === 0);
// 10. preview 的未来时刻严格递增(均为本地 Date,单调递增)
const fs = previewSpringCron("0 0 2 * * ?", 4, new Date(2026,0,1,3,0,0));
ok("preview 单调递增", fs.every((d,i,a)=> i===0 || a[i-1].getTime() < d.getTime()));
console.log("spring-cron 单测:PASS=" + pass + " FAIL=" + fail);
process.exit(fail > 0 ? 1 : 0);
'
@@ -46,4 +46,39 @@ export class FlowScheduleController {
await this.svc.remove(id);
return ActionResult.success(null);
}
/** 按流程查调度(流程详情页用)。 */
@Get('ListByFlow')
async listByFlow(@Req() req: any, @Query('flowId') flowId: string) {
const g = await this.guard(req);
if (g) return g;
return ActionResult.success(await this.svc.listByFlow(flowId));
}
/** 启用 / 停用。body: { id, enabled } */
@Post('SetEnabled')
async setEnabled(@Req() req: any, @Body() body: any) {
const g = await this.guard(req);
if (g) return g;
const enabled = body?.enabled === true || body?.enabled === 1 || body?.enabled === 'true';
return ActionResult.success(await this.svc.setEnabled(body?.id, enabled));
}
/** 预览未来 n 次触发。body: { cron, count? } */
@Post('Preview')
async preview(@Req() req: any, @Body() body: any) {
const g = await this.guard(req);
if (g) return g;
const cron = (body?.cron || '').toString();
const count = Number(body?.count) || 5;
return ActionResult.success({ cron, valid: this.svc.previewNextFires(cron, 1).length > 0, fires: this.svc.previewNextFires(cron, count) });
}
/** 立即触发(手动)。body: { id } */
@Post('TriggerNow')
async triggerNow(@Req() req: any, @Body() body: any) {
const g = await this.guard(req);
if (g) return g;
return ActionResult.success(await this.svc.triggerNow(body?.id));
}
}
+167 -9
View File
@@ -1,16 +1,30 @@
import { Injectable } from '@nestjs/common';
import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { LessThanOrEqual, Repository } from 'typeorm';
import { randomUUID } from 'crypto';
import { FlowScheduleEntity } from './flowschedule.entity';
import { FlowRunService } from './flowrun.service';
import { nextSpringCron, previewSpringCron, CronParseError } from './schedule/spring-cron';
/** 周期调度服务 —— 列表带软删过滤、删除是 update f_delete_mark=1、主键 36 位 UUID。
* 迁 JNPF:对应 XxxServiceImpl extends SuperServiceImpl,逻辑逐行可译。 */
/**
* 周期调度服务 —— 从 ssw-mvp `FlowScheduleServiceImpl.java` 机械移植并补上调度器闭环。
*
* ★ 与 Java 版的口径对齐:
* - `listDue` 只收 enabled=1 且 nextFireTime 非空且 ≤ now 的记录(SQL 层过滤,
* `next_fire_time <= now` 天然排除 NULL)。
* - `doFire` 触发时调用 `flowRun.start(flowId, {trigger:'SCHEDULE', ...})`;
* 失败记 `lastStatus='FAILED'` 且**仍推进** nextFireTime(否则坏调度每 30s 重试刷日志)。
* - `manual`(立即触发)**不改** nextFireTime(对齐 Java `triggerNow`);定时触发才推进。
* - cron 非法 ⇒ `computeNextFire` 返回 null ⇒ 不触发(绝不退化成每分钟跑)。
*/
@Injectable()
export class FlowScheduleService {
private readonly logger = new Logger('FlowSchedule');
constructor(
@InjectRepository(FlowScheduleEntity)
private readonly repo: Repository<FlowScheduleEntity>,
private readonly flowRun: FlowRunService,
) {}
async list(): Promise<FlowScheduleEntity[]> {
@@ -24,10 +38,155 @@ export class FlowScheduleService {
return this.repo.findOne({ where: { id, deleteMark: 0 } as any });
}
/** 某流程下的全部调度(前端流程详情页可用)。 */
async listByFlow(flowId: string): Promise<FlowScheduleEntity[]> {
return this.repo.find({
where: { flowId, deleteMark: 0 } as any,
order: { creatorTime: 'DESC' } as any,
});
}
async setEnabled(id: string, enabled: boolean): Promise<FlowScheduleEntity | null> {
const s = await this.get(id);
if (!s) return null;
const enabledMark = enabled ? 1 : 0;
const patch: any = { enabledMark };
if (enabled && s.cron) {
// 启用 ⇒ 重新计算下一次触发(从当前时刻起)
patch.nextFireTime = this.computeNextFire(s.cron, new Date());
} else if (!enabled) {
// 停用 ⇒ 清空下次触发,避免静默到点起 run
patch.nextFireTime = null;
}
await this.repo.update({ id } as any, patch);
return this.get(id);
}
/** 全部到点待触发(供 Ticker 轮询)。 */
async listDue(now: Date = new Date()): Promise<FlowScheduleEntity[]> {
return this.repo.find({
where: {
enabledMark: 1,
deleteMark: 0,
nextFireTime: LessThanOrEqual(now),
} as any,
});
}
/** 预览未来 n 次触发(前端「预览未来 5 次」用)。cron 非法返回空数组。 */
previewNextFires(cron: string, count = 5, from: Date = new Date()): Date[] {
try {
return previewSpringCron(cron, count, from);
} catch (e) {
if (e instanceof CronParseError) return [];
return [];
}
}
/** 计算从 from 起的下一次触发(严格大于 from);cron 非法返回 null。 */
computeNextFire(cron: string | null | undefined, from: Date): Date | null {
if (!cron) return null;
return nextSpringCron(cron, from);
}
/** 立即触发(手动):忽略 cron,直接起 run,不改 nextFireTime。 */
async triggerNow(
id: string,
): Promise<{ runId: string | null; status: string; schedule?: FlowScheduleEntity }> {
const s = await this.get(id);
if (!s) return { runId: null, status: 'NOT_FOUND' };
const runId = await this.doFire(s, true);
const updated = await this.get(id);
return { runId, status: updated?.lastStatus || 'UNKNOWN', schedule: updated || undefined };
}
/** 定时触发(Ticker 调用):按 cron 推进 nextFireTime。 */
async fire(schedule: FlowScheduleEntity): Promise<string | null> {
return this.doFire(schedule, false);
}
/**
* 真正点火:start 异步执行、立即返回 runId(HTTP 语义与 Java 一致)。
* 记录「已成功派发」为 SUCCESS;派发异常(流程不存在 / 校验失败)记 FAILED。
* run 自身的最终状态由 flowrun 异步推进,这里只负责调度侧的可观测字段。
*/
private async doFire(schedule: FlowScheduleEntity, manual: boolean): Promise<string | null> {
const now = new Date();
try {
const scope = this.parseScope(schedule.runScope);
const run = await this.flowRun.start(schedule.flowId, {
trigger: 'SCHEDULE',
operator: schedule.creatorUserId || 'scheduler',
mode: scope.mode,
stepIds: scope.stepIds,
baseRunId: scope.baseRunId,
});
const runId = run.id;
const patch: any = { lastFireTime: now, lastRunId: runId, lastStatus: 'SUCCESS' };
if (!manual) patch.nextFireTime = this.computeNextFire(schedule.cron, now) ?? this.parkUntil();
await this.repo.update({ id: schedule.id } as any, patch);
return runId;
} catch (e: any) {
this.logger.error(`调度 ${schedule.id} 触发失败:${e?.message || e}`);
const patch: any = { lastFireTime: now, lastStatus: 'FAILED' };
if (!manual) patch.nextFireTime = this.computeNextFire(schedule.cron, now) ?? this.parkUntil();
await this.repo.update({ id: schedule.id } as any, patch);
return null;
}
}
/** 解析 runScope JSON(如 {"mode":"FULL"} / {"mode":"SELECTED","stepIds":[...]})。
* 解析失败退化 FULL 并记 WARN,不因为手滑 JSON 停掉整条调度。 */
private parseScope(
runScope?: string | null,
): { mode: string; stepIds?: string[]; baseRunId?: string } {
if (!runScope) return { mode: 'FULL' };
try {
const o = JSON.parse(runScope);
return {
mode: o.mode || 'FULL',
stepIds: Array.isArray(o.stepIds) ? o.stepIds : undefined,
baseRunId: o.baseRunId || undefined,
};
} catch {
this.logger.warn(`调度 runScope JSON 解析失败(${runScope}),退化 FULL`);
return { mode: 'FULL' };
}
}
/** cron 非法时的兜底:把坏调度 parked 到一年以后,避免每轮重试刷日志。 */
private parkUntil(): Date {
return new Date(Date.now() + 365 * 24 * 3600 * 1000);
}
async save(item: Partial<FlowScheduleEntity>): Promise<FlowScheduleEntity> {
if (!item.id) {
const id = (item as any).id;
const existing = id ? await this.repo.findOne({ where: { id } as any }) : null;
const enabledMark =
(item as any).enabledMark !== undefined
? Number((item as any).enabledMark)
: existing
? existing.enabledMark
: 0;
const cron = (item as any).cron !== undefined ? (item as any).cron : existing ? existing.cron : null;
// ★ 启用 + 有 cron ⇒ 重算 nextFireTime(否则「改了没生效」);停用 ⇒ 清空。
let nextFireTime: Date | null = null;
if (enabledMark === 1 && cron) {
nextFireTime = this.computeNextFire(cron, new Date());
}
const toSave: any = {
...item,
enabledMark,
cron: cron ?? null,
nextFireTime,
};
if (!id) {
const ent = this.repo.create({
...item,
...toSave,
id: randomUUID(),
creatorUserId: (item as any).creatorUserId || 'admin',
creatorTime: new Date(),
@@ -35,12 +194,11 @@ export class FlowScheduleService {
} as any);
return (await this.repo.save(ent)) as unknown as FlowScheduleEntity;
}
const existing = await this.repo.findOne({ where: { id: item.id } as any });
if (!existing) {
const created = this.repo.create({ ...item, creatorTime: new Date(), deleteMark: 0 } as any);
const created = this.repo.create({ ...toSave, creatorTime: new Date(), deleteMark: 0 } as any);
return (await this.repo.save(created)) as unknown as FlowScheduleEntity;
}
Object.assign(existing, item);
Object.assign(existing, toSave);
return (await this.repo.save(existing)) as unknown as FlowScheduleEntity;
}
@@ -0,0 +1,54 @@
import { Injectable, Logger, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
import { FlowScheduleService } from './flowschedule.service';
/**
* 周期调度轮询器 —— 机械移植自 ssw-mvp `FlowScheduleTicker.java`。
*
* ★ 口径对齐:
* - 单线程轮询,无需 Quartz RAMJobStore;状态全在 `sswflow_flow_schedule` 表。
* - 启动后 5s 首次扫描,之后每 30s 一次(`scheduleWithFixedDelay(5s, 30s)`)。
* - 单条调度失败 try/catch 隔离,绝不拖垮整轮扫描。
*/
@Injectable()
export class FlowScheduleTicker implements OnModuleInit, OnModuleDestroy {
private readonly logger = new Logger('FlowScheduleTicker');
private firstTimer: NodeJS.Timeout | null = null;
private timer: NodeJS.Timeout | null = null;
constructor(private readonly svc: FlowScheduleService) {}
onModuleInit() {
// 启动后 5s 首次扫描(避开 Nest 启动竞态),之后每 30s。
this.firstTimer = setTimeout(() => {
this.firstTimer = null;
void this.tick();
this.timer = setInterval(() => void this.tick(), 30 * 1000);
}, 5 * 1000);
this.logger.log('调度轮询器已注册(首次 5s,周期 30s)');
}
onModuleDestroy() {
if (this.firstTimer) clearTimeout(this.firstTimer);
if (this.timer) clearInterval(this.timer);
this.timer = null;
this.firstTimer = null;
}
async tick() {
try {
const due = await this.svc.listDue();
if (due.length) this.logger.log(`扫描到点调度 ${due.length} 条`);
for (const s of due) {
try {
const runId = await this.svc.fire(s);
if (runId) this.logger.log(`触发调度 ${s.id}(${s.name})→ run ${runId}`);
else this.logger.warn(`调度 ${s.id}(${s.name})触发未产生 run(已记 FAILED)`);
} catch (e: any) {
this.logger.error(`调度 ${s.id} 触发异常:${e?.message || e}`);
}
}
} catch (e: any) {
this.logger.error(`调度扫描失败:${e?.message || e}`);
}
}
}
@@ -0,0 +1,222 @@
/**
* Spring 风格 cron 解析(6 位:秒 分 时 日 月 周)。
*
* ★ 口径对齐 ssw-mvp 的 `FlowScheduleServiceImpl.computeNextFire()`:
* 它用 `org.springframework.scheduling.support.CronExpression.parse(cron)`,
* 前端提示文案是「Spring Cron(秒 分 时 日 月 周)」,默认 `0 0 2 * * ?`。
* ⇒ 本文件是那份 Spring 语义的 **TypeScript 复刻**,不是 Unix 5 位 cron。
*
* ★ 为什么自己写而不引库:
* Spring 的 CronExpression 在 `?`(日/周互斥)、日周取「或」等语义上与 Unix cron 不同,
* 通用 cron 库(`node-cron` / `cron-parser`)按 Unix 口径解析会静默偏掉触发时间。
*
* ★ 当前覆盖的语法:`* ?`、单值、`a-b` 范围、步长(域后加 `/n`,例如 `* / 5`、`a-b / 5`)、`,` 枚举、
* 月份/星期英文名(JAN-DEC、SUN-SAT)。**尚未实现** `L`(月末)、`W`(最近工作日)、
* `#`(第 N 个周 X)—— 本项目调度只用到 `* * ?` 与简单枚举,未触发这些边界;
* 若日后需要,在 `parseField`/`matchDay` 增加分支即可。
*
* ★ 失败口径:**解析不出就返回 null**(不触发),与 Java 版一致。
* 绝不「解析失败就退化成每分钟跑一次」—— 那是静默的错误行为。
*/
/** 一次解析结果:给定基准时刻,返回下一次触发时刻(本地时区)。 */
export interface CronFields {
second: number[];
minute: number[];
hour: number[];
dayOfMonth: number[] | null; // null = 「不限定」(对应 `?`)
month: number[];
dayOfWeek: number[] | null; // null = 「不限定」;0=周日, 6=周六
/** 日与周同时被限定时,二者取**或**(Spring 语义);只限定一个时取该一个。 */
domRestricted: boolean;
dowRestricted: boolean;
}
/** 月份名 → 数字(Spring 支持 JAN-DEC,大小写不敏感)。 */
const MONTH_NAMES: Record<string, number> = {
jan: 1, feb: 2, mar: 3, apr: 4, may: 5, jun: 6,
jul: 7, aug: 8, sep: 9, oct: 10, nov: 11, dec: 12,
};
/** 星期名 → 数字(Spring: SUN=0)。 */
const DAY_NAMES: Record<string, number> = {
sun: 0, mon: 1, tue: 2, wed: 3, thu: 4, fri: 5, sat: 6,
};
/** 解析失败抛出的错(消息面向使用者)。 */
export class CronParseError extends Error {}
function parseField(
raw: string,
min: number,
max: number,
names?: Record<string, number>,
): number[] {
const out = new Set<number>();
for (const part of raw.split(',')) {
const p = part.trim();
if (!p) throw new CronParseError(`空的 cron 字段:${raw}`);
// `a-b` 范围;`a-b/n` 带步长;`a` 单值;`*` 全量
let step = 1;
let body = p;
const slash = p.indexOf('/');
if (slash >= 0) {
body = p.slice(0, slash);
const stepRaw = p.slice(slash + 1).trim();
if (!/^\d+$/.test(stepRaw)) throw new CronParseError(`步长不是整数:${p}`);
step = Number(stepRaw);
if (step <= 0) throw new CronParseError(`步长必须大于 0:${p}`);
}
let lo: number;
let hi: number;
if (body === '*' || body === '?') {
lo = min; hi = max;
} else if (body.includes('-')) {
const [a, b] = body.split('-');
lo = toNum(a.trim(), names);
hi = toNum(b.trim(), names);
} else {
lo = toNum(body, names);
hi = step > 1 ? max : lo;
}
if (lo < min || hi > max || lo > hi) {
throw new CronParseError(`取值越界(${min}~${max}):${p}`);
}
for (let v = lo; v <= hi; v += step) out.add(v);
}
if (!out.size) throw new CronParseError(`字段解析为空:${raw}`);
return [...out].sort((a, b) => a - b);
}
function toNum(tok: string, names?: Record<string, number>): number {
const t = tok.trim().toUpperCase();
if (names && names[t.toLowerCase()] !== undefined) return names[t.toLowerCase()];
if (!/^\d+$/.test(t)) throw new CronParseError(`不是数字:${tok}`);
return Number(t);
}
/**
* 解析 6 位 Spring cron。
*
* ★ 日与周的 `?` 语义:Spring 要求**至少有一个**被限定(不能两个都是 `?`),
* 两个都被限定时取**或**(不是 Unix 的「与」)。
*/
export function parseSpringCron(cron: string): CronFields {
const s = (cron || '').trim();
if (!s) throw new CronParseError('cron 为空');
const parts = s.split(/\s+/);
if (parts.length !== 6) {
throw new CronParseError(`必须是 6 位(秒 分 时 日 月 周),得到 ${parts.length} 位:${s}`);
}
const [sec, min, hour, dom, mon, dow] = parts;
const domRestricted = dom !== '?';
const dowRestricted = dow !== '?';
if (!domRestricted && !dowRestricted) {
throw new CronParseError('日与周不能同时用 ?(至少要限定一个)');
}
return {
second: parseField(sec, 0, 59),
minute: parseField(min, 0, 59),
hour: parseField(hour, 0, 23),
dayOfMonth: domRestricted ? parseField(dom, 1, 31) : null,
month: parseField(mon, 1, 12, MONTH_NAMES),
dayOfWeek: dowRestricted ? parseField(dow, 0, 7, DAY_NAMES).map((d) => (d === 7 ? 0 : d)) : null,
domRestricted,
dowRestricted,
};
}
/** `cron` 是否能解析(用于表单校验)。 */
export function isValidSpringCron(cron: string): boolean {
try {
parseSpringCron(cron);
return true;
} catch {
return false;
}
}
/** 该月是否只有 28 天(粗判,用于 `L` 末日:2 月平年)。 */
function daysInMonth(y: number, m: number): number {
return new Date(y, m, 0).getDate();
}
/**
* 计算从 `from` 起的下一次触发时刻(**严格大于** from)。
*
* ★ 与 Spring `CronExpression.next(t)` 语义一致:返回严格晚于 t 的下一个时刻。
* 若 cron 不可能再触发(如 `0 0 0 30 2 ?` 2 月 30 日),返回 null。
*
* 搜索策略:秒 → 分 → 时 → 日逐层推进(跳到下一个候选值),
* 最多向前找 4 年(覆盖 2 月 29 日这种稀疏规则)。
*/
export function nextSpringCron(cron: string, from: Date): Date | null {
let f: CronFields;
try {
f = parseSpringCron(cron);
} catch {
return null;
}
const start = new Date(from.getTime());
// 从「from 的下一秒」开始找(严格大于)
start.setMilliseconds(0);
start.setSeconds(start.getSeconds() + 1);
// 上限:4 年(闰年周期),超出判「不再触发」
const LIMIT_MS = 366 * 4 * 24 * 3600 * 1000;
const deadline = from.getTime() + LIMIT_MS;
const d = new Date(start);
while (d.getTime() <= deadline) {
if (!f.month.includes(d.getMonth() + 1)) {
// 跳到下个月 1 号 00:00:00
d.setMonth(d.getMonth() + 1, 1);
d.setHours(0, 0, 0, 0);
continue;
}
if (!matchDay(f, d)) {
d.setDate(d.getDate() + 1);
d.setHours(0, 0, 0, 0);
continue;
}
if (!f.hour.includes(d.getHours())) {
d.setHours(d.getHours() + 1, 0, 0, 0);
continue;
}
if (!f.minute.includes(d.getMinutes())) {
d.setMinutes(d.getMinutes() + 1, 0, 0);
continue;
}
if (!f.second.includes(d.getSeconds())) {
d.setSeconds(d.getSeconds() + 1, 0);
continue;
}
return d;
}
return null;
}
/** 日匹配:日与周都限定时取**或**(Spring 语义)。 */
function matchDay(f: CronFields, d: Date): boolean {
const domHit = f.dayOfMonth ? f.dayOfMonth.includes(d.getDate()) : false;
const dowHit = f.dayOfWeek ? f.dayOfWeek.includes(d.getDay()) : false;
if (f.domRestricted && f.dowRestricted) return domHit || dowHit;
if (f.domRestricted) return domHit;
if (f.dowRestricted) return dowHit;
return true;
}
/** 预览未来 n 次触发时刻(给前端「预览未来 5 次」用)。 */
export function previewSpringCron(cron: string, count: number, from: Date = new Date()): Date[] {
const out: Date[] = [];
let cur = new Date(from.getTime());
for (let i = 0; i < count; i++) {
const n = nextSpringCron(cron, cur);
if (!n) break;
out.push(n);
cur = n;
}
return out;
}
+3 -1
View File
@@ -28,6 +28,7 @@ import { FlowStepRunService } from './flowsteprun.service';
import { RunEventService } from './runevent.service';
import { ArtifactService } from './artifact.service';
import { FlowScheduleService } from './flowschedule.service';
import { FlowScheduleTicker } from './flowschedule.ticker';
import { EngineRegistry } from './engine/engine-registry';
import { ProjectController } from './project.controller';
@@ -65,7 +66,8 @@ import { EngineController } from './engine.controller';
providers: [
ProjectService, PartyService, ProjectPartyService, DatasourceService,
DatasetService, DatasetAuthService, FlowService, FlowRunService,
FlowStepRunService, RunEventService, ArtifactService, FlowScheduleService,
FlowStepRunService, RunEventService, ArtifactService, FlowScheduleService,
FlowScheduleTicker,
EngineRegistry,
],
exports: [FlowRunService, EngineRegistry],
+9
View File
@@ -6,3 +6,12 @@ export const listFlowSchedules = () => request.get('/ssw/sswflow/FlowSchedule/Li
export const saveFlowSchedule = (dto: any) => request.post('/ssw/sswflow/FlowSchedule/Save', dto);
export const deleteFlowSchedule = (id: string) =>
request.delete(`/ssw/sswflow/FlowSchedule/Delete?id=${id}`);
export const listFlowSchedulesByFlow = (flowId: string) =>
request.get(`/ssw/sswflow/FlowSchedule/ListByFlow?flowId=${encodeURIComponent(flowId)}`);
export const setFlowScheduleEnabled = (id: string, enabled: boolean) =>
request.post('/ssw/sswflow/FlowSchedule/SetEnabled', { id, enabled });
export const previewFlowSchedule = (cron: string, count = 5) =>
request.post('/ssw/sswflow/FlowSchedule/Preview', { cron, count });
export const triggerFlowScheduleNow = (id: string) =>
request.post('/ssw/sswflow/FlowSchedule/TriggerNow', { id });
+216 -11
View File
@@ -1,16 +1,221 @@
import { listFlowSchedules, saveFlowSchedule, deleteFlowSchedule } from '../api/flowschedule';
import CrudPage from '../components/CrudPage';
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { wrap, card, btn, btnDanger, btnGhost, input, tableStyle, th, td } from './ui';
import {
listFlowSchedules, saveFlowSchedule, deleteFlowSchedule,
setFlowScheduleEnabled, previewFlowSchedule, triggerFlowScheduleNow,
} from '../api/flowschedule';
import { listFlows } from '../api/flow';
/** 周期调度 —— 用通用 CRUD 页承载,字段为去前缀名(JNPF Jackson 剥 f_)。 */
const DEFAULT_CRON = '0 0 2 * * ?';
function fmt(v: any): string {
if (v === null || v === undefined || v === '') return '-';
if (v instanceof Date) return v.toLocaleString();
const s = String(v);
if (/^\d{4}-\d{2}-\d{2}T/.test(s)) return new Date(s).toLocaleString();
return s;
}
function fmtStatus(s: string): { text: string; color: string } {
if (s === 'SUCCESS') return { text: '成功', color: '#5ad19a' };
if (s === 'FAILED') return { text: '失败', color: '#ff8a80' };
return { text: s || '-', color: '#9aa7b5' };
}
/** 周期调度 —— 定制页:启用停用 / 立即触发 / 预览未来 5 次 / Spring Cron 录入。 */
export default function FlowSchedule() {
const nav = useNavigate();
const [rows, setRows] = useState<any[]>([]);
const [flows, setFlows] = useState<any[]>([]);
const [editing, setEditing] = useState<any | null>(null);
const [err, setErr] = useState('');
const [busy, setBusy] = useState(false);
const [preview, setPreview] = useState<{ cron: string; valid: boolean; fires: string[] } | null>(null);
const [previewFor, setPreviewFor] = useState<string | null>(null);
async function load() {
try { setRows((await listFlowSchedules()) || []); } catch (e: any) { setErr(e.message); }
}
useEffect(() => {
load();
listFlows().then(setFlows).catch(() => {});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const flowName = (id?: string) => (flows.find((f) => f.id === id)?.name as string) || id || '-';
async function toggleEnabled(r: any) {
setBusy(true); setErr('');
try {
await setFlowScheduleEnabled(r.id, r.enabledMark !== 1);
await load();
} catch (e: any) { setErr(e.message); } finally { setBusy(false); }
}
async function trigger(r: any) {
setBusy(true); setErr('');
try {
const res = await triggerFlowScheduleNow(r.id);
await load();
setErr('');
window.alert(`已触发:${r.name}\nrunId=${res.runId || '-'}\n派发状态=${res.status}`);
} catch (e: any) { setErr(e.message); } finally { setBusy(false); }
}
async function doPreview(r: any) {
try {
const res: any = await previewFlowSchedule(r.cron, 5);
setPreview({ cron: res.cron, valid: res.valid, fires: (res.fires || []).map((d: string) => fmt(d)) });
setPreviewFor(r.id);
} catch (e: any) { setErr(e.message); }
}
async function save() {
try {
await saveFlowSchedule(editing);
setEditing(null); setErr(''); await load();
} catch (e: any) { setErr(e.message); }
}
async function remove(id: string) {
if (!window.confirm('确认删除该调度记录?(软删 f_delete_mark=1)')) return;
try { await deleteFlowSchedule(id); await load(); } catch (e: any) { setErr(e.message); }
}
const editingFlowOptions = (
<select
style={input}
value={editing?.flowId || ''}
onChange={(e) => setEditing({ ...editing, flowId: e.target.value })}
>
<option value="">— 选择流程 —</option>
{flows.map((f) => (
<option key={f.id} value={f.id}>{f.name}</option>
))}
</select>
);
return (
<CrudPage
title="周期调度"
entity="FlowSchedule"
columns={[{key:'name',label:'名称'}, {key:'flowId',label:'流程'}, {key:'cron',label:'Cron'}, {key:'enabledMark',label:'启用'}, {key:'lastStatus',label:'上次状态'}]}
fields={[{key:'name',label:'名称'}, {key:'flowId',label:'流程'}, {key:'cron',label:'Cron'}, {key:'enabledMark',label:'启用'}, {key:'lastStatus',label:'上次状态'}]}
api={{ list: listFlowSchedules, save: saveFlowSchedule, remove: deleteFlowSchedule }}
readonly={false}
/>
<div style={wrap}>
<div style={card}>
<div style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
<button style={{ ...btnGhost, padding: '5px 10px', fontSize: 12 }} onClick={() => nav('/')} title="返回工作台">← 门户</button>
<h2 style={{ margin: 0, fontSize: 17, fontWeight: 650 }}>周期调度</h2>
<span style={{ color: '#6b7a8c', fontSize: 11, fontFamily: 'ui-monospace, monospace' }}>/api/ssw/sswflow/FlowSchedule</span>
<div style={{ marginLeft: 'auto', display: 'flex', gap: 8 }}>
<button style={btn} onClick={load}>刷新</button>
{!editing && <button style={btn} onClick={() => setEditing({ cron: DEFAULT_CRON, enabledMark: 1, misfirePolicy: 'FIRE_NOW', runScope: '{"mode":"FULL"}' })}>新增</button>}
</div>
</div>
<div style={{ marginTop: 12, fontSize: 12, color: '#9aa7b5', lineHeight: 1.7 }}>
触发规则使用 <b style={{ color: '#cfe3ff' }}>Spring Cron(秒 分 时 日 月 周)</b>,如 <code style={{ color: '#ffd27f' }}>{DEFAULT_CRON}</code> = 每天 02:00:00。
日与周不能同时用 <code>?</code>;两字段都限定取「或」。cron 非法不会触发(不退化成每分钟跑)。
</div>
{err && <div style={{ color: '#ff8a80', marginTop: 10 }}>{err}</div>}
{editing && (
<div style={{ marginTop: 14, padding: 14, background: '#121820', borderRadius: 8 }}>
<h3 style={{ marginTop: 0 }}>{editing.id ? '编辑' : '新增'}周期调度</h3>
<div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'flex-end' }}>
<label style={fieldStyle}>名称
<input style={input} value={editing.name ?? ''} onChange={(e) => setEditing({ ...editing, name: e.target.value })} />
</label>
<label style={fieldStyle}>流程
{editingFlowOptions}
</label>
<label style={fieldStyle}>Cron(秒 分 时 日 月 周)
<input style={input} value={editing.cron ?? ''} placeholder={DEFAULT_CRON}
onChange={(e) => setEditing({ ...editing, cron: e.target.value })} />
</label>
<label style={fieldStyle}>运行范围 runScope
<input style={input} value={editing.runScope ?? ''} placeholder='{"mode":"FULL"}'
onChange={(e) => setEditing({ ...editing, runScope: e.target.value })} />
</label>
<label style={fieldStyle}>漏触发策略
<input style={input} value={editing.misfirePolicy ?? 'FIRE_NOW'} placeholder="FIRE_NOW"
onChange={(e) => setEditing({ ...editing, misfirePolicy: e.target.value })} />
</label>
<label style={{ ...fieldStyle, flexDirection: 'row', alignItems: 'center', gap: 6 }}>
<input type="checkbox" checked={editing.enabledMark === 1}
onChange={(e) => setEditing({ ...editing, enabledMark: e.target.checked ? 1 : 0 })} />
启用(到点自动起 run)
</label>
</div>
<div style={{ display: 'flex', gap: 8, marginTop: 12 }}>
<button style={btn} onClick={save} disabled={busy}>保存</button>
<button style={btnGhost} onClick={() => setEditing(null)}>取消</button>
</div>
</div>
)}
<div style={{ overflowX: 'auto', marginTop: 12 }}>
<table style={{ ...tableStyle, marginTop: 0, minWidth: '100%', whiteSpace: 'nowrap' }}>
<thead>
<tr>
{['名称', '流程', 'Cron', '状态', '下次触发', '上次状态', '上次触发', '上次 run', '操作'].map((h) => (
<th key={h} style={{ ...th, whiteSpace: 'nowrap' }}>{h}</th>
))}
</tr>
</thead>
<tbody>
{rows.map((r) => {
const st = fmtStatus(r.lastStatus);
const on = r.enabledMark === 1;
return (
<tr key={r.id}>
<td style={td}>{r.name || '-'}</td>
<td style={td}>{flowName(r.flowId)}</td>
<td style={{ ...td, fontFamily: 'ui-monospace, monospace' }}>{r.cron || '-'}</td>
<td style={td}>
<span style={{ ...chipStyle, color: on ? '#5ad19a' : '#9aa7b5', background: on ? '#16331f' : '#222c37' }}>
{on ? '● 启用' : '○ 停用'}
</span>
</td>
<td style={td}>{fmt(r.nextFireTime)}</td>
<td style={{ ...td, color: st.color }}>{st.text}</td>
<td style={td}>{fmt(r.lastFireTime)}</td>
<td style={{ ...td, fontFamily: 'ui-monospace, monospace' }}>{fmt(r.lastRunId)}</td>
<td style={td}>
<button style={{ ...btnGhost, marginRight: 6 }} disabled={busy} onClick={() => toggleEnabled(r)}>{on ? '停用' : '启用'}</button>
<button style={{ ...btnGhost, marginRight: 6 }} disabled={busy} onClick={() => trigger(r)}>立即触发</button>
<button style={{ ...btnGhost, marginRight: 6 }} disabled={busy} onClick={() => doPreview(r)}>预览</button>
<button style={{ ...btnGhost, marginRight: 6 }} onClick={() => setEditing({ ...r })}>编辑</button>
<button style={btnDanger} onClick={() => remove(r.id)}>删除</button>
</td>
</tr>
);
})}
{rows.length === 0 && <tr><td style={td} colSpan={9}>暂无调度(新增后启用即到点自动起 run)</td></tr>}
</tbody>
</table>
</div>
{preview && (
<div style={{ marginTop: 14, padding: 14, background: '#121820', borderRadius: 8 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
<h3 style={{ margin: 0 }}>未来 5 次触发预览</h3>
<span style={{ ...chipStyle, color: preview.valid ? '#5ad19a' : '#ff8a80', background: preview.valid ? '#16331f' : '#3a1f1f' }}>
{preview.valid ? 'cron 合法' : 'cron 非法'}
</span>
<code style={{ color: '#ffd27f', fontSize: 12 }}>{preview.cron}</code>
<button style={{ ...btnGhost, marginLeft: 'auto' }} onClick={() => { setPreview(null); setPreviewFor(null); }}>关闭</button>
</div>
{preview.valid ? (
<ul style={{ margin: '10px 0 0', paddingLeft: 18, fontSize: 13, color: '#dce6f0', lineHeight: 1.9 }}>
{preview.fires.map((f, i) => <li key={i}>{f}</li>)}
</ul>
) : (
<div style={{ marginTop: 8, fontSize: 12, color: '#ff8a80' }}>该 cron 无法解析(应为 6 位:秒 分 时 日 月 周,且日与周不能同时为 ?)。</div>
)}
</div>
)}
</div>
</div>
);
}
const fieldStyle: React.CSSProperties = {
display: 'flex', flexDirection: 'column', gap: 4, fontSize: 12, color: '#9aa7b5',
};
const chipStyle: React.CSSProperties = {
display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11,
padding: '2px 8px', borderRadius: 10, whiteSpace: 'nowrap',
};