assignment-user-matcher 1.2.5 → 1.6.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/LICENCE +21 -53
- package/README.md +153 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -1
- package/dist/managers/DecisionTraceManager.d.ts +34 -0
- package/dist/managers/DecisionTraceManager.d.ts.map +1 -0
- package/dist/managers/DecisionTraceManager.js +74 -0
- package/dist/managers/WorkflowManager.d.ts +57 -1
- package/dist/managers/WorkflowManager.d.ts.map +1 -1
- package/dist/managers/WorkflowManager.js +296 -2
- package/dist/matcher.class.d.ts +186 -3
- package/dist/matcher.class.d.ts.map +1 -1
- package/dist/matcher.class.js +891 -40
- package/dist/scoring/match-score.d.ts +17 -1
- package/dist/scoring/match-score.d.ts.map +1 -1
- package/dist/scoring/match-score.js +81 -1
- package/dist/tracing/decision-trace.d.ts +48 -0
- package/dist/tracing/decision-trace.d.ts.map +1 -0
- package/dist/tracing/decision-trace.js +152 -0
- package/dist/types/matcher.d.ts +327 -1
- package/dist/types/matcher.d.ts.map +1 -1
- package/dist/utils/keys.d.ts +5 -0
- package/dist/utils/keys.d.ts.map +1 -1
- package/dist/utils/keys.js +17 -0
- package/dist/workflow-builder.d.ts +6 -0
- package/dist/workflow-builder.d.ts.map +1 -1
- package/dist/workflow-builder.js +13 -0
- package/dist/workflow-validation.d.ts.map +1 -1
- package/dist/workflow-validation.js +20 -0
- package/package.json +2 -2
- 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();
|
|
@@ -72,6 +87,16 @@ class WorkflowManager {
|
|
|
72
87
|
const definitions = await this.redisClient.hGetAll(this.keys.workflowDefinitions());
|
|
73
88
|
return Object.entries(definitions).map(([id, name]) => ({ id, name }));
|
|
74
89
|
}
|
|
90
|
+
/**
|
|
91
|
+
* Delete a workflow definition and its listing entry. Running instances keep
|
|
92
|
+
* their own `definitionSnapshot`, so in-flight workflows are unaffected.
|
|
93
|
+
* Returns `false` if no definition with that id existed.
|
|
94
|
+
*/
|
|
95
|
+
async deleteWorkflowDefinition(id) {
|
|
96
|
+
const removed = await this.redisClient.del(this.keys.workflowDefinition(id));
|
|
97
|
+
await this.redisClient.hDel(this.keys.workflowDefinitions(), id);
|
|
98
|
+
return removed > 0;
|
|
99
|
+
}
|
|
75
100
|
async startWorkflow(workflowDefinitionId, userId, initialContext) {
|
|
76
101
|
if (!workflowDefinitionId.trim()) {
|
|
77
102
|
throw new Error('Workflow definition ID is required');
|
|
@@ -88,6 +113,18 @@ class WorkflowManager {
|
|
|
88
113
|
if (!definition) {
|
|
89
114
|
throw new Error(`Workflow definition not found: ${workflowDefinitionId}`);
|
|
90
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
|
+
}
|
|
91
128
|
const now = Date.now();
|
|
92
129
|
const instanceId = (0, crypto_1.randomUUID)();
|
|
93
130
|
this.telemetry.setSpanAttributes(span, {
|
|
@@ -110,11 +147,17 @@ class WorkflowManager {
|
|
|
110
147
|
? JSON.parse(JSON.stringify(definition))
|
|
111
148
|
: undefined,
|
|
112
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());
|
|
113
155
|
const multi = this.redisClient.multi();
|
|
114
156
|
multi.hSet(this.keys.workflowInstance(instanceId), 'data', JSON.stringify(instance));
|
|
115
157
|
multi.sAdd(this.keys.workflowInstancesByUser(userId), instanceId);
|
|
116
158
|
multi.hSet(this.keys.workflowInstances(), instanceId, workflowDefinitionId);
|
|
117
159
|
multi.zAdd(this.keys.workflowInstancesActive(), { score: now, value: instanceId });
|
|
160
|
+
multi.zAdd(this.keys.workflowInstancesByTime(), { score: sequence, value: instanceId });
|
|
118
161
|
await multi.exec();
|
|
119
162
|
await this.reliability.emitAuditEvent('WORKFLOW_STARTED', instanceId, {
|
|
120
163
|
definitionId: workflowDefinitionId,
|
|
@@ -132,6 +175,7 @@ class WorkflowManager {
|
|
|
132
175
|
timestamp: now,
|
|
133
176
|
});
|
|
134
177
|
}
|
|
178
|
+
this.emitTransition('run.started', instance, { stepId: definition.initialStepId });
|
|
135
179
|
await this.executeWorkflowStep(instance, definition.initialStepId, definition);
|
|
136
180
|
endSpan();
|
|
137
181
|
return instance;
|
|
@@ -156,6 +200,50 @@ class WorkflowManager {
|
|
|
156
200
|
resolvedDefinition: definition ?? undefined,
|
|
157
201
|
};
|
|
158
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
|
+
}
|
|
159
247
|
async getActiveWorkflowsForUser(userId) {
|
|
160
248
|
const instanceIds = await this.redisClient.sMembers(this.keys.workflowInstancesByUser(userId));
|
|
161
249
|
if (instanceIds.length === 0)
|
|
@@ -176,6 +264,12 @@ class WorkflowManager {
|
|
|
176
264
|
}
|
|
177
265
|
return instances;
|
|
178
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
|
+
*/
|
|
179
273
|
async cancelWorkflow(instanceId) {
|
|
180
274
|
const instance = await this.getWorkflowInstance(instanceId);
|
|
181
275
|
if (!instance) {
|
|
@@ -183,7 +277,31 @@ class WorkflowManager {
|
|
|
183
277
|
}
|
|
184
278
|
const expectedVersion = instance.version;
|
|
185
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
|
+
}
|
|
186
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);
|
|
187
305
|
return true;
|
|
188
306
|
}
|
|
189
307
|
async executeWorkflowStep(instance, stepId, definition) {
|
|
@@ -195,6 +313,7 @@ class WorkflowManager {
|
|
|
195
313
|
if (step.parallelStepIds && step.parallelStepIds.length > 0) {
|
|
196
314
|
const branches = [];
|
|
197
315
|
const machineParallelSteps = [];
|
|
316
|
+
const externalParallelSteps = [];
|
|
198
317
|
for (const parallelStepId of step.parallelStepIds) {
|
|
199
318
|
const parallelStep = definition.steps.find((s) => s.id === parallelStepId);
|
|
200
319
|
if (!parallelStep)
|
|
@@ -212,6 +331,18 @@ class WorkflowManager {
|
|
|
212
331
|
status: 'pending',
|
|
213
332
|
});
|
|
214
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
|
+
}
|
|
215
346
|
else {
|
|
216
347
|
const assignment = await this.createWorkflowAssignment(instance, parallelStep, definition);
|
|
217
348
|
branches.push({
|
|
@@ -235,6 +366,16 @@ class WorkflowManager {
|
|
|
235
366
|
continue;
|
|
236
367
|
await this.executeMachineStep(instance, parallelStep, definition, machineStep.assignmentId);
|
|
237
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
|
+
}
|
|
238
379
|
return;
|
|
239
380
|
}
|
|
240
381
|
const taskType = step.taskType ?? 'assignment';
|
|
@@ -252,6 +393,25 @@ class WorkflowManager {
|
|
|
252
393
|
await this.executeMachineStep(instance, step, definition);
|
|
253
394
|
return;
|
|
254
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
|
+
}
|
|
255
415
|
const assignment = await this.createWorkflowAssignment(instance, step, definition);
|
|
256
416
|
instance.currentAssignmentId = assignment.id;
|
|
257
417
|
instance.currentStepId = stepId;
|
|
@@ -363,6 +523,49 @@ class WorkflowManager {
|
|
|
363
523
|
}
|
|
364
524
|
return expiredCount;
|
|
365
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
|
+
}
|
|
366
569
|
async createWorkflowAssignment(instance, step, definition) {
|
|
367
570
|
if (!step.assignmentTemplate) {
|
|
368
571
|
throw new Error(`Assignment step "${step.id}" is missing assignmentTemplate`);
|
|
@@ -426,6 +629,70 @@ class WorkflowManager {
|
|
|
426
629
|
});
|
|
427
630
|
return messageId;
|
|
428
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
|
+
}
|
|
429
696
|
async startOrchestrator() {
|
|
430
697
|
if (!this.options.enableWorkflows) {
|
|
431
698
|
throw new Error('Workflows are not enabled. Set enableWorkflows: true in options.');
|
|
@@ -695,6 +962,11 @@ class WorkflowManager {
|
|
|
695
962
|
if (event.payload) {
|
|
696
963
|
instance.context = { ...instance.context, [`step_${stepId}`]: event.payload };
|
|
697
964
|
}
|
|
965
|
+
this.emitTransition('step.completed', instance, {
|
|
966
|
+
stepId,
|
|
967
|
+
assignmentId: event.assignmentId,
|
|
968
|
+
payload: event.payload,
|
|
969
|
+
});
|
|
698
970
|
const expectedVersion = instance.version;
|
|
699
971
|
if (instance.parallelBranches) {
|
|
700
972
|
const branch = instance.parallelBranches.find((b) => b.stepId === stepId);
|
|
@@ -731,6 +1003,7 @@ class WorkflowManager {
|
|
|
731
1003
|
instance.currentStepId = null;
|
|
732
1004
|
instance.currentAssignmentId = undefined;
|
|
733
1005
|
await this.saveInstance(instance, expectedVersion);
|
|
1006
|
+
this.emitTransition('run.completed', instance);
|
|
734
1007
|
}
|
|
735
1008
|
}
|
|
736
1009
|
async handleStepFailure(instance, definition, event) {
|
|
@@ -747,11 +1020,17 @@ class WorkflowManager {
|
|
|
747
1020
|
const branch = instance.parallelBranches.find((b) => b.stepId === stepId);
|
|
748
1021
|
if (branch) {
|
|
749
1022
|
branch.status = 'failed';
|
|
1023
|
+
this.emitTransition('step.failed', instance, {
|
|
1024
|
+
stepId,
|
|
1025
|
+
assignmentId: event.assignmentId,
|
|
1026
|
+
payload: { ...event.payload, willRetry: false },
|
|
1027
|
+
});
|
|
750
1028
|
const policy = step.failurePolicy ?? 'abort';
|
|
751
1029
|
if (policy === 'abort') {
|
|
752
1030
|
// Fail entire workflow
|
|
753
1031
|
instance.status = 'failed';
|
|
754
1032
|
await this.saveInstance(instance, expectedVersion);
|
|
1033
|
+
this.emitTransition('run.failed', instance, { stepId, payload: event.payload });
|
|
755
1034
|
return;
|
|
756
1035
|
}
|
|
757
1036
|
else if (policy === 'continue') {
|
|
@@ -772,7 +1051,13 @@ class WorkflowManager {
|
|
|
772
1051
|
}
|
|
773
1052
|
}
|
|
774
1053
|
// Retry logic
|
|
775
|
-
|
|
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) {
|
|
776
1061
|
instance.retryCount += 1;
|
|
777
1062
|
await this.executeWorkflowStep(instance, stepId, definition);
|
|
778
1063
|
}
|
|
@@ -780,9 +1065,11 @@ class WorkflowManager {
|
|
|
780
1065
|
// Workflow failed
|
|
781
1066
|
instance.status = 'failed';
|
|
782
1067
|
await this.saveInstance(instance, expectedVersion);
|
|
1068
|
+
this.emitTransition('run.failed', instance, { stepId, payload: event.payload });
|
|
783
1069
|
}
|
|
784
1070
|
}
|
|
785
1071
|
async handleStepExpiry(instance, definition, event) {
|
|
1072
|
+
this.emitTransition('step.expired', instance, { stepId: event.stepId, assignmentId: event.assignmentId });
|
|
786
1073
|
await this.handleStepFailure(instance, definition, event);
|
|
787
1074
|
}
|
|
788
1075
|
evaluateCondition(condition, result, context) {
|
|
@@ -1018,7 +1305,13 @@ class WorkflowManager {
|
|
|
1018
1305
|
cursor = nextCursor;
|
|
1019
1306
|
for (const entry of entries) {
|
|
1020
1307
|
const instance = await this.getWorkflowInstance(entry.field);
|
|
1021
|
-
if (instance
|
|
1308
|
+
if (!instance)
|
|
1309
|
+
continue;
|
|
1310
|
+
await this.redisClient.zAdd(this.keys.workflowInstancesByTime(), {
|
|
1311
|
+
score: instance.createdAt,
|
|
1312
|
+
value: instance.id,
|
|
1313
|
+
});
|
|
1314
|
+
if (instance.status === 'active') {
|
|
1022
1315
|
await this.redisClient.zAdd(this.keys.workflowInstancesActive(), {
|
|
1023
1316
|
score: instance.updatedAt,
|
|
1024
1317
|
value: instance.id,
|
|
@@ -1059,6 +1352,7 @@ class WorkflowManager {
|
|
|
1059
1352
|
multi.hDel(this.keys.workflowInstances(), instanceId);
|
|
1060
1353
|
multi.sRem(this.keys.workflowInstancesByUser(instance.initiatorUserId), instanceId);
|
|
1061
1354
|
multi.zRem(this.keys.workflowInstancesActive(), instanceId);
|
|
1355
|
+
multi.zRem(this.keys.workflowInstancesByTime(), instanceId);
|
|
1062
1356
|
await multi.exec();
|
|
1063
1357
|
pruned++;
|
|
1064
1358
|
}
|