assignment-user-matcher 1.3.0 → 1.7.0
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/README.md +96 -0
- package/dist/escalation/policy.d.ts +65 -0
- package/dist/escalation/policy.d.ts.map +1 -0
- package/dist/escalation/policy.js +120 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/managers/WorkflowManager.d.ts +59 -1
- package/dist/managers/WorkflowManager.d.ts.map +1 -1
- package/dist/managers/WorkflowManager.js +340 -2
- package/dist/matcher.class.d.ts +124 -4
- package/dist/matcher.class.d.ts.map +1 -1
- package/dist/matcher.class.js +403 -17
- package/dist/queries/pagination.d.ts +5 -0
- package/dist/queries/pagination.d.ts.map +1 -1
- package/dist/queries/pagination.js +13 -1
- package/dist/types/matcher.d.ts +274 -1
- package/dist/types/matcher.d.ts.map +1 -1
- package/dist/utils/keys.d.ts +3 -0
- package/dist/utils/keys.d.ts.map +1 -1
- package/dist/utils/keys.js +13 -0
- package/dist/workflow-builder.d.ts +28 -0
- package/dist/workflow-builder.d.ts.map +1 -1
- package/dist/workflow-builder.js +42 -0
- package/dist/workflow-validation.d.ts.map +1 -1
- package/dist/workflow-validation.js +52 -0
- package/package.json +1 -1
- package/dist/queries/index.d.ts +0 -5
- package/dist/queries/index.d.ts.map +0 -1
- package/dist/queries/index.js +0 -20
- package/dist/scoring/index.d.ts +0 -5
- package/dist/scoring/index.d.ts.map +0 -1
- package/dist/scoring/index.js +0 -20
- package/dist/utils/index.d.ts +0 -6
- package/dist/utils/index.d.ts.map +0 -1
- package/dist/utils/index.js +0 -21
|
@@ -23,6 +23,21 @@ class WorkflowManager {
|
|
|
23
23
|
this.throttleWindowStart = 0;
|
|
24
24
|
this.throttleTokensUsed = 0;
|
|
25
25
|
}
|
|
26
|
+
/**
|
|
27
|
+
* Fire the onWorkflowEvent hook, if configured. Best-effort: mirrors
|
|
28
|
+
* onMatchDecision's contract, errors thrown by the callback never affect
|
|
29
|
+
* workflow processing.
|
|
30
|
+
*/
|
|
31
|
+
emitTransition(kind, instance, extra) {
|
|
32
|
+
if (!this.options.onWorkflowEvent)
|
|
33
|
+
return;
|
|
34
|
+
try {
|
|
35
|
+
this.options.onWorkflowEvent({ kind, instance, ...extra });
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
// Swallowed by design — a broken consumer must never affect workflow processing.
|
|
39
|
+
}
|
|
40
|
+
}
|
|
26
41
|
async init() {
|
|
27
42
|
if (this.options.enableWorkflows) {
|
|
28
43
|
await this.initStreamConsumerGroup();
|
|
@@ -98,6 +113,18 @@ class WorkflowManager {
|
|
|
98
113
|
if (!definition) {
|
|
99
114
|
throw new Error(`Workflow definition not found: ${workflowDefinitionId}`);
|
|
100
115
|
}
|
|
116
|
+
// Conservative guard: any assignment step that targets 'initiator'
|
|
117
|
+
// (the default target when unset) needs a real user to assign to, or
|
|
118
|
+
// the run silently stalls at that step instead of failing fast at
|
|
119
|
+
// start. Machine/external steps don't route to a user, so their
|
|
120
|
+
// (absent) targetUser must not count as targeting the initiator.
|
|
121
|
+
const targetsInitiator = definition.steps.some((s) => (s.taskType ?? 'assignment') === 'assignment' && (s.targetUser ?? 'initiator') === 'initiator');
|
|
122
|
+
if (targetsInitiator && this.host.userExists) {
|
|
123
|
+
const exists = await this.host.userExists(userId);
|
|
124
|
+
if (!exists) {
|
|
125
|
+
throw new Error(`Initiator user not found: ${userId}`);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
101
128
|
const now = Date.now();
|
|
102
129
|
const instanceId = (0, crypto_1.randomUUID)();
|
|
103
130
|
this.telemetry.setSpanAttributes(span, {
|
|
@@ -120,11 +147,17 @@ class WorkflowManager {
|
|
|
120
147
|
? JSON.parse(JSON.stringify(definition))
|
|
121
148
|
: undefined,
|
|
122
149
|
};
|
|
150
|
+
// A plain Date.now() score would tie (and, at the exclusive cursor
|
|
151
|
+
// boundary, silently drop) runs started within the same millisecond —
|
|
152
|
+
// realistic under a burst of automated triggers. INCR guarantees a
|
|
153
|
+
// strictly distinct, creation-order-preserving score instead.
|
|
154
|
+
const sequence = await this.redisClient.incr(this.keys.workflowInstanceSequence());
|
|
123
155
|
const multi = this.redisClient.multi();
|
|
124
156
|
multi.hSet(this.keys.workflowInstance(instanceId), 'data', JSON.stringify(instance));
|
|
125
157
|
multi.sAdd(this.keys.workflowInstancesByUser(userId), instanceId);
|
|
126
158
|
multi.hSet(this.keys.workflowInstances(), instanceId, workflowDefinitionId);
|
|
127
159
|
multi.zAdd(this.keys.workflowInstancesActive(), { score: now, value: instanceId });
|
|
160
|
+
multi.zAdd(this.keys.workflowInstancesByTime(), { score: sequence, value: instanceId });
|
|
128
161
|
await multi.exec();
|
|
129
162
|
await this.reliability.emitAuditEvent('WORKFLOW_STARTED', instanceId, {
|
|
130
163
|
definitionId: workflowDefinitionId,
|
|
@@ -142,6 +175,7 @@ class WorkflowManager {
|
|
|
142
175
|
timestamp: now,
|
|
143
176
|
});
|
|
144
177
|
}
|
|
178
|
+
this.emitTransition('run.started', instance, { stepId: definition.initialStepId });
|
|
145
179
|
await this.executeWorkflowStep(instance, definition.initialStepId, definition);
|
|
146
180
|
endSpan();
|
|
147
181
|
return instance;
|
|
@@ -166,6 +200,50 @@ class WorkflowManager {
|
|
|
166
200
|
resolvedDefinition: definition ?? undefined,
|
|
167
201
|
};
|
|
168
202
|
}
|
|
203
|
+
/**
|
|
204
|
+
* List workflow instances (runs) newest-created first, optionally filtered
|
|
205
|
+
* by status and/or workflow definition. Paginated via an opaque cursor
|
|
206
|
+
* (the createdAt score of the last item returned) — pass it back as
|
|
207
|
+
* `cursor` for the next page.
|
|
208
|
+
*/
|
|
209
|
+
async listWorkflowInstances(query = {}) {
|
|
210
|
+
const limit = Math.max(query.limit ?? 50, 1);
|
|
211
|
+
const byTimeKey = this.keys.workflowInstancesByTime();
|
|
212
|
+
const instances = [];
|
|
213
|
+
let upperBound = query.cursor ? `(${query.cursor}` : '+inf';
|
|
214
|
+
let lastScore;
|
|
215
|
+
const scanBatchSize = Math.max(limit * 2, 20);
|
|
216
|
+
// Scan back in time in batches, filtering status/workflowDefinitionId in
|
|
217
|
+
// memory, until we have `limit` matches or the index is exhausted.
|
|
218
|
+
// eslint-disable-next-line no-constant-condition
|
|
219
|
+
while (instances.length < limit) {
|
|
220
|
+
const ids = await this.redisClient.zRangeWithScores(byTimeKey, upperBound, '-inf', {
|
|
221
|
+
REV: true,
|
|
222
|
+
BY: 'SCORE',
|
|
223
|
+
LIMIT: { offset: 0, count: scanBatchSize },
|
|
224
|
+
});
|
|
225
|
+
if (!ids.length)
|
|
226
|
+
break;
|
|
227
|
+
for (const { value: id, score } of ids) {
|
|
228
|
+
const instance = await this.getWorkflowInstance(id);
|
|
229
|
+
lastScore = score;
|
|
230
|
+
if (!instance)
|
|
231
|
+
continue;
|
|
232
|
+
if (query.status && instance.status !== query.status)
|
|
233
|
+
continue;
|
|
234
|
+
if (query.workflowDefinitionId && instance.workflowDefinitionId !== query.workflowDefinitionId)
|
|
235
|
+
continue;
|
|
236
|
+
instances.push(instance);
|
|
237
|
+
if (instances.length >= limit)
|
|
238
|
+
break;
|
|
239
|
+
}
|
|
240
|
+
if (ids.length < scanBatchSize)
|
|
241
|
+
break; // index exhausted
|
|
242
|
+
upperBound = `(${lastScore}`;
|
|
243
|
+
}
|
|
244
|
+
const nextCursor = instances.length >= limit && lastScore !== undefined ? String(lastScore) : undefined;
|
|
245
|
+
return { instances, nextCursor };
|
|
246
|
+
}
|
|
169
247
|
async getActiveWorkflowsForUser(userId) {
|
|
170
248
|
const instanceIds = await this.redisClient.sMembers(this.keys.workflowInstancesByUser(userId));
|
|
171
249
|
if (instanceIds.length === 0)
|
|
@@ -186,6 +264,12 @@ class WorkflowManager {
|
|
|
186
264
|
}
|
|
187
265
|
return instances;
|
|
188
266
|
}
|
|
267
|
+
/**
|
|
268
|
+
* Cancel a running workflow instance. Cleans up its outstanding
|
|
269
|
+
* assignment(s) — the current step's assignment, or any still-pending
|
|
270
|
+
* parallel branch assignments — so a cancelled run doesn't leave orphaned
|
|
271
|
+
* work queued/pending forever, and clears their step timeouts.
|
|
272
|
+
*/
|
|
189
273
|
async cancelWorkflow(instanceId) {
|
|
190
274
|
const instance = await this.getWorkflowInstance(instanceId);
|
|
191
275
|
if (!instance) {
|
|
@@ -193,7 +277,31 @@ class WorkflowManager {
|
|
|
193
277
|
}
|
|
194
278
|
const expectedVersion = instance.version;
|
|
195
279
|
instance.status = 'cancelled';
|
|
280
|
+
const outstandingAssignmentIds = [];
|
|
281
|
+
const outstandingStepIds = [];
|
|
282
|
+
if (instance.currentAssignmentId) {
|
|
283
|
+
outstandingAssignmentIds.push(instance.currentAssignmentId);
|
|
284
|
+
if (instance.currentStepId)
|
|
285
|
+
outstandingStepIds.push(instance.currentStepId);
|
|
286
|
+
}
|
|
287
|
+
for (const branch of instance.parallelBranches ?? []) {
|
|
288
|
+
if (branch.status === 'pending') {
|
|
289
|
+
outstandingAssignmentIds.push(branch.assignmentId);
|
|
290
|
+
outstandingStepIds.push(branch.stepId);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
196
293
|
await this.saveInstance(instance, expectedVersion);
|
|
294
|
+
for (const stepId of outstandingStepIds) {
|
|
295
|
+
await this.redisClient.zRem(this.keys.workflowStepExpiryIndex(), `${instanceId}|${stepId}`);
|
|
296
|
+
await this.redisClient.del(this.keys.workflowStepExpiry(instanceId, stepId));
|
|
297
|
+
}
|
|
298
|
+
for (const assignmentId of outstandingAssignmentIds) {
|
|
299
|
+
if (this.host.removeAssignment) {
|
|
300
|
+
await this.host.removeAssignment(assignmentId);
|
|
301
|
+
}
|
|
302
|
+
await this.redisClient.del(this.keys.workflowAssignmentLink(assignmentId));
|
|
303
|
+
}
|
|
304
|
+
this.emitTransition('run.cancelled', instance);
|
|
197
305
|
return true;
|
|
198
306
|
}
|
|
199
307
|
async executeWorkflowStep(instance, stepId, definition) {
|
|
@@ -205,6 +313,7 @@ class WorkflowManager {
|
|
|
205
313
|
if (step.parallelStepIds && step.parallelStepIds.length > 0) {
|
|
206
314
|
const branches = [];
|
|
207
315
|
const machineParallelSteps = [];
|
|
316
|
+
const externalParallelSteps = [];
|
|
208
317
|
for (const parallelStepId of step.parallelStepIds) {
|
|
209
318
|
const parallelStep = definition.steps.find((s) => s.id === parallelStepId);
|
|
210
319
|
if (!parallelStep)
|
|
@@ -222,6 +331,18 @@ class WorkflowManager {
|
|
|
222
331
|
status: 'pending',
|
|
223
332
|
});
|
|
224
333
|
}
|
|
334
|
+
else if (taskType === 'external') {
|
|
335
|
+
if (!parallelStep.external?.name) {
|
|
336
|
+
throw new Error(`External step "${parallelStep.id}" is missing external.name`);
|
|
337
|
+
}
|
|
338
|
+
const syntheticAssignmentId = this.deterministicAssignmentId(instance, parallelStepId);
|
|
339
|
+
externalParallelSteps.push({ stepId: parallelStepId, assignmentId: syntheticAssignmentId });
|
|
340
|
+
branches.push({
|
|
341
|
+
stepId: parallelStepId,
|
|
342
|
+
assignmentId: syntheticAssignmentId,
|
|
343
|
+
status: 'pending',
|
|
344
|
+
});
|
|
345
|
+
}
|
|
225
346
|
else {
|
|
226
347
|
const assignment = await this.createWorkflowAssignment(instance, parallelStep, definition);
|
|
227
348
|
branches.push({
|
|
@@ -245,6 +366,16 @@ class WorkflowManager {
|
|
|
245
366
|
continue;
|
|
246
367
|
await this.executeMachineStep(instance, parallelStep, definition, machineStep.assignmentId);
|
|
247
368
|
}
|
|
369
|
+
for (const externalStep of externalParallelSteps) {
|
|
370
|
+
const parallelStep = definition.steps.find((s) => s.id === externalStep.stepId);
|
|
371
|
+
if (!parallelStep)
|
|
372
|
+
continue;
|
|
373
|
+
this.emitTransition('step.ready', instance, {
|
|
374
|
+
stepId: externalStep.stepId,
|
|
375
|
+
assignmentId: externalStep.assignmentId,
|
|
376
|
+
payload: { name: parallelStep.external.name, input: parallelStep.external.input },
|
|
377
|
+
});
|
|
378
|
+
}
|
|
248
379
|
return;
|
|
249
380
|
}
|
|
250
381
|
const taskType = step.taskType ?? 'assignment';
|
|
@@ -262,6 +393,25 @@ class WorkflowManager {
|
|
|
262
393
|
await this.executeMachineStep(instance, step, definition);
|
|
263
394
|
return;
|
|
264
395
|
}
|
|
396
|
+
if (taskType === 'external') {
|
|
397
|
+
if (!step.external?.name) {
|
|
398
|
+
throw new Error(`External step "${step.id}" is missing external.name`);
|
|
399
|
+
}
|
|
400
|
+
instance.currentAssignmentId = undefined;
|
|
401
|
+
instance.currentStepId = stepId;
|
|
402
|
+
const timeoutMs = step.timeoutMs ?? definition.defaultTimeoutMs;
|
|
403
|
+
if (!timeoutMs) {
|
|
404
|
+
throw new Error(`External step "${step.id}" requires a timeoutMs (or the workflow's defaultTimeoutMs)`);
|
|
405
|
+
}
|
|
406
|
+
await this.setStepTimeout(instance.id, stepId, timeoutMs);
|
|
407
|
+
await this.saveInstance(instance, expectedVersion);
|
|
408
|
+
this.emitTransition('step.ready', instance, {
|
|
409
|
+
stepId,
|
|
410
|
+
assignmentId: this.deterministicAssignmentId(instance, stepId),
|
|
411
|
+
payload: { name: step.external.name, input: step.external.input },
|
|
412
|
+
});
|
|
413
|
+
return;
|
|
414
|
+
}
|
|
265
415
|
const assignment = await this.createWorkflowAssignment(instance, step, definition);
|
|
266
416
|
instance.currentAssignmentId = assignment.id;
|
|
267
417
|
instance.currentStepId = stepId;
|
|
@@ -373,6 +523,49 @@ class WorkflowManager {
|
|
|
373
523
|
}
|
|
374
524
|
return expiredCount;
|
|
375
525
|
}
|
|
526
|
+
/**
|
|
527
|
+
* Complete (or fail) an external step from outside this process — the
|
|
528
|
+
* counterpart to the `step.ready` transition. Validates the step is
|
|
529
|
+
* actually the run's current step (or a pending parallel branch) and is
|
|
530
|
+
* really an external step, clears its timeout, then publishes the same
|
|
531
|
+
* COMPLETED/FAILED event onto the stream that in-process completions use,
|
|
532
|
+
* so the orchestrator advances the run through the ordinary transition
|
|
533
|
+
* pipeline (idempotency, retries, and DLQ all still apply).
|
|
534
|
+
*/
|
|
535
|
+
async completeWorkflowStep(instanceId, stepId, outcome) {
|
|
536
|
+
const instance = await this.getWorkflowInstance(instanceId);
|
|
537
|
+
if (!instance) {
|
|
538
|
+
throw new Error(`Workflow instance not found: ${instanceId}`);
|
|
539
|
+
}
|
|
540
|
+
if (instance.status !== 'active') {
|
|
541
|
+
throw new Error(`Workflow instance ${instanceId} is not active`);
|
|
542
|
+
}
|
|
543
|
+
const branch = instance.parallelBranches?.find((b) => b.stepId === stepId);
|
|
544
|
+
const isCurrentStep = instance.currentStepId === stepId;
|
|
545
|
+
const isPendingBranch = branch?.status === 'pending';
|
|
546
|
+
if (!isCurrentStep && !isPendingBranch) {
|
|
547
|
+
throw new Error(`Step "${stepId}" is not currently active for instance ${instanceId}`);
|
|
548
|
+
}
|
|
549
|
+
const definition = instance.definitionSnapshot ?? (await this.getWorkflowDefinition(instance.workflowDefinitionId));
|
|
550
|
+
const step = definition?.steps.find((s) => s.id === stepId);
|
|
551
|
+
if ((step?.taskType ?? 'assignment') !== 'external') {
|
|
552
|
+
throw new Error(`Step "${stepId}" is not an external step`);
|
|
553
|
+
}
|
|
554
|
+
await this.redisClient.zRem(this.keys.workflowStepExpiryIndex(), `${instanceId}|${stepId}`);
|
|
555
|
+
await this.redisClient.del(this.keys.workflowStepExpiry(instanceId, stepId));
|
|
556
|
+
const assignmentId = branch?.assignmentId ?? this.deterministicAssignmentId(instance, stepId);
|
|
557
|
+
await this.publishWorkflowEvent({
|
|
558
|
+
eventId: (0, crypto_1.randomUUID)(),
|
|
559
|
+
type: outcome.success ? 'COMPLETED' : 'FAILED',
|
|
560
|
+
userId: instance.initiatorUserId,
|
|
561
|
+
assignmentId,
|
|
562
|
+
workflowInstanceId: instanceId,
|
|
563
|
+
stepId,
|
|
564
|
+
timestamp: Date.now(),
|
|
565
|
+
payload: outcome.success ? outcome.data : { error: outcome.error },
|
|
566
|
+
});
|
|
567
|
+
return true;
|
|
568
|
+
}
|
|
376
569
|
async createWorkflowAssignment(instance, step, definition) {
|
|
377
570
|
if (!step.assignmentTemplate) {
|
|
378
571
|
throw new Error(`Assignment step "${step.id}" is missing assignmentTemplate`);
|
|
@@ -436,6 +629,70 @@ class WorkflowManager {
|
|
|
436
629
|
});
|
|
437
630
|
return messageId;
|
|
438
631
|
}
|
|
632
|
+
/**
|
|
633
|
+
* Non-blocking drain of up to `maxEvents` due workflow events, using the
|
|
634
|
+
* main Redis client (no duplicated subscriber connection, no BLOCK wait).
|
|
635
|
+
* Shares all processing internals with the orchestrator loop — idempotency,
|
|
636
|
+
* circuit breaker, retry scheduling, and DLQ all apply — but is meant to be
|
|
637
|
+
* called periodically by a host sweeping many workspaces/tenants rather
|
|
638
|
+
* than running one dedicated blocking loop per matcher instance. Returns
|
|
639
|
+
* the number of events successfully processed (retried/DLQ'd events still
|
|
640
|
+
* count as handled — only a hard read error returns early).
|
|
641
|
+
*/
|
|
642
|
+
async processWorkflowEvents(maxEvents) {
|
|
643
|
+
if (!this.options.enableWorkflows)
|
|
644
|
+
return 0;
|
|
645
|
+
await this.initStreamConsumerGroup();
|
|
646
|
+
const streamKey = this.keys.eventStream();
|
|
647
|
+
const count = maxEvents ?? this.options.eventBatchSize ?? 10;
|
|
648
|
+
let processed = 0;
|
|
649
|
+
try {
|
|
650
|
+
const response = (await this.redisClient.xReadGroup(this.options.streamConsumerGroup, this.options.streamConsumerName, [{ key: streamKey, id: '>' }], { COUNT: count }));
|
|
651
|
+
if (!response)
|
|
652
|
+
return 0;
|
|
653
|
+
for (const stream of response) {
|
|
654
|
+
for (const message of stream.messages) {
|
|
655
|
+
const event = this.parseStreamMessage(message);
|
|
656
|
+
if (await this.reliability.isEventProcessed(event.eventId)) {
|
|
657
|
+
await this.redisClient.xAck(streamKey, this.options.streamConsumerGroup, message.id);
|
|
658
|
+
continue;
|
|
659
|
+
}
|
|
660
|
+
await this.applyEventThrottle();
|
|
661
|
+
try {
|
|
662
|
+
await this.processWorkflowEvent(event);
|
|
663
|
+
await this.reliability.markEventProcessed(event.eventId);
|
|
664
|
+
await this.redisClient.xAck(streamKey, this.options.streamConsumerGroup, message.id);
|
|
665
|
+
this.reliability.recordCircuitBreakerSuccess();
|
|
666
|
+
processed++;
|
|
667
|
+
}
|
|
668
|
+
catch (err) {
|
|
669
|
+
console.error(`Error processing event ${event.eventId}:`, err);
|
|
670
|
+
await this.reliability.recordCircuitBreakerFailure();
|
|
671
|
+
const retryKey = this.keys.eventRetryCount(event.eventId);
|
|
672
|
+
const retryCount = Number(await this.redisClient.get(retryKey)) || 0;
|
|
673
|
+
if (retryCount >= this.reliability.options.workflowMaxRetries) {
|
|
674
|
+
await this.reliability.moveToDeadLetter(event, 'Processing failed after max retries', err instanceof Error ? err : new Error(String(err)));
|
|
675
|
+
await this.redisClient.xAck(streamKey, this.options.streamConsumerGroup, message.id);
|
|
676
|
+
}
|
|
677
|
+
else {
|
|
678
|
+
const nextRetryCount = Number(await this.redisClient.incr(retryKey));
|
|
679
|
+
await this.redisClient.expire(retryKey, 86400);
|
|
680
|
+
await this.scheduleEventRetry(event, nextRetryCount);
|
|
681
|
+
await this.redisClient.xAck(streamKey, this.options.streamConsumerGroup, message.id);
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
catch (err) {
|
|
688
|
+
if (this.isNoGroupError(err)) {
|
|
689
|
+
await this.initStreamConsumerGroup();
|
|
690
|
+
return processed;
|
|
691
|
+
}
|
|
692
|
+
console.error('processWorkflowEvents read error:', err);
|
|
693
|
+
}
|
|
694
|
+
return processed;
|
|
695
|
+
}
|
|
439
696
|
async startOrchestrator() {
|
|
440
697
|
if (!this.options.enableWorkflows) {
|
|
441
698
|
throw new Error('Workflows are not enabled. Set enableWorkflows: true in options.');
|
|
@@ -705,6 +962,11 @@ class WorkflowManager {
|
|
|
705
962
|
if (event.payload) {
|
|
706
963
|
instance.context = { ...instance.context, [`step_${stepId}`]: event.payload };
|
|
707
964
|
}
|
|
965
|
+
this.emitTransition('step.completed', instance, {
|
|
966
|
+
stepId,
|
|
967
|
+
assignmentId: event.assignmentId,
|
|
968
|
+
payload: event.payload,
|
|
969
|
+
});
|
|
708
970
|
const expectedVersion = instance.version;
|
|
709
971
|
if (instance.parallelBranches) {
|
|
710
972
|
const branch = instance.parallelBranches.find((b) => b.stepId === stepId);
|
|
@@ -741,6 +1003,7 @@ class WorkflowManager {
|
|
|
741
1003
|
instance.currentStepId = null;
|
|
742
1004
|
instance.currentAssignmentId = undefined;
|
|
743
1005
|
await this.saveInstance(instance, expectedVersion);
|
|
1006
|
+
this.emitTransition('run.completed', instance);
|
|
744
1007
|
}
|
|
745
1008
|
}
|
|
746
1009
|
async handleStepFailure(instance, definition, event) {
|
|
@@ -757,11 +1020,17 @@ class WorkflowManager {
|
|
|
757
1020
|
const branch = instance.parallelBranches.find((b) => b.stepId === stepId);
|
|
758
1021
|
if (branch) {
|
|
759
1022
|
branch.status = 'failed';
|
|
1023
|
+
this.emitTransition('step.failed', instance, {
|
|
1024
|
+
stepId,
|
|
1025
|
+
assignmentId: event.assignmentId,
|
|
1026
|
+
payload: { ...event.payload, willRetry: false },
|
|
1027
|
+
});
|
|
760
1028
|
const policy = step.failurePolicy ?? 'abort';
|
|
761
1029
|
if (policy === 'abort') {
|
|
762
1030
|
// Fail entire workflow
|
|
763
1031
|
instance.status = 'failed';
|
|
764
1032
|
await this.saveInstance(instance, expectedVersion);
|
|
1033
|
+
this.emitTransition('run.failed', instance, { stepId, payload: event.payload });
|
|
765
1034
|
return;
|
|
766
1035
|
}
|
|
767
1036
|
else if (policy === 'continue') {
|
|
@@ -782,7 +1051,13 @@ class WorkflowManager {
|
|
|
782
1051
|
}
|
|
783
1052
|
}
|
|
784
1053
|
// Retry logic
|
|
785
|
-
|
|
1054
|
+
const willRetry = instance.retryCount < maxRetries;
|
|
1055
|
+
this.emitTransition('step.failed', instance, {
|
|
1056
|
+
stepId,
|
|
1057
|
+
assignmentId: event.assignmentId,
|
|
1058
|
+
payload: { ...event.payload, willRetry },
|
|
1059
|
+
});
|
|
1060
|
+
if (willRetry) {
|
|
786
1061
|
instance.retryCount += 1;
|
|
787
1062
|
await this.executeWorkflowStep(instance, stepId, definition);
|
|
788
1063
|
}
|
|
@@ -790,11 +1065,67 @@ class WorkflowManager {
|
|
|
790
1065
|
// Workflow failed
|
|
791
1066
|
instance.status = 'failed';
|
|
792
1067
|
await this.saveInstance(instance, expectedVersion);
|
|
1068
|
+
this.emitTransition('run.failed', instance, { stepId, payload: event.payload });
|
|
793
1069
|
}
|
|
794
1070
|
}
|
|
795
1071
|
async handleStepExpiry(instance, definition, event) {
|
|
1072
|
+
this.emitTransition('step.expired', instance, { stepId: event.stepId, assignmentId: event.assignmentId });
|
|
1073
|
+
if (await this.tryEscalateExpiredStep(instance, definition, event))
|
|
1074
|
+
return;
|
|
796
1075
|
await this.handleStepFailure(instance, definition, event);
|
|
797
1076
|
}
|
|
1077
|
+
/**
|
|
1078
|
+
* Advance a timed-out step to its `onTimeoutStepId` instead of failing the
|
|
1079
|
+
* run — the escalation ladder (page primary, then secondary, then the
|
|
1080
|
+
* manager). Returns false when the step declares no escalation target, or
|
|
1081
|
+
* when the run has climbed past `maxEscalationDepth`, in which case the
|
|
1082
|
+
* caller falls through to the ordinary failure path.
|
|
1083
|
+
*/
|
|
1084
|
+
async tryEscalateExpiredStep(instance, definition, event) {
|
|
1085
|
+
const stepId = event.stepId;
|
|
1086
|
+
if (!stepId)
|
|
1087
|
+
return false;
|
|
1088
|
+
const step = definition.steps.find((s) => s.id === stepId);
|
|
1089
|
+
const target = step?.onTimeoutStepId;
|
|
1090
|
+
if (!step || !target)
|
|
1091
|
+
return false;
|
|
1092
|
+
// A parallel branch has no single "next step" to escalate to; validation
|
|
1093
|
+
// rejects the combination, but a hand-written definition could slip past
|
|
1094
|
+
// an older registration, so bail out rather than corrupt the branch state.
|
|
1095
|
+
if (instance.parallelBranches?.some((b) => b.stepId === stepId))
|
|
1096
|
+
return false;
|
|
1097
|
+
const depth = Number(instance.context._escalationDepth ?? 0) + 1;
|
|
1098
|
+
const maxDepth = definition.maxEscalationDepth ?? 10;
|
|
1099
|
+
if (depth > maxDepth)
|
|
1100
|
+
return false;
|
|
1101
|
+
// Pull the superseded assignment so a late responder on the previous
|
|
1102
|
+
// tier cannot act on work the ladder has already moved on from.
|
|
1103
|
+
const assignmentId = event.assignmentId || instance.currentAssignmentId;
|
|
1104
|
+
if (assignmentId && this.host.removeAssignment) {
|
|
1105
|
+
await this.host.removeAssignment(assignmentId).catch(() => {
|
|
1106
|
+
/* already gone (accepted, cancelled, swept) — nothing to supersede */
|
|
1107
|
+
});
|
|
1108
|
+
await this.redisClient.del(this.keys.workflowAssignmentLink(assignmentId));
|
|
1109
|
+
}
|
|
1110
|
+
instance.history.push({
|
|
1111
|
+
stepId,
|
|
1112
|
+
assignmentId: assignmentId ?? '',
|
|
1113
|
+
userId: '',
|
|
1114
|
+
completedAt: Date.now(),
|
|
1115
|
+
result: { escalated: true, to: target },
|
|
1116
|
+
});
|
|
1117
|
+
instance.context._escalatedFrom = stepId;
|
|
1118
|
+
instance.context._escalationDepth = depth;
|
|
1119
|
+
this.emitTransition('step.escalated', instance, {
|
|
1120
|
+
stepId,
|
|
1121
|
+
assignmentId,
|
|
1122
|
+
payload: { from: stepId, to: target, depth },
|
|
1123
|
+
});
|
|
1124
|
+
// Deliberately does not touch instance.retryCount: an escalation is a
|
|
1125
|
+
// different person getting the work, not another attempt at the same one.
|
|
1126
|
+
await this.executeWorkflowStep(instance, target, definition);
|
|
1127
|
+
return true;
|
|
1128
|
+
}
|
|
798
1129
|
evaluateCondition(condition, result, context) {
|
|
799
1130
|
try {
|
|
800
1131
|
const match = condition.match(/^(result|context)\.(\w+)\s*(===|!==|==|!=|>=|<=|>|<)\s*(.+)$/);
|
|
@@ -1028,7 +1359,13 @@ class WorkflowManager {
|
|
|
1028
1359
|
cursor = nextCursor;
|
|
1029
1360
|
for (const entry of entries) {
|
|
1030
1361
|
const instance = await this.getWorkflowInstance(entry.field);
|
|
1031
|
-
if (instance
|
|
1362
|
+
if (!instance)
|
|
1363
|
+
continue;
|
|
1364
|
+
await this.redisClient.zAdd(this.keys.workflowInstancesByTime(), {
|
|
1365
|
+
score: instance.createdAt,
|
|
1366
|
+
value: instance.id,
|
|
1367
|
+
});
|
|
1368
|
+
if (instance.status === 'active') {
|
|
1032
1369
|
await this.redisClient.zAdd(this.keys.workflowInstancesActive(), {
|
|
1033
1370
|
score: instance.updatedAt,
|
|
1034
1371
|
value: instance.id,
|
|
@@ -1069,6 +1406,7 @@ class WorkflowManager {
|
|
|
1069
1406
|
multi.hDel(this.keys.workflowInstances(), instanceId);
|
|
1070
1407
|
multi.sRem(this.keys.workflowInstancesByUser(instance.initiatorUserId), instanceId);
|
|
1071
1408
|
multi.zRem(this.keys.workflowInstancesActive(), instanceId);
|
|
1409
|
+
multi.zRem(this.keys.workflowInstancesByTime(), instanceId);
|
|
1072
1410
|
await multi.exec();
|
|
1073
1411
|
pruned++;
|
|
1074
1412
|
}
|