assignment-user-matcher 1.2.1 → 1.2.3

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 (43) hide show
  1. package/README.md +609 -5
  2. package/dist/index.d.ts +7 -3
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +13 -1
  5. package/dist/learning/auto-weights.d.ts +31 -0
  6. package/dist/learning/auto-weights.d.ts.map +1 -0
  7. package/dist/learning/auto-weights.js +65 -0
  8. package/dist/learning/features.d.ts +19 -0
  9. package/dist/learning/features.d.ts.map +1 -0
  10. package/dist/learning/features.js +55 -0
  11. package/dist/lua/workflow-transition.lua +29 -0
  12. package/dist/managers/LearningManager.d.ts +129 -0
  13. package/dist/managers/LearningManager.d.ts.map +1 -0
  14. package/dist/managers/LearningManager.js +269 -0
  15. package/dist/managers/ReliabilityManager.d.ts +60 -2
  16. package/dist/managers/ReliabilityManager.d.ts.map +1 -1
  17. package/dist/managers/ReliabilityManager.js +190 -9
  18. package/dist/managers/TelemetryManager.d.ts.map +1 -1
  19. package/dist/managers/WorkflowManager.d.ts +80 -6
  20. package/dist/managers/WorkflowManager.d.ts.map +1 -1
  21. package/dist/managers/WorkflowManager.js +464 -81
  22. package/dist/matcher.class.d.ts +180 -13
  23. package/dist/matcher.class.d.ts.map +1 -1
  24. package/dist/matcher.class.js +632 -46
  25. package/dist/queries/pagination.d.ts.map +1 -1
  26. package/dist/queries/pagination.js +9 -6
  27. package/dist/scoring/match-score.d.ts.map +1 -1
  28. package/dist/scoring/match-score.js +1 -1
  29. package/dist/types/matcher.d.ts +258 -9
  30. package/dist/types/matcher.d.ts.map +1 -1
  31. package/dist/utils/geo.d.ts +26 -0
  32. package/dist/utils/geo.d.ts.map +1 -0
  33. package/dist/utils/geo.js +62 -0
  34. package/dist/utils/keys.d.ts +15 -0
  35. package/dist/utils/keys.d.ts.map +1 -1
  36. package/dist/utils/keys.js +17 -0
  37. package/dist/workflow-builder.d.ts +2 -4
  38. package/dist/workflow-builder.d.ts.map +1 -1
  39. package/dist/workflow-builder.js +4 -46
  40. package/dist/workflow-validation.d.ts +4 -0
  41. package/dist/workflow-validation.d.ts.map +1 -0
  42. package/dist/workflow-validation.js +85 -0
  43. package/package.json +4 -2
@@ -1,7 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.WorkflowManager = void 0;
3
+ exports.WorkflowManager = exports.backoff = void 0;
4
4
  const crypto_1 = require("crypto");
5
+ const ReliabilityManager_1 = require("./ReliabilityManager");
6
+ const workflow_validation_1 = require("../workflow-validation");
7
+ // Re-export the static backoff method for convenience
8
+ exports.backoff = ReliabilityManager_1.ReliabilityManager.backoff;
5
9
  class WorkflowManager {
6
10
  constructor(redisClient, keys, reliability, telemetry, host, options) {
7
11
  this.redisClient = redisClient;
@@ -13,7 +17,11 @@ class WorkflowManager {
13
17
  this.orchestratorRunning = false;
14
18
  this.orchestratorAbortController = null;
15
19
  this.subscriberClient = null;
20
+ this.subscriberReconnectAttempts = 0;
16
21
  this.luaScriptSha = null;
22
+ this.machineHandlers = new Map();
23
+ this.throttleWindowStart = 0;
24
+ this.throttleTokensUsed = 0;
17
25
  }
18
26
  async init() {
19
27
  if (this.options.enableWorkflows) {
@@ -33,14 +41,27 @@ class WorkflowManager {
33
41
  }
34
42
  }
35
43
  }
44
+ isNoGroupError(err) {
45
+ const message = err instanceof Error ? err.message : String(err ?? '');
46
+ return message.includes('NOGROUP');
47
+ }
36
48
  setLuaScriptSha(sha) {
37
49
  this.luaScriptSha = sha;
38
50
  }
51
+ /**
52
+ * Register a machine task handler by name. Machine steps whose
53
+ * machineTask.handler matches the name run through this handler.
54
+ * Falls back to the host's executeMachineTask when no handler matches.
55
+ */
56
+ registerMachineHandler(name, handler) {
57
+ this.machineHandlers.set(name, handler);
58
+ }
39
59
  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;
60
+ const normalizedDefinition = (0, workflow_validation_1.normalizeWorkflowDefinition)(definition);
61
+ const key = this.keys.workflowDefinition(normalizedDefinition.id);
62
+ await this.redisClient.set(key, JSON.stringify(normalizedDefinition));
63
+ await this.redisClient.hSet(this.keys.workflowDefinitions(), normalizedDefinition.id, normalizedDefinition.name);
64
+ return normalizedDefinition;
44
65
  }
45
66
  async getWorkflowDefinition(id) {
46
67
  const key = this.keys.workflowDefinition(id);
@@ -52,6 +73,12 @@ class WorkflowManager {
52
73
  return Object.entries(definitions).map(([id, name]) => ({ id, name }));
53
74
  }
54
75
  async startWorkflow(workflowDefinitionId, userId, initialContext) {
76
+ if (!workflowDefinitionId.trim()) {
77
+ throw new Error('Workflow definition ID is required');
78
+ }
79
+ if (!userId.trim()) {
80
+ throw new Error('Workflow user ID is required');
81
+ }
55
82
  const { span, end: endSpan } = this.telemetry.startSpan('workflow.start', {
56
83
  'workflow.definition_id': workflowDefinitionId,
57
84
  'workflow.user_id': userId,
@@ -83,9 +110,12 @@ class WorkflowManager {
83
110
  ? JSON.parse(JSON.stringify(definition))
84
111
  : undefined,
85
112
  };
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);
113
+ const multi = this.redisClient.multi();
114
+ multi.hSet(this.keys.workflowInstance(instanceId), 'data', JSON.stringify(instance));
115
+ multi.sAdd(this.keys.workflowInstancesByUser(userId), instanceId);
116
+ multi.hSet(this.keys.workflowInstances(), instanceId, workflowDefinitionId);
117
+ multi.zAdd(this.keys.workflowInstancesActive(), { score: now, value: instanceId });
118
+ await multi.exec();
89
119
  await this.reliability.emitAuditEvent('WORKFLOW_STARTED', instanceId, {
90
120
  definitionId: workflowDefinitionId,
91
121
  definitionVersion: definition.version,
@@ -120,7 +150,7 @@ class WorkflowManager {
120
150
  const instance = await this.getWorkflowInstance(instanceId);
121
151
  if (!instance)
122
152
  return null;
123
- const definition = instance.definitionSnapshot ?? await this.getWorkflowDefinition(instance.workflowDefinitionId);
153
+ const definition = instance.definitionSnapshot ?? (await this.getWorkflowDefinition(instance.workflowDefinitionId));
124
154
  return {
125
155
  ...instance,
126
156
  resolvedDefinition: definition ?? undefined,
@@ -128,10 +158,19 @@ class WorkflowManager {
128
158
  }
129
159
  async getActiveWorkflowsForUser(userId) {
130
160
  const instanceIds = await this.redisClient.sMembers(this.keys.workflowInstancesByUser(userId));
131
- const instances = [];
161
+ if (instanceIds.length === 0)
162
+ return [];
163
+ const multi = this.redisClient.multi();
132
164
  for (const id of instanceIds) {
133
- const instance = await this.getWorkflowInstance(id);
134
- if (instance && instance.status === 'active') {
165
+ multi.hGet(this.keys.workflowInstance(id), 'data');
166
+ }
167
+ const results = (await multi.exec());
168
+ const instances = [];
169
+ for (const json of results) {
170
+ if (!json)
171
+ continue;
172
+ const instance = JSON.parse(String(json));
173
+ if (instance.status === 'active') {
135
174
  instances.push(instance);
136
175
  }
137
176
  }
@@ -165,7 +204,7 @@ class WorkflowManager {
165
204
  if (!parallelStep.machineTask?.handler) {
166
205
  throw new Error(`Machine step "${parallelStep.id}" is missing machineTask.handler`);
167
206
  }
168
- const syntheticAssignmentId = (0, crypto_1.randomUUID)();
207
+ const syntheticAssignmentId = this.deterministicAssignmentId(instance, parallelStepId);
169
208
  machineParallelSteps.push({ stepId: parallelStepId, assignmentId: syntheticAssignmentId });
170
209
  branches.push({
171
210
  stepId: parallelStepId,
@@ -223,7 +262,7 @@ class WorkflowManager {
223
262
  await this.saveInstance(instance, expectedVersion);
224
263
  }
225
264
  async executeMachineStep(instance, step, definition, assignmentId) {
226
- const syntheticAssignmentId = assignmentId ?? (0, crypto_1.randomUUID)();
265
+ const syntheticAssignmentId = assignmentId ?? this.deterministicAssignmentId(instance, step.id);
227
266
  const eventBase = {
228
267
  eventId: (0, crypto_1.randomUUID)(),
229
268
  type: 'COMPLETED',
@@ -234,14 +273,32 @@ class WorkflowManager {
234
273
  timestamp: Date.now(),
235
274
  };
236
275
  try {
237
- if (!this.host.executeMachineTask) {
276
+ const handlerName = step.machineTask?.handler;
277
+ const registered = handlerName ? this.machineHandlers.get(handlerName) : undefined;
278
+ const executor = registered ?? (this.host.executeMachineTask ? (args) => this.host.executeMachineTask(args) : undefined);
279
+ if (!executor) {
238
280
  throw new Error(`Machine task executor not configured for step "${step.id}" (handler: ${step.machineTask?.handler ?? 'unknown'})`);
239
281
  }
240
- const result = await this.host.executeMachineTask({
241
- instance,
242
- step,
243
- definition,
244
- });
282
+ const run = Promise.resolve(executor({ instance, step, definition }));
283
+ // Prevent unhandled rejections when the handler loses the timeout race
284
+ run.catch(() => { });
285
+ const timeoutMs = step.timeoutMs ?? definition.defaultTimeoutMs;
286
+ let result;
287
+ if (timeoutMs) {
288
+ let timer;
289
+ const timeout = new Promise((_, reject) => {
290
+ timer = setTimeout(() => reject(new Error(`Machine step "${step.id}" timed out after ${timeoutMs}ms`)), timeoutMs);
291
+ });
292
+ try {
293
+ result = await Promise.race([run, timeout]);
294
+ }
295
+ finally {
296
+ clearTimeout(timer);
297
+ }
298
+ }
299
+ else {
300
+ result = await run;
301
+ }
245
302
  await this.processWorkflowEvent({
246
303
  ...eventBase,
247
304
  type: 'COMPLETED',
@@ -261,41 +318,48 @@ class WorkflowManager {
261
318
  async setStepTimeout(instanceId, stepId, timeoutMs) {
262
319
  const expiryKey = this.keys.workflowStepExpiry(instanceId, stepId);
263
320
  const expiryTime = Date.now() + timeoutMs;
264
- await this.redisClient.set(expiryKey, String(expiryTime), { PX: timeoutMs });
321
+ const multi = this.redisClient.multi();
322
+ multi.set(expiryKey, String(expiryTime), { PX: timeoutMs });
323
+ multi.zAdd(this.keys.workflowStepExpiryIndex(), {
324
+ score: expiryTime,
325
+ value: `${instanceId}|${stepId}`,
326
+ });
327
+ await multi.exec();
265
328
  }
266
329
  async processExpiredWorkflowSteps() {
267
330
  if (!this.options.enableWorkflows)
268
331
  return 0;
269
- const instances = await this.redisClient.hGetAll(this.keys.workflowInstances());
332
+ const indexKey = this.keys.workflowStepExpiryIndex();
333
+ const due = await this.redisClient.zRangeByScore(indexKey, '-inf', Date.now());
270
334
  let expiredCount = 0;
271
- for (const [instanceId] of Object.entries(instances)) {
335
+ for (const member of due) {
336
+ // Atomic claim: only the replica that removes the member fires the expiry
337
+ const removed = await this.redisClient.zRem(indexKey, member);
338
+ if (!removed)
339
+ continue;
340
+ const separatorIndex = member.indexOf('|');
341
+ if (separatorIndex === -1)
342
+ continue;
343
+ const instanceId = member.slice(0, separatorIndex);
344
+ const stepId = member.slice(separatorIndex + 1);
272
345
  const instance = await this.getWorkflowInstance(instanceId);
273
346
  if (!instance || instance.status !== 'active')
274
347
  continue;
275
- const currentStepId = instance.currentStepId;
276
- if (!currentStepId)
348
+ const branch = instance.parallelBranches?.find((b) => b.stepId === stepId);
349
+ const isCurrentStep = instance.currentStepId === stepId;
350
+ const isPendingBranch = branch?.status === 'pending';
351
+ if (!isCurrentStep && !isPendingBranch)
277
352
  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
- }
353
+ await this.publishWorkflowEvent({
354
+ eventId: (0, crypto_1.randomUUID)(),
355
+ type: 'EXPIRED',
356
+ userId: instance.initiatorUserId,
357
+ assignmentId: branch?.assignmentId ?? instance.currentAssignmentId ?? '',
358
+ workflowInstanceId: instanceId,
359
+ stepId,
360
+ timestamp: Date.now(),
361
+ });
362
+ expiredCount++;
299
363
  }
300
364
  return expiredCount;
301
365
  }
@@ -318,7 +382,7 @@ class WorkflowManager {
318
382
  else {
319
383
  targetUserId = targetUserSelector;
320
384
  }
321
- const assignmentId = (0, crypto_1.randomUUID)();
385
+ const assignmentId = this.deterministicAssignmentId(instance, step.id);
322
386
  const assignment = {
323
387
  id: assignmentId,
324
388
  tags: step.assignmentTemplate.tags ?? ['workflow'],
@@ -370,19 +434,82 @@ class WorkflowManager {
370
434
  return;
371
435
  this.orchestratorRunning = true;
372
436
  this.orchestratorAbortController = new AbortController();
373
- this.subscriberClient = this.redisClient.duplicate();
374
- await this.subscriberClient.connect();
437
+ // Ensure the stream and group exist even if Redis was flushed since init.
438
+ await this.initStreamConsumerGroup();
439
+ // Setup subscriber client with reconnection handling
440
+ await this.setupSubscriberClient();
375
441
  this.orchestratorLoop().catch((err) => {
376
442
  if (!this.orchestratorAbortController?.signal.aborted) {
377
443
  console.error('Orchestrator error:', err);
378
444
  }
379
445
  });
380
446
  }
447
+ /**
448
+ * Setup subscriber client with comprehensive reconnection handling
449
+ */
450
+ async setupSubscriberClient() {
451
+ this.subscriberClient = this.redisClient.duplicate();
452
+ // Setup reconnection handling
453
+ this.subscriberClient.on('error', (err) => {
454
+ console.error('Subscriber client error:', err);
455
+ this.subscriberReconnectAttempts++;
456
+ this.reliability.updateReconnectCount(this.subscriberReconnectAttempts);
457
+ });
458
+ this.subscriberClient.on('connect', () => {
459
+ console.log('Subscriber client connected');
460
+ this.subscriberReconnectAttempts = 0;
461
+ this.reliability.updateReconnectCount(0);
462
+ });
463
+ this.subscriberClient.on('disconnect', () => {
464
+ console.warn('Subscriber client disconnected');
465
+ this.reliability.updateRedisHealth(false, 'Subscriber client disconnected');
466
+ });
467
+ this.subscriberClient.on('ready', () => {
468
+ console.log('Subscriber client ready');
469
+ this.reliability.updateRedisHealth(true);
470
+ });
471
+ await this.subscriberClient.connect();
472
+ }
473
+ /**
474
+ * Reconnect subscriber client with exponential backoff
475
+ */
476
+ async reconnectSubscriberClient() {
477
+ if (this.subscriberClient?.isOpen) {
478
+ await this.subscriberClient.quit();
479
+ }
480
+ const maxAttempts = 5;
481
+ let attempt = 0;
482
+ while (attempt < maxAttempts && this.orchestratorRunning) {
483
+ try {
484
+ await this.setupSubscriberClient();
485
+ console.log('Subscriber client reconnected successfully');
486
+ return;
487
+ }
488
+ catch (err) {
489
+ attempt++;
490
+ this.subscriberReconnectAttempts = attempt;
491
+ if (attempt >= maxAttempts) {
492
+ console.error(`Failed to reconnect subscriber client after ${maxAttempts} attempts`);
493
+ throw err;
494
+ }
495
+ // Exponential backoff: 100ms, 200ms, 400ms, 800ms, 1600ms
496
+ const delay = Math.min(100 * Math.pow(2, attempt - 1), 2000);
497
+ console.warn(`Subscriber client reconnection attempt ${attempt}/${maxAttempts}, retrying in ${delay}ms`);
498
+ await new Promise((resolve) => setTimeout(resolve, delay));
499
+ }
500
+ }
501
+ throw new Error(`Failed to reconnect subscriber client after ${maxAttempts} attempts`);
502
+ }
381
503
  async stopOrchestrator() {
382
504
  this.orchestratorRunning = false;
383
505
  this.orchestratorAbortController?.abort();
384
506
  if (this.subscriberClient?.isOpen) {
385
- await this.subscriberClient.quit();
507
+ try {
508
+ await this.subscriberClient.quit();
509
+ }
510
+ catch (err) {
511
+ console.error('Error closing subscriber client:', err);
512
+ }
386
513
  this.subscriberClient = null;
387
514
  }
388
515
  }
@@ -396,6 +523,12 @@ class WorkflowManager {
396
523
  catch (err) {
397
524
  console.error('Error reclaiming orphaned messages:', err);
398
525
  }
526
+ try {
527
+ await this.drainScheduledRetries();
528
+ }
529
+ catch (err) {
530
+ console.error('Error draining scheduled retries:', err);
531
+ }
399
532
  }, this.options.reclaimIntervalMs);
400
533
  try {
401
534
  while (this.orchestratorRunning) {
@@ -404,7 +537,10 @@ class WorkflowManager {
404
537
  await new Promise((r) => setTimeout(r, 5000));
405
538
  continue;
406
539
  }
407
- const response = await client.xReadGroup(this.options.streamConsumerGroup, this.options.streamConsumerName, [{ key: streamKey, id: '>' }], { COUNT: 10, BLOCK: 5000 });
540
+ const response = (await client.xReadGroup(this.options.streamConsumerGroup, this.options.streamConsumerName, [{ key: streamKey, id: '>' }], {
541
+ COUNT: this.options.eventBatchSize ?? 10,
542
+ BLOCK: this.options.pollBlockMs ?? 5000,
543
+ }));
408
544
  if (!response)
409
545
  continue;
410
546
  for (const stream of response) {
@@ -414,6 +550,7 @@ class WorkflowManager {
414
550
  await client.xAck(streamKey, this.options.streamConsumerGroup, message.id);
415
551
  continue;
416
552
  }
553
+ await this.applyEventThrottle();
417
554
  try {
418
555
  await this.processWorkflowEvent(event);
419
556
  await this.reliability.markEventProcessed(event.eventId);
@@ -426,7 +563,7 @@ class WorkflowManager {
426
563
  }
427
564
  catch (err) {
428
565
  console.error(`Error processing event ${event.eventId}:`, err);
429
- this.reliability.recordCircuitBreakerFailure();
566
+ await this.reliability.recordCircuitBreakerFailure();
430
567
  const retryKey = this.keys.eventRetryCount(event.eventId);
431
568
  const retryCount = Number(await this.redisClient.get(retryKey)) || 0;
432
569
  if (retryCount >= this.reliability.options.workflowMaxRetries) {
@@ -434,8 +571,12 @@ class WorkflowManager {
434
571
  await client.xAck(streamKey, this.options.streamConsumerGroup, message.id);
435
572
  }
436
573
  else {
437
- await this.redisClient.incr(retryKey);
574
+ const nextRetryCount = Number(await this.redisClient.incr(retryKey));
438
575
  await this.redisClient.expire(retryKey, 86400);
576
+ // Schedule a delayed retry with backoff and release the
577
+ // stream entry instead of waiting for the reclaim idle window.
578
+ await this.scheduleEventRetry(event, nextRetryCount);
579
+ await client.xAck(streamKey, this.options.streamConsumerGroup, message.id);
439
580
  }
440
581
  }
441
582
  }
@@ -444,9 +585,27 @@ class WorkflowManager {
444
585
  catch (err) {
445
586
  if (this.orchestratorAbortController?.signal.aborted)
446
587
  break;
588
+ if (this.isNoGroupError(err)) {
589
+ await this.initStreamConsumerGroup();
590
+ continue;
591
+ }
447
592
  console.error('Orchestrator read error:', err);
448
- this.reliability.recordCircuitBreakerFailure();
449
- await new Promise((r) => setTimeout(r, 1000));
593
+ await this.reliability.recordCircuitBreakerFailure();
594
+ // Check if it's a connection error and try to reconnect
595
+ const errorMessage = err?.message || String(err);
596
+ if (errorMessage.includes('connection') ||
597
+ errorMessage.includes('Socket') ||
598
+ errorMessage.includes('ECONN')) {
599
+ console.warn('Detected connection error, attempting to reconnect subscriber client...');
600
+ try {
601
+ await this.reconnectSubscriberClient();
602
+ }
603
+ catch (reconnectErr) {
604
+ console.error('Failed to reconnect subscriber client:', reconnectErr);
605
+ }
606
+ }
607
+ // Exponential backoff before retry
608
+ await ReliabilityManager_1.ReliabilityManager.backoff(this.subscriberReconnectAttempts);
450
609
  }
451
610
  }
452
611
  }
@@ -477,26 +636,39 @@ class WorkflowManager {
477
636
  'workflow.step_id': event.stepId ?? '',
478
637
  });
479
638
  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);
639
+ const maxAttempts = 3;
640
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
641
+ const instance = await this.getWorkflowInstance(event.workflowInstanceId);
642
+ if (!instance || instance.status !== 'active') {
493
643
  break;
494
- case 'FAILED':
495
- await this.handleStepFailure(instance, definition, event);
644
+ }
645
+ const definition = instance.definitionSnapshot ?? (await this.getWorkflowDefinition(instance.workflowDefinitionId));
646
+ if (!definition) {
496
647
  break;
497
- case 'EXPIRED':
498
- await this.handleStepExpiry(instance, definition, event);
648
+ }
649
+ try {
650
+ switch (event.type) {
651
+ case 'COMPLETED':
652
+ await this.handleStepCompletion(instance, definition, event);
653
+ break;
654
+ case 'FAILED':
655
+ await this.handleStepFailure(instance, definition, event);
656
+ break;
657
+ case 'EXPIRED':
658
+ await this.handleStepExpiry(instance, definition, event);
659
+ break;
660
+ }
499
661
  break;
662
+ }
663
+ catch (err) {
664
+ // Optimistic-lock conflicts are retried in place with a fresh
665
+ // read instead of waiting for the reclaim loop.
666
+ if (attempt < maxAttempts - 1 && String(err?.message ?? err).includes('VERSION_MISMATCH')) {
667
+ await ReliabilityManager_1.ReliabilityManager.backoff(attempt, 25, 250);
668
+ continue;
669
+ }
670
+ throw err;
671
+ }
500
672
  }
501
673
  endSpan();
502
674
  }
@@ -592,6 +764,9 @@ class WorkflowManager {
592
764
  type: 'COMPLETED',
593
765
  });
594
766
  }
767
+ else {
768
+ await this.saveInstance(instance, expectedVersion);
769
+ }
595
770
  return;
596
771
  }
597
772
  }
@@ -633,14 +808,21 @@ class WorkflowManager {
633
808
  expectedValue = valueStr;
634
809
  switch (operator) {
635
810
  case '==':
636
- case '===': return actualValue === expectedValue;
811
+ case '===':
812
+ return actualValue === expectedValue;
637
813
  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;
814
+ case '!==':
815
+ return actualValue !== expectedValue;
816
+ case '>':
817
+ return actualValue > expectedValue;
818
+ case '<':
819
+ return actualValue < expectedValue;
820
+ case '>=':
821
+ return actualValue >= expectedValue;
822
+ case '<=':
823
+ return actualValue <= expectedValue;
824
+ default:
825
+ return false;
644
826
  }
645
827
  }
646
828
  catch {
@@ -691,6 +873,10 @@ class WorkflowManager {
691
873
  }
692
874
  }
693
875
  catch (err) {
876
+ if (this.isNoGroupError(err)) {
877
+ await this.initStreamConsumerGroup();
878
+ return 0;
879
+ }
694
880
  console.error('Error in XAUTOCLAIM:', err);
695
881
  }
696
882
  return totalReclaimed;
@@ -701,10 +887,10 @@ class WorkflowManager {
701
887
  instance.updatedAt = Date.now();
702
888
  const newData = JSON.stringify(instance);
703
889
  if (this.luaScriptSha) {
704
- const result = await this.redisClient.evalSha(this.luaScriptSha, {
890
+ const result = (await this.redisClient.evalSha(this.luaScriptSha, {
705
891
  keys: [instanceKey],
706
892
  arguments: [String(expectedVersion), newData],
707
- });
893
+ }));
708
894
  const parsed = JSON.parse(result);
709
895
  if (parsed.err) {
710
896
  throw new Error(`Workflow transition failed: ${parsed.err}`);
@@ -713,6 +899,203 @@ class WorkflowManager {
713
899
  else {
714
900
  await this.redisClient.hSet(instanceKey, 'data', newData);
715
901
  }
902
+ await this.syncInstanceIndexes(instance);
903
+ }
904
+ /**
905
+ * Keep the active-instance index in sync with instance status and apply
906
+ * the retention policy to terminal instances.
907
+ */
908
+ async syncInstanceIndexes(instance) {
909
+ const activeKey = this.keys.workflowInstancesActive();
910
+ if (instance.status === 'active') {
911
+ await this.redisClient.zAdd(activeKey, { score: instance.updatedAt, value: instance.id });
912
+ return;
913
+ }
914
+ const multi = this.redisClient.multi();
915
+ multi.zRem(activeKey, instance.id);
916
+ if (this.options.retentionMs) {
917
+ multi.pExpire(this.keys.workflowInstance(instance.id), this.options.retentionMs);
918
+ multi.hDel(this.keys.workflowInstances(), instance.id);
919
+ multi.sRem(this.keys.workflowInstancesByUser(instance.initiatorUserId), instance.id);
920
+ }
921
+ await multi.exec();
922
+ }
923
+ /**
924
+ * Deterministic assignment id for a step execution, so replays of the same
925
+ * event after a crash produce the same assignment instead of duplicates.
926
+ */
927
+ deterministicAssignmentId(instance, stepId) {
928
+ return (0, crypto_1.createHash)('sha256')
929
+ .update(`wfa:${instance.id}:${stepId}:${instance.retryCount}:${instance.history.length}`)
930
+ .digest('hex')
931
+ .slice(0, 32);
932
+ }
933
+ /**
934
+ * Per-replica flow-rate limiter: allows a burst of up to maxEventsPerSecond
935
+ * events per one-second window, then waits for the window to roll over.
936
+ * No-op when maxEventsPerSecond is unset.
937
+ */
938
+ async applyEventThrottle() {
939
+ const limit = this.options.maxEventsPerSecond;
940
+ if (!limit || limit <= 0)
941
+ return;
942
+ const now = Date.now();
943
+ if (now - this.throttleWindowStart >= 1000) {
944
+ this.throttleWindowStart = now;
945
+ this.throttleTokensUsed = 0;
946
+ }
947
+ if (this.throttleTokensUsed >= limit) {
948
+ const waitMs = Math.max(this.throttleWindowStart + 1000 - now, 1);
949
+ await new Promise((r) => setTimeout(r, waitMs));
950
+ this.throttleWindowStart = Date.now();
951
+ this.throttleTokensUsed = 0;
952
+ }
953
+ this.throttleTokensUsed++;
954
+ }
955
+ /**
956
+ * Schedule a failed event for a delayed retry with exponential backoff.
957
+ */
958
+ async scheduleEventRetry(event, attempt) {
959
+ const base = this.options.retryBackoffMs ?? 1000;
960
+ const delay = Math.min(base * Math.pow(2, Math.max(attempt - 1, 0)), 60000);
961
+ await this.redisClient.zAdd(this.keys.eventsRetryScheduled(), {
962
+ score: Date.now() + delay,
963
+ value: JSON.stringify(event),
964
+ });
965
+ }
966
+ /**
967
+ * Process due scheduled retries. Entries are claimed atomically (ZREM) so
968
+ * concurrent replicas never process the same retry twice.
969
+ */
970
+ async drainScheduledRetries() {
971
+ const key = this.keys.eventsRetryScheduled();
972
+ const due = await this.redisClient.zRangeByScore(key, '-inf', Date.now());
973
+ let processed = 0;
974
+ for (const raw of due) {
975
+ const removed = await this.redisClient.zRem(key, raw);
976
+ if (!removed)
977
+ continue;
978
+ let event;
979
+ try {
980
+ event = JSON.parse(raw);
981
+ }
982
+ catch {
983
+ continue;
984
+ }
985
+ if (await this.reliability.isEventProcessed(event.eventId))
986
+ continue;
987
+ await this.applyEventThrottle();
988
+ try {
989
+ await this.processWorkflowEvent(event);
990
+ await this.reliability.markEventProcessed(event.eventId);
991
+ processed++;
992
+ }
993
+ catch (err) {
994
+ const retryKey = this.keys.eventRetryCount(event.eventId);
995
+ const retryCount = Number(await this.redisClient.incr(retryKey));
996
+ await this.redisClient.expire(retryKey, 86400);
997
+ if (retryCount >= this.reliability.options.workflowMaxRetries) {
998
+ await this.reliability.moveToDeadLetter(event, 'Max retries exceeded', err instanceof Error ? err : new Error(String(err)));
999
+ }
1000
+ else {
1001
+ await this.scheduleEventRetry(event, retryCount);
1002
+ }
1003
+ }
1004
+ }
1005
+ return processed;
1006
+ }
1007
+ /**
1008
+ * Backfill the active-instance index from legacy instance records that
1009
+ * were created before the index existed. Safe to run multiple times.
1010
+ */
1011
+ async backfillWorkflowIndexes() {
1012
+ let cursor = '0';
1013
+ let indexed = 0;
1014
+ do {
1015
+ const { cursor: nextCursor, entries } = await this.redisClient.hScan(this.keys.workflowInstances(), cursor, {
1016
+ COUNT: 100,
1017
+ });
1018
+ cursor = nextCursor;
1019
+ for (const entry of entries) {
1020
+ const instance = await this.getWorkflowInstance(entry.field);
1021
+ if (instance && instance.status === 'active') {
1022
+ await this.redisClient.zAdd(this.keys.workflowInstancesActive(), {
1023
+ score: instance.updatedAt,
1024
+ value: instance.id,
1025
+ });
1026
+ indexed++;
1027
+ }
1028
+ }
1029
+ } while (cursor !== '0');
1030
+ return indexed;
1031
+ }
1032
+ /**
1033
+ * Remove terminal (completed/failed/cancelled) workflow instances that
1034
+ * were last updated more than olderThanMs ago, including their registry,
1035
+ * per-user, and active-index entries.
1036
+ */
1037
+ async pruneWorkflowInstances(olderThanMs) {
1038
+ const cutoff = Date.now() - olderThanMs;
1039
+ let cursor = '0';
1040
+ let pruned = 0;
1041
+ do {
1042
+ const { cursor: nextCursor, entries } = await this.redisClient.hScan(this.keys.workflowInstances(), cursor, {
1043
+ COUNT: 100,
1044
+ });
1045
+ cursor = nextCursor;
1046
+ for (const entry of entries) {
1047
+ const instanceId = entry.field;
1048
+ const instance = await this.getWorkflowInstance(instanceId);
1049
+ if (!instance) {
1050
+ await this.redisClient.hDel(this.keys.workflowInstances(), instanceId);
1051
+ continue;
1052
+ }
1053
+ if (instance.status === 'active')
1054
+ continue;
1055
+ if (instance.updatedAt > cutoff)
1056
+ continue;
1057
+ const multi = this.redisClient.multi();
1058
+ multi.del(this.keys.workflowInstance(instanceId));
1059
+ multi.hDel(this.keys.workflowInstances(), instanceId);
1060
+ multi.sRem(this.keys.workflowInstancesByUser(instance.initiatorUserId), instanceId);
1061
+ multi.zRem(this.keys.workflowInstancesActive(), instanceId);
1062
+ await multi.exec();
1063
+ pruned++;
1064
+ }
1065
+ } while (cursor !== '0');
1066
+ return pruned;
1067
+ }
1068
+ /**
1069
+ * Operational metrics for the workflow engine.
1070
+ */
1071
+ async getWorkflowMetrics() {
1072
+ const [activeInstances, scheduledRetries, deadLetterQueueSize] = await Promise.all([
1073
+ this.redisClient.zCard(this.keys.workflowInstancesActive()),
1074
+ this.redisClient.zCard(this.keys.eventsRetryScheduled()),
1075
+ this.reliability.getDeadLetterQueueSize(),
1076
+ ]);
1077
+ let streamLength = 0;
1078
+ let streamPending = 0;
1079
+ try {
1080
+ streamLength = Number(await this.redisClient.xLen(this.keys.eventStream()));
1081
+ }
1082
+ catch {
1083
+ // Stream may not exist yet
1084
+ }
1085
+ try {
1086
+ const pendingInfo = await this.redisClient.xPending(this.keys.eventStream(), this.options.streamConsumerGroup);
1087
+ streamPending = Number(pendingInfo?.pending ?? 0);
1088
+ }
1089
+ catch {
1090
+ // Consumer group may not exist yet
1091
+ }
1092
+ return {
1093
+ activeInstances: Number(activeInstances),
1094
+ scheduledRetries: Number(scheduledRetries),
1095
+ deadLetterQueueSize,
1096
+ streamLength,
1097
+ streamPending,
1098
+ };
716
1099
  }
717
1100
  async atomicWorkflowTransition(instanceId, expectedVersion, newStatus, newStepId, updatedContext, historyEntry) {
718
1101
  const instance = await this.getWorkflowInstance(instanceId);