@mldong/jeeflow 1.8.51 → 1.8.53

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/engine.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { ProcessInstance } from './model.js';
1
+ import { ProcessInstance, type ProcessTask } from './model.js';
2
2
  import type { ProcessRepository, ProcessExtRepository, UserProvider, IDGenerator, ExpressionEvaluator } from './spi.js';
3
3
  import { type EngineExtensions, type ProcessEvent } from './extensions.js';
4
4
  import { HandlerRegistry } from './registry.js';
@@ -40,10 +40,10 @@ export declare function parseActorIds(v: any): string[];
40
40
  export declare const parseCcActors: (v: any) => string[];
41
41
  export interface Engine {
42
42
  startProcessInstanceById(defineId: string, operator: string, args?: Record<string, any>): Promise<ProcessInstance>;
43
- executeProcessTask(taskId: string, operator: string, args?: Record<string, any>): Promise<ProcessInstance>;
44
- executeAndJumpToEnd(taskId: string, operator: string, args?: Record<string, any>): Promise<ProcessInstance>;
45
- executeAndJumpTask(taskId: string, operator: string, args: Record<string, any>, targetTaskName?: string): Promise<ProcessInstance>;
46
- executeAndJumpToFirstTaskNode(taskId: string, operator: string, args?: Record<string, any>): Promise<ProcessInstance>;
43
+ executeProcessTask(taskId: string, operator: string, args?: Record<string, any>): Promise<ProcessTask[]>;
44
+ executeAndJumpToEnd(taskId: string, operator: string, args?: Record<string, any>): Promise<ProcessTask[]>;
45
+ executeAndJumpTask(taskId: string, operator: string, args: Record<string, any>, targetTaskName?: string): Promise<ProcessTask[]>;
46
+ executeAndJumpToFirstTaskNode(taskId: string, operator: string, args?: Record<string, any>): Promise<ProcessTask[]>;
47
47
  /** 事务包裹(audit8 145-2 / spec/12 §12.2):仓储有事务载体则并入(嵌套经 withTx 的 join 支),
48
48
  * 无(内存仓)则裸跑=显式降级(§12.1 原则 4)。门面动作级包裹也走这一枚。 */
49
49
  inTx<T>(fn: () => Promise<T>): Promise<T>;
@@ -67,6 +67,8 @@ export declare class EngineImpl implements Engine {
67
67
  private userProv?;
68
68
  private idGen?;
69
69
  private exprEval?;
70
+ /** R92:执行族产出列表的每次调用作用域(AsyncLocalStorage,并发安全)。 */
71
+ private readonly createdScope;
70
72
  private ext?;
71
73
  private registry?;
72
74
  private surrogateRepo?;
@@ -99,12 +101,19 @@ export declare class EngineImpl implements Engine {
99
101
  setExtensions(ext: EngineExtensions): void;
100
102
  setRegistry(reg: HandlerRegistry): void;
101
103
  private interceptorCache;
102
- /** 定义级拦截器解析(issue 34,对齐 Java 模型级 postInterceptors):
103
- * 流程定义顶层 postInterceptors 声明 → 按名从 interceptorRegistry 取(未声明该流程不触发);
104
- * 未声明 → 回落引擎级列表(向后兼容)。结果按 defineId 缓存。
104
+ /** 流程根 pre/post 声明缓存(每 defineId 只回查一行定义):节点档拆开后若逐节点读定义行,
105
+ * 就把 issue 34 的"读一次"放大成逐任务读——spec.test 的 defineReads 次数不变量钉的就是它。 */
106
+ private rootDeclCache;
107
+ /** 定义级/节点级拦截器解析(issue 34 + audit8 R91,对齐 java `NodeModel.java:49-59`):
108
+ * 档位=`pre`/`post` 两档各自独立取串——节点 properties 声明优先,串空才回落流程根同名键,
109
+ * **两档不叠加**(spec02 §3「节点级拦截器的优先序、回落与键形」);两档都没声明才回落引擎级列表
110
+ * (向后兼容)。解析键=注册名(键形按丙=各家注册表沿用 java 全类名串,本栈不另发明短名)。
111
+ * 结果缓存键含 defineId+节点+档位(issues/234 §4.2:按 defineId 单键会把两个节点的声明串档)。
105
112
  * issues/60:解析与校验分离——定义读取/JSON 解析失败回落引擎级(现状语义),
106
- * 声明中存在未注册名时抛错(不静默跳过),且错误不写缓存保证持续报错。 */
113
+ * 声明中存在未注册名时抛错(不静默跳过,带节点 id 与档位),且错误不写缓存保证持续报错。 */
107
114
  private resolveInterceptors;
115
+ /** 流程根 pre/post 声明:每一定义只回查一行(读取/JSON 解析失败按 issues/60 现状语义视作"根级未声明",同样缓存)。 */
116
+ private resolveRootDecls;
108
117
  private firePre;
109
118
  /** 表达式求值(v1.5.0,门面 highLight 决策分支过滤用) */
110
119
  evalExpr(expr: string, vars: Record<string, any>): Promise<any>;
@@ -149,15 +158,21 @@ export declare class EngineImpl implements Engine {
149
158
  /** 事务包裹:有事务载体(JDBC `withTx`)则整段并入外层/自开一段;无(内存仓)裸跑。
150
159
  * 引擎入口包裹与门面动作级包裹都走这一枚 —— 嵌套调用由 withTx 的 join 支并入最外层。 */
151
160
  inTx<T>(fn: () => Promise<T>): Promise<T>;
161
+ /** 提交后腿通道(audit8 R77 读法一,issues/234 §4.3/spec12 §12.3.1;java 形状=监听器侧自取
162
+ * afterCommit,php 侧 R25 已收口同形):监听器/集成层把"必须看到已提交世界"的那一腿(反查、
163
+ * 外发通知、二次写)交到这里声明 ⇒ COMMIT 之后执行、回滚整批丢弃。
164
+ * 没有活动事务(或仓储没这条通道)⇒ 立即执行,行为与上一版逐字一致。
165
+ * ⚠ 引擎自身的 fire 不经过这里:派发点与「监听器随事件拿到动作事务连接」由 145-3 钉住。 */
166
+ runAfterCommit(fn: () => any | Promise<any>): Promise<void>;
152
167
  startProcessInstanceById(defineId: string, operator: string, args?: Record<string, any>): Promise<ProcessInstance>;
153
168
  private startProcessInstanceByIdInner;
154
- executeProcessTask(taskId: string, operator: string, args?: Record<string, any>): Promise<ProcessInstance>;
169
+ executeProcessTask(taskId: string, operator: string, args?: Record<string, any>): Promise<ProcessTask[]>;
155
170
  private executeProcessTaskInner;
156
- executeAndJumpToEnd(taskId: string, operator: string, args?: Record<string, any>): Promise<ProcessInstance>;
171
+ executeAndJumpToEnd(taskId: string, operator: string, args?: Record<string, any>): Promise<ProcessTask[]>;
157
172
  private executeAndJumpToEndInner;
158
- executeAndJumpTask(taskId: string, operator: string, args?: Record<string, any>, targetTaskName?: string): Promise<ProcessInstance>;
173
+ executeAndJumpTask(taskId: string, operator: string, args?: Record<string, any>, targetTaskName?: string): Promise<ProcessTask[]>;
159
174
  private executeAndJumpTaskInner;
160
- executeAndJumpToFirstTaskNode(taskId: string, operator: string, args?: Record<string, any>): Promise<ProcessInstance>;
175
+ executeAndJumpToFirstTaskNode(taskId: string, operator: string, args?: Record<string, any>): Promise<ProcessTask[]>;
161
176
  private executeAndJumpToFirstTaskNodeInner;
162
177
  private prepareExecuteTask;
163
178
  private isFirstTaskNode;
package/dist/engine.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
1
2
  import { TypeStart, TypeEnd, TypeTask, TypeDecision, TypeFork, TypeJoin, TypeCustom, KnownNodeTypes, ProcessInstance, InstanceState, TaskState, SubmitType, } from './model.js';
2
3
  // issues/141 G2:cc 写侧判重的 java `default` 方法在 TS 里的对应物(第三方仓储未实现判重 SPI 时兜旧行为)
3
4
  // issues/141 G10:归属值单值/集合归一的**那一份**判据(漏斗层与写侧层共用;issues/142 B 批
@@ -114,6 +115,8 @@ export class EngineImpl {
114
115
  userProv;
115
116
  idGen;
116
117
  exprEval;
118
+ /** R92:执行族产出列表的每次调用作用域(AsyncLocalStorage,并发安全)。 */
119
+ createdScope = new AsyncLocalStorage();
117
120
  ext;
118
121
  registry;
119
122
  // issues/116:委托代理自动生效——内置能力,注入查询源后默认开启
@@ -190,52 +193,74 @@ export class EngineImpl {
190
193
  setExtensions(ext) {
191
194
  this.ext = ext;
192
195
  this.interceptorCache = new Map();
196
+ this.rootDeclCache = new Map();
193
197
  }
194
198
  setRegistry(reg) { this.registry = reg; }
195
199
  interceptorCache = new Map();
196
- /** 定义级拦截器解析(issue 34,对齐 Java 模型级 postInterceptors):
197
- * 流程定义顶层 postInterceptors 声明 → 按名从 interceptorRegistry 取(未声明该流程不触发);
198
- * 未声明 → 回落引擎级列表(向后兼容)。结果按 defineId 缓存。
200
+ /** 流程根 pre/post 声明缓存(每 defineId 只回查一行定义):节点档拆开后若逐节点读定义行,
201
+ * 就把 issue 34 的"读一次"放大成逐任务读——spec.test 的 defineReads 次数不变量钉的就是它。 */
202
+ rootDeclCache = new Map();
203
+ /** 定义级/节点级拦截器解析(issue 34 + audit8 R91,对齐 java `NodeModel.java:49-59`):
204
+ * 档位=`pre`/`post` 两档各自独立取串——节点 properties 声明优先,串空才回落流程根同名键,
205
+ * **两档不叠加**(spec02 §3「节点级拦截器的优先序、回落与键形」);两档都没声明才回落引擎级列表
206
+ * (向后兼容)。解析键=注册名(键形按丙=各家注册表沿用 java 全类名串,本栈不另发明短名)。
207
+ * 结果缓存键含 defineId+节点+档位(issues/234 §4.2:按 defineId 单键会把两个节点的声明串档)。
199
208
  * issues/60:解析与校验分离——定义读取/JSON 解析失败回落引擎级(现状语义),
200
- * 声明中存在未注册名时抛错(不静默跳过),且错误不写缓存保证持续报错。 */
201
- async resolveInterceptors(inst) {
209
+ * 声明中存在未注册名时抛错(不静默跳过,带节点 id 与档位),且错误不写缓存保证持续报错。 */
210
+ async resolveInterceptors(node, inst, phase) {
202
211
  if (!this.ext)
203
212
  return [];
204
213
  const defineId = inst.defineId;
214
+ const key = `${defineId}|${node.id}|${phase}`;
205
215
  if (defineId == null)
206
216
  return this.ext.interceptors ?? [];
207
- const cached = this.interceptorCache.get(defineId);
217
+ const cached = this.interceptorCache.get(key);
208
218
  if (cached)
209
219
  return cached;
210
- let list = this.ext.interceptors ?? [];
211
- let declared = '';
220
+ const prop = `${phase}Interceptors`;
221
+ let declared = String(node.properties?.[prop] ?? '').trim();
222
+ if (!declared) {
223
+ const list = this.ext.interceptors ?? [];
224
+ declared = (await this.resolveRootDecls(defineId))[phase];
225
+ if (!declared) {
226
+ this.interceptorCache.set(key, list);
227
+ return list;
228
+ }
229
+ }
230
+ const list = [];
231
+ for (const name of declared.split(',').map(n => n.trim())) {
232
+ if (!name)
233
+ continue;
234
+ const ic = this.ext.interceptorRegistry?.[name];
235
+ if (!ic)
236
+ throw new Error(`${prop} 声明的拦截器未注册: ${name}(nodeId=${node.id})`);
237
+ list.push(ic);
238
+ }
239
+ this.interceptorCache.set(key, list);
240
+ return list;
241
+ }
242
+ /** 流程根 pre/post 声明:每一定义只回查一行(读取/JSON 解析失败按 issues/60 现状语义视作"根级未声明",同样缓存)。 */
243
+ async resolveRootDecls(defineId) {
244
+ const cached = this.rootDeclCache.get(defineId);
245
+ if (cached)
246
+ return cached;
247
+ let decl = { pre: '', post: '' };
212
248
  try {
213
249
  const def = await this.repo.findDefineById(defineId);
214
250
  if (def) {
215
251
  const content = typeof def.content === 'string' ? def.content : new TextDecoder().decode(def.content);
216
252
  const meta = JSON.parse(content);
217
- declared = String(meta.postInterceptors ?? '').trim();
253
+ decl = { pre: String(meta.preInterceptors ?? '').trim(), post: String(meta.postInterceptors ?? '').trim() };
218
254
  }
219
255
  }
220
256
  catch { /* 定义读取/JSON 解析失败回落引擎级 */ }
221
- if (declared) {
222
- list = [];
223
- for (const name of declared.split(',').map(n => n.trim())) {
224
- if (!name)
225
- continue;
226
- const ic = this.ext.interceptorRegistry?.[name];
227
- if (!ic)
228
- throw new Error(`postInterceptors 声明的拦截器未注册: ${name}`);
229
- list.push(ic);
230
- }
231
- }
232
- this.interceptorCache.set(defineId, list);
233
- return list;
257
+ this.rootDeclCache.set(defineId, decl);
258
+ return decl;
234
259
  }
235
260
  async firePre(node, inst) {
236
261
  if (!this.ext?.interceptors && !this.ext?.interceptorRegistry)
237
262
  return true;
238
- const list = await this.resolveInterceptors(inst);
263
+ const list = await this.resolveInterceptors(node, inst, 'pre');
239
264
  for (const ic of [...list].sort((a, b) => a.order - b.order))
240
265
  if (!(await ic.preHandle(node, inst)))
241
266
  return false;
@@ -250,7 +275,7 @@ export class EngineImpl {
250
275
  async firePost(node, inst) {
251
276
  if (!this.ext?.interceptors && !this.ext?.interceptorRegistry)
252
277
  return;
253
- for (const ic of await this.resolveInterceptors(inst))
278
+ for (const ic of await this.resolveInterceptors(node, inst, 'post'))
254
279
  await ic.postHandle(node, inst);
255
280
  }
256
281
  async fireEvent(evt) {
@@ -334,6 +359,16 @@ export class EngineImpl {
334
359
  async inTx(fn) {
335
360
  return this.repo.withTx ? this.repo.withTx(fn) : fn();
336
361
  }
362
+ /** 提交后腿通道(audit8 R77 读法一,issues/234 §4.3/spec12 §12.3.1;java 形状=监听器侧自取
363
+ * afterCommit,php 侧 R25 已收口同形):监听器/集成层把"必须看到已提交世界"的那一腿(反查、
364
+ * 外发通知、二次写)交到这里声明 ⇒ COMMIT 之后执行、回滚整批丢弃。
365
+ * 没有活动事务(或仓储没这条通道)⇒ 立即执行,行为与上一版逐字一致。
366
+ * ⚠ 引擎自身的 fire 不经过这里:派发点与「监听器随事件拿到动作事务连接」由 145-3 钉住。 */
367
+ async runAfterCommit(fn) {
368
+ if (this.repo.afterCommit?.call(this.repo, fn))
369
+ return;
370
+ await fn();
371
+ }
337
372
  // ─── Start ─────────────────────────────────────────────────────────────────
338
373
  async startProcessInstanceById(defineId, operator, args = {}) {
339
374
  // audit8 145-2①:入口级包裹——直连引擎的调用方也拿到"一次动作一笔原子"(spec/12 §12.2)。
@@ -378,7 +413,12 @@ export class EngineImpl {
378
413
  // ─── Execute ───────────────────────────────────────────────────────────────
379
414
  async executeProcessTask(taskId, operator, args = {}) {
380
415
  // audit8 145-2①:入口级包裹(同 startProcessInstanceById 注释)
381
- return this.inTx(() => this.executeProcessTaskInner(taskId, operator, args));
416
+ const created = [];
417
+ // spec04 §完成任务:公开方法回传「本次动作产出的任务行」(基准=java exec.getProcessTaskList())。
418
+ // 作用域用 AsyncLocalStorage:一个 EngineImpl 实例并发处理多个请求,class 字段会互踩;
419
+ // 而 node 没有 go 那样的 ctx 可挂,ALS 是等价的每次调用作用域(见 R92 notes)。
420
+ await this.createdScope.run(created, () => this.inTx(() => this.executeProcessTaskInner(taskId, operator, args)));
421
+ return created;
382
422
  }
383
423
  async executeProcessTaskInner(taskId, operator, args = {}) {
384
424
  const { task, inst, flow, vars } = await this.prepareExecuteTask(taskId, operator, args);
@@ -439,6 +479,7 @@ export class EngineImpl {
439
479
  // 变量源=实例变量(与建单同档),取时基准=本行 createTime 用的同一个 now。
440
480
  applyNodeExpireTime(nt, curNode.properties?.expireTime, inst.variables, now);
441
481
  await this.repo.saveTask(nt);
482
+ this.createdScope.getStore()?.push(nt);
442
483
  // PROCESS_TASK_START:顺序会签推进新任务落库后 fire(对齐 Java CreateTaskHandler / Rust)
443
484
  await this.fireEvent({ type: EventType.ProcessTaskStart, instanceId: inst.id, taskId: nt.id, nodeId: curNode.id, operator, actors: [...nt.actorIds] });
444
485
  return finishExecute();
@@ -504,7 +545,12 @@ export class EngineImpl {
504
545
  // ─── Reject ────────────────────────────────────────────────────────────────
505
546
  async executeAndJumpToEnd(taskId, operator, args = {}) {
506
547
  // audit8 145-2①:入口级包裹(同 startProcessInstanceById 注释)
507
- return this.inTx(() => this.executeAndJumpToEndInner(taskId, operator, args));
548
+ const created = [];
549
+ // spec04 §完成任务:公开方法回传「本次动作产出的任务行」(基准=java exec.getProcessTaskList())。
550
+ // 作用域用 AsyncLocalStorage:一个 EngineImpl 实例并发处理多个请求,class 字段会互踩;
551
+ // 而 node 没有 go 那样的 ctx 可挂,ALS 是等价的每次调用作用域(见 R92 notes)。
552
+ await this.createdScope.run(created, () => this.inTx(() => this.executeAndJumpToEndInner(taskId, operator, args)));
553
+ return created;
508
554
  }
509
555
  async executeAndJumpToEndInner(taskId, operator, args = {}) {
510
556
  const { inst } = await this.prepareExecuteTask(taskId, operator, args);
@@ -519,7 +565,12 @@ export class EngineImpl {
519
565
  // ─── Jump(ROLLBACK 空 target / JUMP 命名 target,boot2 executeAndJumpTask)────
520
566
  async executeAndJumpTask(taskId, operator, args = {}, targetTaskName) {
521
567
  // audit8 145-2①:入口级包裹(同 startProcessInstanceById 注释)
522
- return this.inTx(() => this.executeAndJumpTaskInner(taskId, operator, args, targetTaskName));
568
+ const created = [];
569
+ // spec04 §完成任务:公开方法回传「本次动作产出的任务行」(基准=java exec.getProcessTaskList())。
570
+ // 作用域用 AsyncLocalStorage:一个 EngineImpl 实例并发处理多个请求,class 字段会互踩;
571
+ // 而 node 没有 go 那样的 ctx 可挂,ALS 是等价的每次调用作用域(见 R92 notes)。
572
+ await this.createdScope.run(created, () => this.inTx(() => this.executeAndJumpTaskInner(taskId, operator, args, targetTaskName)));
573
+ return created;
523
574
  }
524
575
  async executeAndJumpTaskInner(taskId, operator, args = {}, targetTaskName) {
525
576
  const { task, inst, flow, vars } = await this.prepareExecuteTask(taskId, operator, args);
@@ -546,7 +597,12 @@ export class EngineImpl {
546
597
  // ─── Jump To First Task(退回发起人,boot2 ROLLBACK_TO_OPERATOR=6)────────────
547
598
  async executeAndJumpToFirstTaskNode(taskId, operator, args = {}) {
548
599
  // audit8 145-2①:入口级包裹(同 startProcessInstanceById 注释)
549
- return this.inTx(() => this.executeAndJumpToFirstTaskNodeInner(taskId, operator, args));
600
+ const created = [];
601
+ // spec04 §完成任务:公开方法回传「本次动作产出的任务行」(基准=java exec.getProcessTaskList())。
602
+ // 作用域用 AsyncLocalStorage:一个 EngineImpl 实例并发处理多个请求,class 字段会互踩;
603
+ // 而 node 没有 go 那样的 ctx 可挂,ALS 是等价的每次调用作用域(见 R92 notes)。
604
+ await this.createdScope.run(created, () => this.inTx(() => this.executeAndJumpToFirstTaskNodeInner(taskId, operator, args)));
605
+ return created;
550
606
  }
551
607
  async executeAndJumpToFirstTaskNodeInner(taskId, operator, args = {}) {
552
608
  const { inst, flow, vars } = await this.prepareExecuteTask(taskId, operator, args);
@@ -652,6 +708,7 @@ export class EngineImpl {
652
708
  if (eff.length > 1)
653
709
  nt.actorIds = eff;
654
710
  await this.repo.saveTask(nt);
711
+ this.createdScope.getStore()?.push(nt);
655
712
  await this.fireEvent({ type: EventType.ProcessTaskStart, instanceId: inst.id,
656
713
  taskId: nt.id, nodeId: prev.id, operator, actors: [...nt.actorIds] });
657
714
  }
@@ -865,6 +922,7 @@ export class EngineImpl {
865
922
  nt.actorIds = eff;
866
923
  applyNodeExpireTime(nt, expireExpr, expireArgs, now); // 并行会签全员
867
924
  await this.repo.saveTask(nt);
925
+ this.createdScope.getStore()?.push(nt);
868
926
  // PROCESS_TASK_START:任务落库后逐个 fire(会签多任务逐个,对齐 Java CreateTaskHandler)
869
927
  await this.fireEvent({ type: EventType.ProcessTaskStart, instanceId: inst.id, taskId: nt.id, nodeId: node.id, operator, actors: [...nt.actorIds] });
870
928
  }
@@ -883,6 +941,7 @@ export class EngineImpl {
883
941
  nt.actorIds = eff;
884
942
  applyNodeExpireTime(nt, expireExpr, expireArgs, now); // 串行会签首位成员
885
943
  await this.repo.saveTask(nt);
944
+ this.createdScope.getStore()?.push(nt);
886
945
  await this.fireEvent({ type: EventType.ProcessTaskStart, instanceId: inst.id, taskId: nt.id, nodeId: node.id, operator, actors: [...nt.actorIds] });
887
946
  return;
888
947
  }
@@ -894,6 +953,7 @@ export class EngineImpl {
894
953
  nt.actorIds = eff;
895
954
  applyNodeExpireTime(nt, expireExpr, expireArgs, now); // 未配会签类型=全员预创建,与并行同档
896
955
  await this.repo.saveTask(nt);
956
+ this.createdScope.getStore()?.push(nt);
897
957
  await this.fireEvent({ type: EventType.ProcessTaskStart, instanceId: inst.id, taskId: nt.id, nodeId: node.id, operator, actors: [...nt.actorIds] });
898
958
  }
899
959
  return;
@@ -909,6 +969,7 @@ export class EngineImpl {
909
969
  nt.actorIds = effActors;
910
970
  applyNodeExpireTime(nt, expireExpr, expireArgs, now); // 普通建单
911
971
  await this.repo.saveTask(nt);
972
+ this.createdScope.getStore()?.push(nt);
912
973
  await this.fireEvent({ type: EventType.ProcessTaskStart, instanceId: inst.id, taskId: nt.id, nodeId: node.id, operator, actors: [...nt.actorIds] });
913
974
  }
914
975
  /**
@@ -2,6 +2,11 @@ import { AsyncLocalStorage } from 'node:async_hooks';
2
2
  import { ProcessInstance, ProcessTask, type ProcessDefine, type CcInstanceRow, type DefineRow, type InstanceRow, type TaskRow } from '../model.js';
3
3
  import type { IDGenerator, ProcessRepository, QueryCondition, InstanceStatsRow, TaskStatsRow } from '../spi.js';
4
4
  export declare const txStore: AsyncLocalStorage<SqlConnection>;
5
+ export interface AfterCommitScope {
6
+ cbs: Array<() => any | Promise<any>>;
7
+ done: boolean;
8
+ }
9
+ export declare const afterCommitStore: AsyncLocalStorage<AfterCommitScope>;
5
10
  /** 当前事务连接(无事务 ⇒ null)。集成方自研写腿(如 DynamicTableWriter 的 MySQL 实现)
6
11
  * 用它并入引擎事务——spec/12 §12.2 覆盖面:一次动作内所有写腿取同一条连接。 */
7
12
  export declare function currentTxConnection(): SqlConnection | null;
@@ -48,6 +53,10 @@ export declare class JdbcRepository implements ProcessRepository {
48
53
  private readonly adapter;
49
54
  private readonly idGen;
50
55
  constructor(adapter: SqlAdapter, idGen?: IDGenerator);
56
+ /** 登记「本次事务提交之后」执行的回调(audit8 R77 读法一;java 形状=监听器侧自取 afterCommit,
57
+ * php 侧 R25 已收口同形)。返回 false=当前无活动事务 ⇒ 调用方须自行立即执行
58
+ * (门面级没外包事务模板的栈,「落库后」与「提交后」等价)。 */
59
+ afterCommit(fn: () => any | Promise<any>): boolean;
51
60
  private sql;
52
61
  withTx<T>(fn: () => Promise<T>): Promise<T>;
53
62
  /** 返回当前连接:有事务绑定用事务连接,否则从适配器获取 */
@@ -4,7 +4,7 @@
4
4
  // - 本文件是**唯一维护点**:15 个仓储方法的 SQL 逻辑、行映射、ID 生成
5
5
  // - SQL 占位符统一使用 `?`,由各数据库适配器(SqlAdapter)转换为自家风格
6
6
  // (MySQL `?` 原生 / PostgreSQL `$n`)
7
- // - 事务(spec §7.4):withTx 用 AsyncLocalStorage 绑定当前异步上下文的事务连接
7
+ // - 事务(规范 05「事务约定」节):withTx 用 AsyncLocalStorage 绑定当前异步上下文的事务连接
8
8
  //
9
9
  // 新增数据库 = 写一个适配器(约 80 行):实现 SqlAdapter + 连接包装
10
10
  // (execute/fetchOne/fetchAll/begin/commit/rollback)。参考 mysql.ts / postgres.ts。
@@ -40,6 +40,7 @@ const DEFINE_WHITELIST = new Set([
40
40
  // audit8 145-2:**导出**——ext.ts 必须共用这一枚(此前它自带第二枚且从不 run,扩展写腿
41
41
  // 永远逃逸出引擎事务)。集成方写腿也可经 currentTxConnection/transactionAwarePool 并入。
42
42
  export const txStore = new AsyncLocalStorage();
43
+ export const afterCommitStore = new AsyncLocalStorage();
43
44
  /** 当前事务连接(无事务 ⇒ null)。集成方自研写腿(如 DynamicTableWriter 的 MySQL 实现)
44
45
  * 用它并入引擎事务——spec/12 §12.2 覆盖面:一次动作内所有写腿取同一条连接。 */
45
46
  export function currentTxConnection() {
@@ -108,25 +109,48 @@ export class JdbcRepository {
108
109
  this.adapter = adapter;
109
110
  this.idGen = idGen;
110
111
  }
112
+ /** 登记「本次事务提交之后」执行的回调(audit8 R77 读法一;java 形状=监听器侧自取 afterCommit,
113
+ * php 侧 R25 已收口同形)。返回 false=当前无活动事务 ⇒ 调用方须自行立即执行
114
+ * (门面级没外包事务模板的栈,「落库后」与「提交后」等价)。 */
115
+ afterCommit(fn) {
116
+ const sc = afterCommitStore.getStore();
117
+ if (!sc || sc.done)
118
+ return false;
119
+ sc.cbs.push(fn);
120
+ return true;
121
+ }
111
122
  sql(s) {
112
123
  return convertPlaceholder(s, this.adapter.placeholder);
113
124
  }
114
- // ── 事务(spec §7.4:AsyncLocalStorage 绑定连接)─────────────────────────
125
+ // ── 事务(规范 05「事务约定」节:AsyncLocalStorage 绑定连接)─────────────────────────
115
126
  async withTx(fn) {
116
127
  // audit8 145-2③(spec/12 §12.2 归属面):已有活动事务 ⇒ **并入**(不再开第二段事务、
117
128
  // 不提前提交;提交/回滚归最外层)——引擎入口包裹与门面动作级包裹嵌套时落这一支。
118
129
  if (txStore.getStore())
119
130
  return fn();
120
131
  const conn = await this.adapter.acquire();
132
+ const scope = { cbs: [], done: false };
121
133
  try {
122
134
  await conn.begin();
123
135
  try {
124
- const result = await txStore.run(conn, fn);
136
+ const result = await txStore.run(conn, () => afterCommitStore.run(scope, fn));
125
137
  await conn.commit();
138
+ scope.done = true;
139
+ // R77 提交后腿:逐条吞掉自家异常,不打断主流程(登记方自己承担失败语义)
140
+ for (const cb of scope.cbs) {
141
+ try {
142
+ await cb();
143
+ }
144
+ catch (err) {
145
+ console.warn('[jeeflow] afterCommit 回调失败: ' + String(err));
146
+ }
147
+ }
126
148
  return result;
127
149
  }
128
150
  catch (err) {
129
151
  await conn.rollback();
152
+ scope.done = true;
153
+ scope.cbs = []; // R77:回滚 ⇒ 提交后腿整批丢弃(监听器不得看到未提交的世界)
130
154
  throw err;
131
155
  }
132
156
  }
@@ -283,7 +307,7 @@ export class JdbcRepository {
283
307
  'operator=?, expire_time=?, variable=?, update_time=?, update_user=? WHERE id=?'), [inst.state, inst.parentNodeName ?? '', inst.businessNo ?? '', inst.operator,
284
308
  inst.expireTime ?? null, JSON.stringify(inst.variables ?? {}),
285
309
  inst.updateTime, inst.updateUser, inst.id]);
286
- // v1.0.1:级联持久化聚合根内任务状态变更(同连接,spec §7.4)
310
+ // v1.0.1:级联持久化聚合根内任务状态变更(同连接,规范 05「事务约定」节)
287
311
  for (const task of inst.tasks) {
288
312
  if (task.id)
289
313
  await this.updateTaskWithConn(conn, task);
package/dist/spi.d.ts CHANGED
@@ -148,6 +148,10 @@ export interface ProcessRepository {
148
148
  /** 事务载体(audit8 145-2,spec/12 §12.2)——JDBC 仓储天然实现(AsyncLocalStorage);
149
149
  * 内存仓没有此方法 ⇒ 引擎 inTx 显式降级裸跑(§12.1 原则 4)。 */
150
150
  withTx?<T>(fn: () => Promise<T>): Promise<T>;
151
+ /** 提交后腿通道(audit8 R77 读法一,spec/12 §12.3.1):有活动事务时登记回调并返回 true
152
+ * (Commit 后执行、回滚丢弃);无活动事务返回 false ⇒ 调用方须自行立即执行。
153
+ * 内存仓没有此方法 ⇒ 一律立即执行(与"落库后"等价)。 */
154
+ afterCommit?(fn: () => any | Promise<any>): boolean;
151
155
  findDefineById(id: string): Promise<ProcessDefine | null>;
152
156
  findDefineByName(name: string): Promise<ProcessDefine | null>;
153
157
  saveDefine(define: ProcessDefine): Promise<void>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mldong/jeeflow",
3
- "version": "1.8.51",
3
+ "version": "1.8.53",
4
4
  "description": "jeeflow workflow engine — Node.js / TypeScript implementation",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -20,7 +20,7 @@
20
20
  "build": "tsc",
21
21
  "typecheck": "tsc -p tsconfig.check.json",
22
22
  "test": "node --import tsx __tests__/spec.test.ts",
23
- "test-mysql": "node --import tsx --test __tests__/jdbc.test.ts __tests__/tx-tier-145.test.ts",
23
+ "test-mysql": "node --import tsx --test __tests__/jdbc.test.ts __tests__/tx-tier-145.test.ts __tests__/after_commit_r77.test.ts",
24
24
  "demo": "node --import tsx demo/main.ts",
25
25
  "prepublishOnly": "npm run build"
26
26
  },