assignment-user-matcher 1.1.6 → 1.2.1

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.
Files changed (44) hide show
  1. package/README.md +18 -2
  2. package/dist/index.d.ts +4 -0
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +26 -1
  5. package/dist/managers/ReliabilityManager.d.ts +42 -0
  6. package/dist/managers/ReliabilityManager.d.ts.map +1 -0
  7. package/dist/managers/ReliabilityManager.js +115 -0
  8. package/dist/managers/TelemetryManager.d.ts +13 -0
  9. package/dist/managers/TelemetryManager.d.ts.map +1 -0
  10. package/dist/managers/TelemetryManager.js +52 -0
  11. package/dist/managers/WorkflowManager.d.ts +69 -0
  12. package/dist/managers/WorkflowManager.d.ts.map +1 -0
  13. package/dist/managers/WorkflowManager.js +735 -0
  14. package/dist/matcher.class.d.ts +143 -77
  15. package/dist/matcher.class.d.ts.map +1 -1
  16. package/dist/matcher.class.js +460 -447
  17. package/dist/queries/index.d.ts +5 -0
  18. package/dist/queries/index.d.ts.map +1 -0
  19. package/dist/queries/index.js +20 -0
  20. package/dist/queries/pagination.d.ts +51 -0
  21. package/dist/queries/pagination.d.ts.map +1 -0
  22. package/dist/queries/pagination.js +200 -0
  23. package/dist/scoring/index.d.ts +5 -0
  24. package/dist/scoring/index.d.ts.map +1 -0
  25. package/dist/scoring/index.js +20 -0
  26. package/dist/scoring/match-score.d.ts +29 -0
  27. package/dist/scoring/match-score.d.ts.map +1 -0
  28. package/dist/scoring/match-score.js +131 -0
  29. package/dist/types/matcher.d.ts +279 -0
  30. package/dist/types/matcher.d.ts.map +1 -0
  31. package/dist/types/matcher.js +2 -0
  32. package/dist/utils/cidr.d.ts +40 -0
  33. package/dist/utils/cidr.d.ts.map +1 -0
  34. package/dist/utils/cidr.js +150 -0
  35. package/dist/utils/index.d.ts +6 -0
  36. package/dist/utils/index.d.ts.map +1 -0
  37. package/dist/utils/index.js +21 -0
  38. package/dist/utils/keys.d.ts +45 -0
  39. package/dist/utils/keys.d.ts.map +1 -0
  40. package/dist/utils/keys.js +57 -0
  41. package/dist/workflow-builder.d.ts +195 -0
  42. package/dist/workflow-builder.d.ts.map +1 -0
  43. package/dist/workflow-builder.js +366 -0
  44. package/package.json +1 -1
@@ -0,0 +1,735 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WorkflowManager = void 0;
4
+ const crypto_1 = require("crypto");
5
+ class WorkflowManager {
6
+ constructor(redisClient, keys, reliability, telemetry, host, options) {
7
+ this.redisClient = redisClient;
8
+ this.keys = keys;
9
+ this.reliability = reliability;
10
+ this.telemetry = telemetry;
11
+ this.host = host;
12
+ this.options = options;
13
+ this.orchestratorRunning = false;
14
+ this.orchestratorAbortController = null;
15
+ this.subscriberClient = null;
16
+ this.luaScriptSha = null;
17
+ }
18
+ async init() {
19
+ if (this.options.enableWorkflows) {
20
+ await this.initStreamConsumerGroup();
21
+ }
22
+ }
23
+ async initStreamConsumerGroup() {
24
+ const streamKey = this.keys.eventStream();
25
+ try {
26
+ await this.redisClient.xGroupCreate(streamKey, this.options.streamConsumerGroup, '0', {
27
+ MKSTREAM: true,
28
+ });
29
+ }
30
+ catch (err) {
31
+ if (!err.message?.includes('BUSYGROUP')) {
32
+ throw err;
33
+ }
34
+ }
35
+ }
36
+ setLuaScriptSha(sha) {
37
+ this.luaScriptSha = sha;
38
+ }
39
+ async registerWorkflow(definition) {
40
+ const key = this.keys.workflowDefinition(definition.id);
41
+ await this.redisClient.set(key, JSON.stringify(definition));
42
+ await this.redisClient.hSet(this.keys.workflowDefinitions(), definition.id, definition.name);
43
+ return definition;
44
+ }
45
+ async getWorkflowDefinition(id) {
46
+ const key = this.keys.workflowDefinition(id);
47
+ const json = await this.redisClient.get(key);
48
+ return json ? JSON.parse(json) : null;
49
+ }
50
+ async listWorkflowDefinitions() {
51
+ const definitions = await this.redisClient.hGetAll(this.keys.workflowDefinitions());
52
+ return Object.entries(definitions).map(([id, name]) => ({ id, name }));
53
+ }
54
+ async startWorkflow(workflowDefinitionId, userId, initialContext) {
55
+ const { span, end: endSpan } = this.telemetry.startSpan('workflow.start', {
56
+ 'workflow.definition_id': workflowDefinitionId,
57
+ 'workflow.user_id': userId,
58
+ });
59
+ try {
60
+ const definition = await this.getWorkflowDefinition(workflowDefinitionId);
61
+ if (!definition) {
62
+ throw new Error(`Workflow definition not found: ${workflowDefinitionId}`);
63
+ }
64
+ const now = Date.now();
65
+ const instanceId = (0, crypto_1.randomUUID)();
66
+ this.telemetry.setSpanAttributes(span, {
67
+ 'workflow.instance_id': instanceId,
68
+ 'workflow.definition_version': definition.version,
69
+ });
70
+ const instance = {
71
+ id: instanceId,
72
+ workflowDefinitionId,
73
+ initiatorUserId: userId,
74
+ status: 'active',
75
+ currentStepId: definition.initialStepId,
76
+ context: initialContext ?? {},
77
+ history: [],
78
+ retryCount: 0,
79
+ version: 1,
80
+ createdAt: now,
81
+ updatedAt: now,
82
+ definitionSnapshot: this.reliability.options.workflowSnapshotDefinitions !== false
83
+ ? JSON.parse(JSON.stringify(definition))
84
+ : undefined,
85
+ };
86
+ await this.redisClient.hSet(this.keys.workflowInstance(instanceId), 'data', JSON.stringify(instance));
87
+ await this.redisClient.sAdd(this.keys.workflowInstancesByUser(userId), instanceId);
88
+ await this.redisClient.hSet(this.keys.workflowInstances(), instanceId, workflowDefinitionId);
89
+ await this.reliability.emitAuditEvent('WORKFLOW_STARTED', instanceId, {
90
+ definitionId: workflowDefinitionId,
91
+ definitionVersion: definition.version,
92
+ userId,
93
+ }, 'workflow_instance');
94
+ if (this.options.enableWorkflows) {
95
+ await this.publishWorkflowEvent({
96
+ eventId: (0, crypto_1.randomUUID)(),
97
+ type: 'STARTED',
98
+ userId,
99
+ assignmentId: '',
100
+ workflowInstanceId: instanceId,
101
+ stepId: definition.initialStepId,
102
+ timestamp: now,
103
+ });
104
+ }
105
+ await this.executeWorkflowStep(instance, definition.initialStepId, definition);
106
+ endSpan();
107
+ return instance;
108
+ }
109
+ catch (err) {
110
+ this.telemetry.recordSpanError(span, err instanceof Error ? err : new Error(String(err)));
111
+ endSpan();
112
+ throw err;
113
+ }
114
+ }
115
+ async getWorkflowInstance(instanceId) {
116
+ const json = await this.redisClient.hGet(this.keys.workflowInstance(instanceId), 'data');
117
+ return json ? JSON.parse(json) : null;
118
+ }
119
+ async getWorkflowInstanceWithSnapshot(instanceId) {
120
+ const instance = await this.getWorkflowInstance(instanceId);
121
+ if (!instance)
122
+ return null;
123
+ const definition = instance.definitionSnapshot ?? await this.getWorkflowDefinition(instance.workflowDefinitionId);
124
+ return {
125
+ ...instance,
126
+ resolvedDefinition: definition ?? undefined,
127
+ };
128
+ }
129
+ async getActiveWorkflowsForUser(userId) {
130
+ const instanceIds = await this.redisClient.sMembers(this.keys.workflowInstancesByUser(userId));
131
+ const instances = [];
132
+ for (const id of instanceIds) {
133
+ const instance = await this.getWorkflowInstance(id);
134
+ if (instance && instance.status === 'active') {
135
+ instances.push(instance);
136
+ }
137
+ }
138
+ return instances;
139
+ }
140
+ async cancelWorkflow(instanceId) {
141
+ const instance = await this.getWorkflowInstance(instanceId);
142
+ if (!instance) {
143
+ throw new Error(`Workflow instance not found: ${instanceId}`);
144
+ }
145
+ const expectedVersion = instance.version;
146
+ instance.status = 'cancelled';
147
+ await this.saveInstance(instance, expectedVersion);
148
+ return true;
149
+ }
150
+ async executeWorkflowStep(instance, stepId, definition) {
151
+ const step = definition.steps.find((s) => s.id === stepId);
152
+ if (!step) {
153
+ throw new Error(`Step not found: ${stepId} in workflow ${definition.id}`);
154
+ }
155
+ const expectedVersion = instance.version;
156
+ if (step.parallelStepIds && step.parallelStepIds.length > 0) {
157
+ const branches = [];
158
+ const machineParallelSteps = [];
159
+ for (const parallelStepId of step.parallelStepIds) {
160
+ const parallelStep = definition.steps.find((s) => s.id === parallelStepId);
161
+ if (!parallelStep)
162
+ continue;
163
+ const taskType = parallelStep.taskType ?? 'assignment';
164
+ if (taskType === 'machine') {
165
+ if (!parallelStep.machineTask?.handler) {
166
+ throw new Error(`Machine step "${parallelStep.id}" is missing machineTask.handler`);
167
+ }
168
+ const syntheticAssignmentId = (0, crypto_1.randomUUID)();
169
+ machineParallelSteps.push({ stepId: parallelStepId, assignmentId: syntheticAssignmentId });
170
+ branches.push({
171
+ stepId: parallelStepId,
172
+ assignmentId: syntheticAssignmentId,
173
+ status: 'pending',
174
+ });
175
+ }
176
+ else {
177
+ const assignment = await this.createWorkflowAssignment(instance, parallelStep, definition);
178
+ branches.push({
179
+ stepId: parallelStepId,
180
+ assignmentId: assignment.id,
181
+ status: 'pending',
182
+ });
183
+ }
184
+ const timeoutMs = parallelStep.timeoutMs ?? definition.defaultTimeoutMs;
185
+ if (timeoutMs) {
186
+ await this.setStepTimeout(instance.id, parallelStepId, timeoutMs);
187
+ }
188
+ }
189
+ instance.parallelBranches = branches;
190
+ instance.currentStepId = null;
191
+ instance.currentAssignmentId = undefined;
192
+ await this.saveInstance(instance, expectedVersion);
193
+ for (const machineStep of machineParallelSteps) {
194
+ const parallelStep = definition.steps.find((s) => s.id === machineStep.stepId);
195
+ if (!parallelStep)
196
+ continue;
197
+ await this.executeMachineStep(instance, parallelStep, definition, machineStep.assignmentId);
198
+ }
199
+ return;
200
+ }
201
+ const taskType = step.taskType ?? 'assignment';
202
+ if (taskType === 'machine') {
203
+ if (!step.machineTask?.handler) {
204
+ throw new Error(`Machine step "${step.id}" is missing machineTask.handler`);
205
+ }
206
+ instance.currentAssignmentId = undefined;
207
+ instance.currentStepId = stepId;
208
+ const timeoutMs = step.timeoutMs ?? definition.defaultTimeoutMs;
209
+ if (timeoutMs) {
210
+ await this.setStepTimeout(instance.id, stepId, timeoutMs);
211
+ }
212
+ await this.saveInstance(instance, expectedVersion);
213
+ await this.executeMachineStep(instance, step, definition);
214
+ return;
215
+ }
216
+ const assignment = await this.createWorkflowAssignment(instance, step, definition);
217
+ instance.currentAssignmentId = assignment.id;
218
+ instance.currentStepId = stepId;
219
+ const timeoutMs = step.timeoutMs ?? definition.defaultTimeoutMs;
220
+ if (timeoutMs) {
221
+ await this.setStepTimeout(instance.id, stepId, timeoutMs);
222
+ }
223
+ await this.saveInstance(instance, expectedVersion);
224
+ }
225
+ async executeMachineStep(instance, step, definition, assignmentId) {
226
+ const syntheticAssignmentId = assignmentId ?? (0, crypto_1.randomUUID)();
227
+ const eventBase = {
228
+ eventId: (0, crypto_1.randomUUID)(),
229
+ type: 'COMPLETED',
230
+ userId: instance.initiatorUserId,
231
+ assignmentId: syntheticAssignmentId,
232
+ workflowInstanceId: instance.id,
233
+ stepId: step.id,
234
+ timestamp: Date.now(),
235
+ };
236
+ try {
237
+ if (!this.host.executeMachineTask) {
238
+ throw new Error(`Machine task executor not configured for step "${step.id}" (handler: ${step.machineTask?.handler ?? 'unknown'})`);
239
+ }
240
+ const result = await this.host.executeMachineTask({
241
+ instance,
242
+ step,
243
+ definition,
244
+ });
245
+ await this.processWorkflowEvent({
246
+ ...eventBase,
247
+ type: 'COMPLETED',
248
+ payload: result ? { ...result } : undefined,
249
+ });
250
+ }
251
+ catch (err) {
252
+ await this.processWorkflowEvent({
253
+ ...eventBase,
254
+ type: 'FAILED',
255
+ payload: {
256
+ error: err?.message ?? String(err),
257
+ },
258
+ });
259
+ }
260
+ }
261
+ async setStepTimeout(instanceId, stepId, timeoutMs) {
262
+ const expiryKey = this.keys.workflowStepExpiry(instanceId, stepId);
263
+ const expiryTime = Date.now() + timeoutMs;
264
+ await this.redisClient.set(expiryKey, String(expiryTime), { PX: timeoutMs });
265
+ }
266
+ async processExpiredWorkflowSteps() {
267
+ if (!this.options.enableWorkflows)
268
+ return 0;
269
+ const instances = await this.redisClient.hGetAll(this.keys.workflowInstances());
270
+ let expiredCount = 0;
271
+ for (const [instanceId] of Object.entries(instances)) {
272
+ const instance = await this.getWorkflowInstance(instanceId);
273
+ if (!instance || instance.status !== 'active')
274
+ continue;
275
+ const currentStepId = instance.currentStepId;
276
+ if (!currentStepId)
277
+ continue;
278
+ const expiryKey = this.keys.workflowStepExpiry(instanceId, currentStepId);
279
+ const expiryTimeStr = await this.redisClient.get(expiryKey);
280
+ if (expiryTimeStr === null) {
281
+ const definition = await this.getWorkflowDefinition(instance.workflowDefinitionId);
282
+ if (!definition)
283
+ continue;
284
+ const step = definition.steps.find((s) => s.id === currentStepId);
285
+ const timeoutMs = step?.timeoutMs ?? definition.defaultTimeoutMs;
286
+ if (!timeoutMs)
287
+ continue;
288
+ await this.publishWorkflowEvent({
289
+ eventId: (0, crypto_1.randomUUID)(),
290
+ type: 'EXPIRED',
291
+ userId: instance.initiatorUserId,
292
+ assignmentId: instance.currentAssignmentId ?? '',
293
+ workflowInstanceId: instanceId,
294
+ stepId: currentStepId,
295
+ timestamp: Date.now(),
296
+ });
297
+ expiredCount++;
298
+ }
299
+ }
300
+ return expiredCount;
301
+ }
302
+ async createWorkflowAssignment(instance, step, definition) {
303
+ if (!step.assignmentTemplate) {
304
+ throw new Error(`Assignment step "${step.id}" is missing assignmentTemplate`);
305
+ }
306
+ const targetUserSelector = step.targetUser ?? 'initiator';
307
+ let targetUserId;
308
+ if (targetUserSelector === 'initiator') {
309
+ targetUserId = instance.initiatorUserId;
310
+ }
311
+ else if (targetUserSelector === 'previous') {
312
+ const lastEntry = instance.history[instance.history.length - 1];
313
+ targetUserId = lastEntry?.userId ?? instance.initiatorUserId;
314
+ }
315
+ else if (typeof targetUserSelector === 'object' && 'tag' in targetUserSelector) {
316
+ targetUserId = '';
317
+ }
318
+ else {
319
+ targetUserId = targetUserSelector;
320
+ }
321
+ const assignmentId = (0, crypto_1.randomUUID)();
322
+ const assignment = {
323
+ id: assignmentId,
324
+ tags: step.assignmentTemplate.tags ?? ['workflow'],
325
+ priority: step.assignmentTemplate.priority ?? 1000,
326
+ ...step.assignmentTemplate,
327
+ _workflowInstanceId: instance.id,
328
+ _workflowStepId: step.id,
329
+ _workflowContext: instance.context,
330
+ _targetUserId: targetUserId || undefined,
331
+ };
332
+ await this.host.addAssignment(assignment);
333
+ await this.redisClient.set(this.keys.workflowAssignmentLink(assignmentId), JSON.stringify({
334
+ instanceId: instance.id,
335
+ stepId: step.id,
336
+ definitionId: definition.id,
337
+ }));
338
+ if (targetUserId) {
339
+ await this.host.matchUsersAssignments(targetUserId);
340
+ }
341
+ return assignment;
342
+ }
343
+ async publishWorkflowEvent(event) {
344
+ const streamKey = this.keys.eventStream();
345
+ if (!event.workflowInstanceId && event.assignmentId) {
346
+ const linkJson = await this.redisClient.get(this.keys.workflowAssignmentLink(event.assignmentId));
347
+ if (linkJson) {
348
+ const link = JSON.parse(linkJson);
349
+ event.workflowInstanceId = link.instanceId;
350
+ event.stepId = link.stepId;
351
+ }
352
+ }
353
+ const messageId = await this.redisClient.xAdd(streamKey, '*', {
354
+ eventId: event.eventId,
355
+ type: event.type,
356
+ userId: event.userId,
357
+ assignmentId: event.assignmentId,
358
+ workflowInstanceId: event.workflowInstanceId ?? '',
359
+ stepId: event.stepId ?? '',
360
+ timestamp: String(event.timestamp),
361
+ payload: event.payload ? JSON.stringify(event.payload) : '',
362
+ });
363
+ return messageId;
364
+ }
365
+ async startOrchestrator() {
366
+ if (!this.options.enableWorkflows) {
367
+ throw new Error('Workflows are not enabled. Set enableWorkflows: true in options.');
368
+ }
369
+ if (this.orchestratorRunning)
370
+ return;
371
+ this.orchestratorRunning = true;
372
+ this.orchestratorAbortController = new AbortController();
373
+ this.subscriberClient = this.redisClient.duplicate();
374
+ await this.subscriberClient.connect();
375
+ this.orchestratorLoop().catch((err) => {
376
+ if (!this.orchestratorAbortController?.signal.aborted) {
377
+ console.error('Orchestrator error:', err);
378
+ }
379
+ });
380
+ }
381
+ async stopOrchestrator() {
382
+ this.orchestratorRunning = false;
383
+ this.orchestratorAbortController?.abort();
384
+ if (this.subscriberClient?.isOpen) {
385
+ await this.subscriberClient.quit();
386
+ this.subscriberClient = null;
387
+ }
388
+ }
389
+ async orchestratorLoop() {
390
+ const streamKey = this.keys.eventStream();
391
+ const client = this.subscriberClient;
392
+ const reclaimIntervalHandle = setInterval(async () => {
393
+ try {
394
+ await this.reclaimOrphanedMessages();
395
+ }
396
+ catch (err) {
397
+ console.error('Error reclaiming orphaned messages:', err);
398
+ }
399
+ }, this.options.reclaimIntervalMs);
400
+ try {
401
+ while (this.orchestratorRunning) {
402
+ try {
403
+ if (!this.reliability.shouldProcessCircuitBreaker()) {
404
+ await new Promise((r) => setTimeout(r, 5000));
405
+ continue;
406
+ }
407
+ const response = await client.xReadGroup(this.options.streamConsumerGroup, this.options.streamConsumerName, [{ key: streamKey, id: '>' }], { COUNT: 10, BLOCK: 5000 });
408
+ if (!response)
409
+ continue;
410
+ for (const stream of response) {
411
+ for (const message of stream.messages) {
412
+ const event = this.parseStreamMessage(message);
413
+ if (await this.reliability.isEventProcessed(event.eventId)) {
414
+ await client.xAck(streamKey, this.options.streamConsumerGroup, message.id);
415
+ continue;
416
+ }
417
+ try {
418
+ await this.processWorkflowEvent(event);
419
+ await this.reliability.markEventProcessed(event.eventId);
420
+ await client.xAck(streamKey, this.options.streamConsumerGroup, message.id);
421
+ this.reliability.recordCircuitBreakerSuccess();
422
+ await this.reliability.emitAuditEvent('EVENT_PROCESSED', event.eventId, {
423
+ type: event.type,
424
+ workflowInstanceId: event.workflowInstanceId,
425
+ }, 'event');
426
+ }
427
+ catch (err) {
428
+ console.error(`Error processing event ${event.eventId}:`, err);
429
+ this.reliability.recordCircuitBreakerFailure();
430
+ const retryKey = this.keys.eventRetryCount(event.eventId);
431
+ const retryCount = Number(await this.redisClient.get(retryKey)) || 0;
432
+ if (retryCount >= this.reliability.options.workflowMaxRetries) {
433
+ await this.reliability.moveToDeadLetter(event, 'Processing failed after max retries', err instanceof Error ? err : new Error(String(err)));
434
+ await client.xAck(streamKey, this.options.streamConsumerGroup, message.id);
435
+ }
436
+ else {
437
+ await this.redisClient.incr(retryKey);
438
+ await this.redisClient.expire(retryKey, 86400);
439
+ }
440
+ }
441
+ }
442
+ }
443
+ }
444
+ catch (err) {
445
+ if (this.orchestratorAbortController?.signal.aborted)
446
+ break;
447
+ console.error('Orchestrator read error:', err);
448
+ this.reliability.recordCircuitBreakerFailure();
449
+ await new Promise((r) => setTimeout(r, 1000));
450
+ }
451
+ }
452
+ }
453
+ finally {
454
+ clearInterval(reclaimIntervalHandle);
455
+ }
456
+ }
457
+ parseStreamMessage(message) {
458
+ const m = message.message;
459
+ return {
460
+ eventId: m.eventId,
461
+ type: m.type,
462
+ userId: m.userId,
463
+ assignmentId: m.assignmentId,
464
+ workflowInstanceId: m.workflowInstanceId || undefined,
465
+ stepId: m.stepId || undefined,
466
+ timestamp: Number(m.timestamp),
467
+ payload: m.payload ? JSON.parse(m.payload) : undefined,
468
+ };
469
+ }
470
+ async processWorkflowEvent(event) {
471
+ if (!event.workflowInstanceId)
472
+ return;
473
+ const { span, end: endSpan } = this.telemetry.startSpan('workflow.process_event', {
474
+ 'workflow.event_type': event.type,
475
+ 'workflow.event_id': event.eventId,
476
+ 'workflow.instance_id': event.workflowInstanceId,
477
+ 'workflow.step_id': event.stepId ?? '',
478
+ });
479
+ try {
480
+ const instance = await this.getWorkflowInstance(event.workflowInstanceId);
481
+ if (!instance || instance.status !== 'active') {
482
+ endSpan();
483
+ return;
484
+ }
485
+ const definition = instance.definitionSnapshot ?? await this.getWorkflowDefinition(instance.workflowDefinitionId);
486
+ if (!definition) {
487
+ endSpan();
488
+ return;
489
+ }
490
+ switch (event.type) {
491
+ case 'COMPLETED':
492
+ await this.handleStepCompletion(instance, definition, event);
493
+ break;
494
+ case 'FAILED':
495
+ await this.handleStepFailure(instance, definition, event);
496
+ break;
497
+ case 'EXPIRED':
498
+ await this.handleStepExpiry(instance, definition, event);
499
+ break;
500
+ }
501
+ endSpan();
502
+ }
503
+ catch (err) {
504
+ this.telemetry.recordSpanError(span, err instanceof Error ? err : new Error(String(err)));
505
+ endSpan();
506
+ throw err;
507
+ }
508
+ }
509
+ async handleStepCompletion(instance, definition, event) {
510
+ const stepId = event.stepId;
511
+ if (!stepId)
512
+ return;
513
+ const step = definition.steps.find((s) => s.id === stepId);
514
+ if (!step)
515
+ return;
516
+ instance.history.push({
517
+ stepId,
518
+ assignmentId: event.assignmentId,
519
+ userId: event.userId,
520
+ completedAt: event.timestamp,
521
+ result: event.payload,
522
+ });
523
+ if (event.payload) {
524
+ instance.context = { ...instance.context, [`step_${stepId}`]: event.payload };
525
+ }
526
+ const expectedVersion = instance.version;
527
+ if (instance.parallelBranches) {
528
+ const branch = instance.parallelBranches.find((b) => b.stepId === stepId);
529
+ if (branch) {
530
+ branch.status = 'completed';
531
+ branch.result = event.payload;
532
+ const allComplete = instance.parallelBranches.every((b) => b.status === 'completed');
533
+ if (!allComplete && step.waitForAll !== false) {
534
+ await this.saveInstance(instance, expectedVersion);
535
+ return;
536
+ }
537
+ instance.parallelBranches = undefined;
538
+ }
539
+ }
540
+ let nextStepId = null;
541
+ if (step.routing && step.routing.length > 0) {
542
+ for (const route of step.routing) {
543
+ if (this.evaluateCondition(route.condition, event.payload, instance.context)) {
544
+ nextStepId = route.targetStepId;
545
+ break;
546
+ }
547
+ }
548
+ }
549
+ if (!nextStepId && step.defaultNextStepId !== undefined) {
550
+ nextStepId = step.defaultNextStepId;
551
+ }
552
+ if (nextStepId) {
553
+ instance.currentStepId = nextStepId;
554
+ instance.currentAssignmentId = undefined;
555
+ await this.executeWorkflowStep(instance, nextStepId, definition);
556
+ }
557
+ else {
558
+ instance.status = 'completed';
559
+ instance.currentStepId = null;
560
+ instance.currentAssignmentId = undefined;
561
+ await this.saveInstance(instance, expectedVersion);
562
+ }
563
+ }
564
+ async handleStepFailure(instance, definition, event) {
565
+ const stepId = event.stepId;
566
+ if (!stepId)
567
+ return;
568
+ const step = definition.steps.find((s) => s.id === stepId);
569
+ if (!step)
570
+ return;
571
+ const maxRetries = step.maxRetries ?? 0;
572
+ const expectedVersion = instance.version;
573
+ // Handle parallel branch failure
574
+ if (instance.parallelBranches) {
575
+ const branch = instance.parallelBranches.find((b) => b.stepId === stepId);
576
+ if (branch) {
577
+ branch.status = 'failed';
578
+ const policy = step.failurePolicy ?? 'abort';
579
+ if (policy === 'abort') {
580
+ // Fail entire workflow
581
+ instance.status = 'failed';
582
+ await this.saveInstance(instance, expectedVersion);
583
+ return;
584
+ }
585
+ else if (policy === 'continue') {
586
+ // Check if remaining branches can complete
587
+ const allDone = instance.parallelBranches.every((b) => b.status === 'completed' || b.status === 'failed');
588
+ if (allDone) {
589
+ // Proceed with partial results
590
+ await this.handleStepCompletion(instance, definition, {
591
+ ...event,
592
+ type: 'COMPLETED',
593
+ });
594
+ }
595
+ return;
596
+ }
597
+ }
598
+ }
599
+ // Retry logic
600
+ if (instance.retryCount < maxRetries) {
601
+ instance.retryCount += 1;
602
+ await this.executeWorkflowStep(instance, stepId, definition);
603
+ }
604
+ else {
605
+ // Workflow failed
606
+ instance.status = 'failed';
607
+ await this.saveInstance(instance, expectedVersion);
608
+ }
609
+ }
610
+ async handleStepExpiry(instance, definition, event) {
611
+ await this.handleStepFailure(instance, definition, event);
612
+ }
613
+ evaluateCondition(condition, result, context) {
614
+ try {
615
+ const match = condition.match(/^(result|context)\.(\w+)\s*(===|!==|==|!=|>=|<=|>|<)\s*(.+)$/);
616
+ if (!match)
617
+ return false;
618
+ const [, source, field, operator, valueStr] = match;
619
+ const sourceObj = source === 'result' ? result : context;
620
+ const actualValue = sourceObj?.[field];
621
+ let expectedValue;
622
+ if (valueStr === 'true')
623
+ expectedValue = true;
624
+ else if (valueStr === 'false')
625
+ expectedValue = false;
626
+ else if (valueStr === 'null')
627
+ expectedValue = null;
628
+ else if (/^['"].*['"]$/.test(valueStr))
629
+ expectedValue = valueStr.slice(1, -1);
630
+ else if (!isNaN(Number(valueStr)))
631
+ expectedValue = Number(valueStr);
632
+ else
633
+ expectedValue = valueStr;
634
+ switch (operator) {
635
+ case '==':
636
+ case '===': return actualValue === expectedValue;
637
+ case '!=':
638
+ case '!==': return actualValue !== expectedValue;
639
+ case '>': return actualValue > expectedValue;
640
+ case '<': return actualValue < expectedValue;
641
+ case '>=': return actualValue >= expectedValue;
642
+ case '<=': return actualValue <= expectedValue;
643
+ default: return false;
644
+ }
645
+ }
646
+ catch {
647
+ return false;
648
+ }
649
+ }
650
+ async reclaimOrphanedMessages() {
651
+ if (!this.subscriberClient?.isOpen)
652
+ return 0;
653
+ const streamKey = this.keys.eventStream();
654
+ let totalReclaimed = 0;
655
+ try {
656
+ const result = await this.subscriberClient.xAutoClaim(streamKey, this.options.streamConsumerGroup, this.options.streamConsumerName, this.options.reclaimMinIdleMs ?? this.options.reclaimIntervalMs, '0-0', { COUNT: 100 });
657
+ if (result && result.messages && result.messages.length > 0) {
658
+ for (const message of result.messages) {
659
+ if (!message)
660
+ continue;
661
+ const event = this.parseStreamMessage(message);
662
+ try {
663
+ if (await this.reliability.isEventProcessed(event.eventId)) {
664
+ await this.subscriberClient.xAck(streamKey, this.options.streamConsumerGroup, message.id);
665
+ continue;
666
+ }
667
+ const retryKey = this.keys.eventRetryCount(event.eventId);
668
+ const retryCount = Number(await this.redisClient.get(retryKey)) || 0;
669
+ if (retryCount >= this.reliability.options.workflowMaxRetries) {
670
+ await this.reliability.moveToDeadLetter(event, 'Max retries exceeded');
671
+ await this.subscriberClient.xAck(streamKey, this.options.streamConsumerGroup, message.id);
672
+ }
673
+ else {
674
+ try {
675
+ await this.processWorkflowEvent(event);
676
+ await this.reliability.markEventProcessed(event.eventId);
677
+ await this.subscriberClient.xAck(streamKey, this.options.streamConsumerGroup, message.id);
678
+ totalReclaimed++;
679
+ }
680
+ catch (err) {
681
+ await this.redisClient.incr(retryKey);
682
+ await this.redisClient.expire(retryKey, 86400);
683
+ throw err;
684
+ }
685
+ }
686
+ }
687
+ catch (err) {
688
+ console.error(`Error processing reclaimed message ${message.id}:`, err);
689
+ }
690
+ }
691
+ }
692
+ }
693
+ catch (err) {
694
+ console.error('Error in XAUTOCLAIM:', err);
695
+ }
696
+ return totalReclaimed;
697
+ }
698
+ async saveInstance(instance, expectedVersion) {
699
+ const instanceKey = this.keys.workflowInstance(instance.id);
700
+ instance.version += 1;
701
+ instance.updatedAt = Date.now();
702
+ const newData = JSON.stringify(instance);
703
+ if (this.luaScriptSha) {
704
+ const result = await this.redisClient.evalSha(this.luaScriptSha, {
705
+ keys: [instanceKey],
706
+ arguments: [String(expectedVersion), newData],
707
+ });
708
+ const parsed = JSON.parse(result);
709
+ if (parsed.err) {
710
+ throw new Error(`Workflow transition failed: ${parsed.err}`);
711
+ }
712
+ }
713
+ else {
714
+ await this.redisClient.hSet(instanceKey, 'data', newData);
715
+ }
716
+ }
717
+ async atomicWorkflowTransition(instanceId, expectedVersion, newStatus, newStepId, updatedContext, historyEntry) {
718
+ const instance = await this.getWorkflowInstance(instanceId);
719
+ if (!instance)
720
+ return { ok: false, error: 'Instance not found' };
721
+ instance.status = newStatus;
722
+ instance.currentStepId = newStepId;
723
+ instance.context = { ...instance.context, ...updatedContext };
724
+ if (historyEntry)
725
+ instance.history.push(historyEntry);
726
+ try {
727
+ await this.saveInstance(instance, expectedVersion);
728
+ return { ok: true, instance };
729
+ }
730
+ catch (err) {
731
+ return { ok: false, error: err.message };
732
+ }
733
+ }
734
+ }
735
+ exports.WorkflowManager = WorkflowManager;