assignment-user-matcher 1.3.0 → 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/README.md +23 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/managers/WorkflowManager.d.ts +51 -1
- package/dist/managers/WorkflowManager.d.ts.map +1 -1
- package/dist/managers/WorkflowManager.js +286 -2
- package/dist/matcher.class.d.ts +62 -3
- package/dist/matcher.class.d.ts.map +1 -1
- package/dist/matcher.class.js +193 -8
- package/dist/types/matcher.d.ts +122 -1
- package/dist/types/matcher.d.ts.map +1 -1
- package/dist/utils/keys.d.ts +2 -0
- package/dist/utils/keys.d.ts.map +1 -1
- package/dist/utils/keys.js +10 -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 +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
package/README.md
CHANGED
|
@@ -312,6 +312,10 @@ Operator availability controls. A paused user stops receiving new assignments in
|
|
|
312
312
|
|
|
313
313
|
When decision traces are enabled, paused users appear struck out in traces with a `paused` reason, and `explainMatch()` reports them as ineligible.
|
|
314
314
|
|
|
315
|
+
### `releaseUserAssignments(userId: string): Promise<string[]>`
|
|
316
|
+
|
|
317
|
+
The redistribution counterpart to `pauseUser`: requeue every pending (matched but not yet accepted) assignment the user holds so other users can pick them up — for when a worker is gone rather than briefly away. Accepted assignments (work in progress) are never touched. Requeued assignments keep their original wait clock (`getQueueStats().oldestWaitingMs` does not reset), workflow subscribers receive an `EXPIRED` event per released assignment, and a still-paused user cannot win their released work back until resumed. Returns the released assignment ids (`[]` when the user holds nothing or is unknown). The idle auto-removal path (`processIdleUsers`) uses the same requeue mechanics internally.
|
|
318
|
+
|
|
315
319
|
### `assignToUser(assignmentId: string, userId: string, options?: { force?: boolean }): Promise<{ previousOwnerId: string | null }>`
|
|
316
320
|
|
|
317
321
|
Operator override: hand an assignment directly to a user, bypassing tag/weight selection. Works on queued assignments and on pending assignments held by another user (the previous owner's backlog slot is released and the expiry clock restarts). Idempotent when the user already owns the assignment.
|
|
@@ -608,6 +612,25 @@ assignments the current owner is flagged `chosen`). Because it evaluates _now_
|
|
|
608
612
|
rather than at decision time, use it for support tooling and dry-runs
|
|
609
613
|
("who would get this?"), and decision traces for the compliance-grade record.
|
|
610
614
|
|
|
615
|
+
### Hypothetical preview (`previewMatch`)
|
|
616
|
+
|
|
617
|
+
`previewMatch()` answers "who would receive this assignment if I created it?"
|
|
618
|
+
without persisting or claiming anything. It uses the same scoring and hard
|
|
619
|
+
rules as real matching, so the ranking mirrors what `explainMatch()` would
|
|
620
|
+
report after the assignment is added.
|
|
621
|
+
|
|
622
|
+
```typescript
|
|
623
|
+
const preview = await matcher.previewMatch(
|
|
624
|
+
{ tags: ['english', 'billing'], priority: 100, skillThresholds: { english: 50 } },
|
|
625
|
+
// optional: restrict to specific users
|
|
626
|
+
{ userIds: ['alice', 'bob'] },
|
|
627
|
+
);
|
|
628
|
+
// { tags, priority, evaluatedAt, candidates: MatchCandidateTrace[] }
|
|
629
|
+
```
|
|
630
|
+
|
|
631
|
+
Use it for autosuggestion UIs: render the ranked best-fit workers with score
|
|
632
|
+
breakdowns and blocked reasons before the operator commits the task.
|
|
633
|
+
|
|
611
634
|
## Adaptive Matching with Reinforcement Learning
|
|
612
635
|
|
|
613
636
|
The matcher includes an opt-in, Redis-backed contextual bandit that learns from
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import AssignmentMatcher from './matcher.class';
|
|
2
|
-
export type { Assignment, MatcherOptions, options, Stats, QueueStats, UserLoadInfo, User, GeoMatchResult, GeoMatchingFunction, ReliabilityMetrics, AssignmentStatus, FairnessMode, FairnessConfig, MatchTraceReason, MatchCandidateTrace, MatchDecisionTrace, MatchDecisionMode, MatchExplanation, DecisionTraceQuery, } from './matcher.class';
|
|
3
|
-
export type { WorkflowDefinition, WorkflowDefinitionInput, WorkflowDefinitionSummary, WorkflowInstance, WorkflowInstanceStatus, WorkflowStep, WorkflowRouting, WorkflowTargetUser, WorkflowMachineTask, WorkflowTaskType, WorkflowEvent, WorkflowEventType, AssignmentResult, ParallelBranchState, DeadLetterEntry, AuditEntry, CircuitBreakerState, WorkflowInstanceWithSnapshot, LearningOutcome, LearningRewards, LearningFeatures, LearningAssignmentContext, LearningFeatureExtractor, LearningDecisionRecord, LearningEpisodeRecord, LearningSignals, LearningSample, LearningStats, LearningTagStat, AutoRoutingWeightsOptions, PendingAssignmentInfo, WorkflowEngineMetrics, MachineTaskHandler, WorkflowHost, PaginationOptions, PaginationResult, AssignmentCounts, } from './matcher.class';
|
|
2
|
+
export type { Assignment, MatcherOptions, options, Stats, QueueStats, UserLoadInfo, User, GeoMatchResult, GeoMatchingFunction, ReliabilityMetrics, AssignmentStatus, FairnessMode, FairnessConfig, MatchTraceReason, MatchCandidateTrace, MatchDecisionTrace, MatchDecisionMode, MatchExplanation, MatchPreview, MatchPreviewInput, DecisionTraceQuery, AssignmentLifecycleEvent, } from './matcher.class';
|
|
3
|
+
export type { WorkflowDefinition, WorkflowDefinitionInput, WorkflowDefinitionSummary, WorkflowInstance, WorkflowInstanceStatus, WorkflowStep, WorkflowRouting, WorkflowTargetUser, WorkflowMachineTask, WorkflowExternalTask, WorkflowTaskType, WorkflowEvent, WorkflowEventType, AssignmentResult, ParallelBranchState, DeadLetterEntry, AuditEntry, CircuitBreakerState, WorkflowInstanceWithSnapshot, WorkflowInstanceQuery, WorkflowInstancePage, WorkflowTransition, LearningOutcome, LearningRewards, LearningFeatures, LearningAssignmentContext, LearningFeatureExtractor, LearningDecisionRecord, LearningEpisodeRecord, LearningSignals, LearningSample, LearningStats, LearningTagStat, AutoRoutingWeightsOptions, PendingAssignmentInfo, WorkflowEngineMetrics, MachineTaskHandler, WorkflowHost, PaginationOptions, PaginationResult, AssignmentCounts, } from './matcher.class';
|
|
4
4
|
export { explainMatchScore, type MatchScoreExplanation } from './scoring/match-score';
|
|
5
5
|
export { extractMatchFeatures, cosineSimilarity } from './learning/features';
|
|
6
6
|
export { synthesizeRoutingWeights, DEFAULT_AUTO_WEIGHTS_OPTIONS } from './learning/auto-weights';
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,iBAAiB,MAAM,iBAAiB,CAAC;AAEhD,YAAY,EACR,UAAU,EACV,cAAc,EACd,OAAO,EACP,KAAK,EACL,UAAU,EACV,YAAY,EACZ,IAAI,EACJ,cAAc,EACd,mBAAmB,EACnB,kBAAkB,EAClB,gBAAgB,EAChB,YAAY,EACZ,cAAc,EACd,gBAAgB,EAChB,mBAAmB,EACnB,kBAAkB,EAClB,iBAAiB,EACjB,gBAAgB,EAChB,kBAAkB,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,iBAAiB,MAAM,iBAAiB,CAAC;AAEhD,YAAY,EACR,UAAU,EACV,cAAc,EACd,OAAO,EACP,KAAK,EACL,UAAU,EACV,YAAY,EACZ,IAAI,EACJ,cAAc,EACd,mBAAmB,EACnB,kBAAkB,EAClB,gBAAgB,EAChB,YAAY,EACZ,cAAc,EACd,gBAAgB,EAChB,mBAAmB,EACnB,kBAAkB,EAClB,iBAAiB,EACjB,gBAAgB,EAChB,YAAY,EACZ,iBAAiB,EACjB,kBAAkB,EAClB,wBAAwB,G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
|
|
|
1
|
-
import { RedisClientType, WorkflowDefinition, WorkflowDefinitionInput, WorkflowDefinitionSummary, WorkflowInstance, WorkflowStep, WorkflowEvent, Assignment, WorkflowInstanceWithSnapshot, WorkflowEngineMetrics } from '../types/matcher';
|
|
1
|
+
import { RedisClientType, WorkflowDefinition, WorkflowDefinitionInput, WorkflowDefinitionSummary, WorkflowInstance, WorkflowStep, WorkflowEvent, Assignment, WorkflowInstanceWithSnapshot, WorkflowEngineMetrics, WorkflowInstanceQuery, WorkflowInstancePage, WorkflowTransition } from '../types/matcher';
|
|
2
2
|
import { KeyBuilders } from '../utils/keys';
|
|
3
3
|
import { ReliabilityManager } from './ReliabilityManager';
|
|
4
4
|
import { TelemetryManager } from './TelemetryManager';
|
|
@@ -11,6 +11,10 @@ export interface WorkflowHost {
|
|
|
11
11
|
step: WorkflowStep;
|
|
12
12
|
definition: WorkflowDefinition;
|
|
13
13
|
}): Promise<Record<string, any> | void>;
|
|
14
|
+
/** Checked at run start when a step targets 'initiator' (the default target). Skipped if unimplemented. */
|
|
15
|
+
userExists?(userId: string): Promise<boolean>;
|
|
16
|
+
/** Used by cancelWorkflow to clean up a run's outstanding queued/pending assignment. Skipped if unimplemented. */
|
|
17
|
+
removeAssignment?(assignmentId: string): Promise<any>;
|
|
14
18
|
}
|
|
15
19
|
/** Signature for machine task handlers registered via registerMachineHandler(). */
|
|
16
20
|
export type MachineTaskHandler = (args: {
|
|
@@ -50,7 +54,15 @@ export declare class WorkflowManager {
|
|
|
50
54
|
pollBlockMs?: number;
|
|
51
55
|
/** Per-replica cap on processed events per second; unlimited when unset */
|
|
52
56
|
maxEventsPerSecond?: number;
|
|
57
|
+
/** Fired after every durably-applied transition; best-effort, errors swallowed */
|
|
58
|
+
onWorkflowEvent?: (transition: WorkflowTransition) => void;
|
|
53
59
|
});
|
|
60
|
+
/**
|
|
61
|
+
* Fire the onWorkflowEvent hook, if configured. Best-effort: mirrors
|
|
62
|
+
* onMatchDecision's contract, errors thrown by the callback never affect
|
|
63
|
+
* workflow processing.
|
|
64
|
+
*/
|
|
65
|
+
private emitTransition;
|
|
54
66
|
init(): Promise<void>;
|
|
55
67
|
private initStreamConsumerGroup;
|
|
56
68
|
private isNoGroupError;
|
|
@@ -73,14 +85,52 @@ export declare class WorkflowManager {
|
|
|
73
85
|
startWorkflow(workflowDefinitionId: string, userId: string, initialContext?: Record<string, any>): Promise<WorkflowInstance>;
|
|
74
86
|
getWorkflowInstance(instanceId: string): Promise<WorkflowInstance | null>;
|
|
75
87
|
getWorkflowInstanceWithSnapshot(instanceId: string): Promise<WorkflowInstanceWithSnapshot | null>;
|
|
88
|
+
/**
|
|
89
|
+
* List workflow instances (runs) newest-created first, optionally filtered
|
|
90
|
+
* by status and/or workflow definition. Paginated via an opaque cursor
|
|
91
|
+
* (the createdAt score of the last item returned) — pass it back as
|
|
92
|
+
* `cursor` for the next page.
|
|
93
|
+
*/
|
|
94
|
+
listWorkflowInstances(query?: WorkflowInstanceQuery): Promise<WorkflowInstancePage>;
|
|
76
95
|
getActiveWorkflowsForUser(userId: string): Promise<WorkflowInstance[]>;
|
|
96
|
+
/**
|
|
97
|
+
* Cancel a running workflow instance. Cleans up its outstanding
|
|
98
|
+
* assignment(s) — the current step's assignment, or any still-pending
|
|
99
|
+
* parallel branch assignments — so a cancelled run doesn't leave orphaned
|
|
100
|
+
* work queued/pending forever, and clears their step timeouts.
|
|
101
|
+
*/
|
|
77
102
|
cancelWorkflow(instanceId: string): Promise<boolean>;
|
|
78
103
|
private executeWorkflowStep;
|
|
79
104
|
private executeMachineStep;
|
|
80
105
|
private setStepTimeout;
|
|
81
106
|
processExpiredWorkflowSteps(): Promise<number>;
|
|
107
|
+
/**
|
|
108
|
+
* Complete (or fail) an external step from outside this process — the
|
|
109
|
+
* counterpart to the `step.ready` transition. Validates the step is
|
|
110
|
+
* actually the run's current step (or a pending parallel branch) and is
|
|
111
|
+
* really an external step, clears its timeout, then publishes the same
|
|
112
|
+
* COMPLETED/FAILED event onto the stream that in-process completions use,
|
|
113
|
+
* so the orchestrator advances the run through the ordinary transition
|
|
114
|
+
* pipeline (idempotency, retries, and DLQ all still apply).
|
|
115
|
+
*/
|
|
116
|
+
completeWorkflowStep(instanceId: string, stepId: string, outcome: {
|
|
117
|
+
success: boolean;
|
|
118
|
+
data?: Record<string, any>;
|
|
119
|
+
error?: string;
|
|
120
|
+
}): Promise<boolean>;
|
|
82
121
|
private createWorkflowAssignment;
|
|
83
122
|
publishWorkflowEvent(event: WorkflowEvent): Promise<string>;
|
|
123
|
+
/**
|
|
124
|
+
* Non-blocking drain of up to `maxEvents` due workflow events, using the
|
|
125
|
+
* main Redis client (no duplicated subscriber connection, no BLOCK wait).
|
|
126
|
+
* Shares all processing internals with the orchestrator loop — idempotency,
|
|
127
|
+
* circuit breaker, retry scheduling, and DLQ all apply — but is meant to be
|
|
128
|
+
* called periodically by a host sweeping many workspaces/tenants rather
|
|
129
|
+
* than running one dedicated blocking loop per matcher instance. Returns
|
|
130
|
+
* the number of events successfully processed (retried/DLQ'd events still
|
|
131
|
+
* count as handled — only a hard read error returns early).
|
|
132
|
+
*/
|
|
133
|
+
processWorkflowEvents(maxEvents?: number): Promise<number>;
|
|
84
134
|
startOrchestrator(): Promise<void>;
|
|
85
135
|
/**
|
|
86
136
|
* Setup subscriber client with comprehensive reconnection handling
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"WorkflowManager.d.ts","sourceRoot":"","sources":["../../src/managers/WorkflowManager.ts"],"names":[],"mappings":"AACA,OAAO,EACH,eAAe,EACf,kBAAkB,EAClB,uBAAuB,EACvB,yBAAyB,EACzB,gBAAgB,EAChB,YAAY,EACZ,aAAa,EAEb,UAAU,EACV,4BAA4B,EAE5B,qBAAqB,
|
|
1
|
+
{"version":3,"file":"WorkflowManager.d.ts","sourceRoot":"","sources":["../../src/managers/WorkflowManager.ts"],"names":[],"mappings":"AACA,OAAO,EACH,eAAe,EACf,kBAAkB,EAClB,uBAAuB,EACvB,y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BAAgB,CAAC,QAAQ,CAAC,EACrC,SAAS,EAAE,MAAM,GAAG,IAAI,EACxB,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EACnC,YAAY,CAAC,EAAE,gBAAgB,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,GAC9C,OAAO,CAAC;QAAE,EAAE,EAAE,OAAO,CAAC;QAAC,QAAQ,CAAC,EAAE,gBAAgB,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;CAgB3E"}
|
|
@@ -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,9 +1065,11 @@ 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 });
|
|
796
1073
|
await this.handleStepFailure(instance, definition, event);
|
|
797
1074
|
}
|
|
798
1075
|
evaluateCondition(condition, result, context) {
|
|
@@ -1028,7 +1305,13 @@ class WorkflowManager {
|
|
|
1028
1305
|
cursor = nextCursor;
|
|
1029
1306
|
for (const entry of entries) {
|
|
1030
1307
|
const instance = await this.getWorkflowInstance(entry.field);
|
|
1031
|
-
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') {
|
|
1032
1315
|
await this.redisClient.zAdd(this.keys.workflowInstancesActive(), {
|
|
1033
1316
|
score: instance.updatedAt,
|
|
1034
1317
|
value: instance.id,
|
|
@@ -1069,6 +1352,7 @@ class WorkflowManager {
|
|
|
1069
1352
|
multi.hDel(this.keys.workflowInstances(), instanceId);
|
|
1070
1353
|
multi.sRem(this.keys.workflowInstancesByUser(instance.initiatorUserId), instanceId);
|
|
1071
1354
|
multi.zRem(this.keys.workflowInstancesActive(), instanceId);
|
|
1355
|
+
multi.zRem(this.keys.workflowInstancesByTime(), instanceId);
|
|
1072
1356
|
await multi.exec();
|
|
1073
1357
|
pruned++;
|
|
1074
1358
|
}
|