assignment-user-matcher 1.2.2 → 1.2.5

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 (38) hide show
  1. package/README.md +243 -91
  2. package/dist/index.d.ts +5 -3
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +6 -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/lua/workflow-transition.lua +29 -0
  9. package/dist/managers/LearningManager.d.ts +39 -4
  10. package/dist/managers/LearningManager.d.ts.map +1 -1
  11. package/dist/managers/LearningManager.js +78 -3
  12. package/dist/managers/ReliabilityManager.d.ts +60 -2
  13. package/dist/managers/ReliabilityManager.d.ts.map +1 -1
  14. package/dist/managers/ReliabilityManager.js +190 -9
  15. package/dist/managers/TelemetryManager.d.ts.map +1 -1
  16. package/dist/managers/WorkflowManager.d.ts +78 -1
  17. package/dist/managers/WorkflowManager.d.ts.map +1 -1
  18. package/dist/managers/WorkflowManager.js +449 -77
  19. package/dist/matcher.class.d.ts +195 -8
  20. package/dist/matcher.class.d.ts.map +1 -1
  21. package/dist/matcher.class.js +619 -36
  22. package/dist/queries/pagination.d.ts.map +1 -1
  23. package/dist/queries/pagination.js +9 -6
  24. package/dist/scoring/fair-arbitration.d.ts +68 -0
  25. package/dist/scoring/fair-arbitration.d.ts.map +1 -0
  26. package/dist/scoring/fair-arbitration.js +151 -0
  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 -0
  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 +13 -0
  35. package/dist/utils/keys.d.ts.map +1 -1
  36. package/dist/utils/keys.js +14 -0
  37. package/dist/workflow-validation.d.ts.map +1 -1
  38. package/package.json +58 -57
@@ -1,8 +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");
5
6
  const workflow_validation_1 = require("../workflow-validation");
7
+ // Re-export the static backoff method for convenience
8
+ exports.backoff = ReliabilityManager_1.ReliabilityManager.backoff;
6
9
  class WorkflowManager {
7
10
  constructor(redisClient, keys, reliability, telemetry, host, options) {
8
11
  this.redisClient = redisClient;
@@ -14,7 +17,11 @@ class WorkflowManager {
14
17
  this.orchestratorRunning = false;
15
18
  this.orchestratorAbortController = null;
16
19
  this.subscriberClient = null;
20
+ this.subscriberReconnectAttempts = 0;
17
21
  this.luaScriptSha = null;
22
+ this.machineHandlers = new Map();
23
+ this.throttleWindowStart = 0;
24
+ this.throttleTokensUsed = 0;
18
25
  }
19
26
  async init() {
20
27
  if (this.options.enableWorkflows) {
@@ -34,9 +41,21 @@ class WorkflowManager {
34
41
  }
35
42
  }
36
43
  }
44
+ isNoGroupError(err) {
45
+ const message = err instanceof Error ? err.message : String(err ?? '');
46
+ return message.includes('NOGROUP');
47
+ }
37
48
  setLuaScriptSha(sha) {
38
49
  this.luaScriptSha = sha;
39
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
+ }
40
59
  async registerWorkflow(definition) {
41
60
  const normalizedDefinition = (0, workflow_validation_1.normalizeWorkflowDefinition)(definition);
42
61
  const key = this.keys.workflowDefinition(normalizedDefinition.id);
@@ -91,9 +110,12 @@ class WorkflowManager {
91
110
  ? JSON.parse(JSON.stringify(definition))
92
111
  : undefined,
93
112
  };
94
- await this.redisClient.hSet(this.keys.workflowInstance(instanceId), 'data', JSON.stringify(instance));
95
- await this.redisClient.sAdd(this.keys.workflowInstancesByUser(userId), instanceId);
96
- 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();
97
119
  await this.reliability.emitAuditEvent('WORKFLOW_STARTED', instanceId, {
98
120
  definitionId: workflowDefinitionId,
99
121
  definitionVersion: definition.version,
@@ -128,7 +150,7 @@ class WorkflowManager {
128
150
  const instance = await this.getWorkflowInstance(instanceId);
129
151
  if (!instance)
130
152
  return null;
131
- const definition = instance.definitionSnapshot ?? await this.getWorkflowDefinition(instance.workflowDefinitionId);
153
+ const definition = instance.definitionSnapshot ?? (await this.getWorkflowDefinition(instance.workflowDefinitionId));
132
154
  return {
133
155
  ...instance,
134
156
  resolvedDefinition: definition ?? undefined,
@@ -136,10 +158,19 @@ class WorkflowManager {
136
158
  }
137
159
  async getActiveWorkflowsForUser(userId) {
138
160
  const instanceIds = await this.redisClient.sMembers(this.keys.workflowInstancesByUser(userId));
139
- const instances = [];
161
+ if (instanceIds.length === 0)
162
+ return [];
163
+ const multi = this.redisClient.multi();
140
164
  for (const id of instanceIds) {
141
- const instance = await this.getWorkflowInstance(id);
142
- 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') {
143
174
  instances.push(instance);
144
175
  }
145
176
  }
@@ -173,7 +204,7 @@ class WorkflowManager {
173
204
  if (!parallelStep.machineTask?.handler) {
174
205
  throw new Error(`Machine step "${parallelStep.id}" is missing machineTask.handler`);
175
206
  }
176
- const syntheticAssignmentId = (0, crypto_1.randomUUID)();
207
+ const syntheticAssignmentId = this.deterministicAssignmentId(instance, parallelStepId);
177
208
  machineParallelSteps.push({ stepId: parallelStepId, assignmentId: syntheticAssignmentId });
178
209
  branches.push({
179
210
  stepId: parallelStepId,
@@ -231,7 +262,7 @@ class WorkflowManager {
231
262
  await this.saveInstance(instance, expectedVersion);
232
263
  }
233
264
  async executeMachineStep(instance, step, definition, assignmentId) {
234
- const syntheticAssignmentId = assignmentId ?? (0, crypto_1.randomUUID)();
265
+ const syntheticAssignmentId = assignmentId ?? this.deterministicAssignmentId(instance, step.id);
235
266
  const eventBase = {
236
267
  eventId: (0, crypto_1.randomUUID)(),
237
268
  type: 'COMPLETED',
@@ -242,14 +273,32 @@ class WorkflowManager {
242
273
  timestamp: Date.now(),
243
274
  };
244
275
  try {
245
- 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) {
246
280
  throw new Error(`Machine task executor not configured for step "${step.id}" (handler: ${step.machineTask?.handler ?? 'unknown'})`);
247
281
  }
248
- const result = await this.host.executeMachineTask({
249
- instance,
250
- step,
251
- definition,
252
- });
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
+ }
253
302
  await this.processWorkflowEvent({
254
303
  ...eventBase,
255
304
  type: 'COMPLETED',
@@ -269,41 +318,48 @@ class WorkflowManager {
269
318
  async setStepTimeout(instanceId, stepId, timeoutMs) {
270
319
  const expiryKey = this.keys.workflowStepExpiry(instanceId, stepId);
271
320
  const expiryTime = Date.now() + timeoutMs;
272
- 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();
273
328
  }
274
329
  async processExpiredWorkflowSteps() {
275
330
  if (!this.options.enableWorkflows)
276
331
  return 0;
277
- 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());
278
334
  let expiredCount = 0;
279
- 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);
280
345
  const instance = await this.getWorkflowInstance(instanceId);
281
346
  if (!instance || instance.status !== 'active')
282
347
  continue;
283
- const currentStepId = instance.currentStepId;
284
- 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)
285
352
  continue;
286
- const expiryKey = this.keys.workflowStepExpiry(instanceId, currentStepId);
287
- const expiryTimeStr = await this.redisClient.get(expiryKey);
288
- if (expiryTimeStr === null) {
289
- const definition = await this.getWorkflowDefinition(instance.workflowDefinitionId);
290
- if (!definition)
291
- continue;
292
- const step = definition.steps.find((s) => s.id === currentStepId);
293
- const timeoutMs = step?.timeoutMs ?? definition.defaultTimeoutMs;
294
- if (!timeoutMs)
295
- continue;
296
- await this.publishWorkflowEvent({
297
- eventId: (0, crypto_1.randomUUID)(),
298
- type: 'EXPIRED',
299
- userId: instance.initiatorUserId,
300
- assignmentId: instance.currentAssignmentId ?? '',
301
- workflowInstanceId: instanceId,
302
- stepId: currentStepId,
303
- timestamp: Date.now(),
304
- });
305
- expiredCount++;
306
- }
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++;
307
363
  }
308
364
  return expiredCount;
309
365
  }
@@ -326,7 +382,7 @@ class WorkflowManager {
326
382
  else {
327
383
  targetUserId = targetUserSelector;
328
384
  }
329
- const assignmentId = (0, crypto_1.randomUUID)();
385
+ const assignmentId = this.deterministicAssignmentId(instance, step.id);
330
386
  const assignment = {
331
387
  id: assignmentId,
332
388
  tags: step.assignmentTemplate.tags ?? ['workflow'],
@@ -378,19 +434,82 @@ class WorkflowManager {
378
434
  return;
379
435
  this.orchestratorRunning = true;
380
436
  this.orchestratorAbortController = new AbortController();
381
- this.subscriberClient = this.redisClient.duplicate();
382
- 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();
383
441
  this.orchestratorLoop().catch((err) => {
384
442
  if (!this.orchestratorAbortController?.signal.aborted) {
385
443
  console.error('Orchestrator error:', err);
386
444
  }
387
445
  });
388
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
+ }
389
503
  async stopOrchestrator() {
390
504
  this.orchestratorRunning = false;
391
505
  this.orchestratorAbortController?.abort();
392
506
  if (this.subscriberClient?.isOpen) {
393
- await this.subscriberClient.quit();
507
+ try {
508
+ await this.subscriberClient.quit();
509
+ }
510
+ catch (err) {
511
+ console.error('Error closing subscriber client:', err);
512
+ }
394
513
  this.subscriberClient = null;
395
514
  }
396
515
  }
@@ -404,6 +523,12 @@ class WorkflowManager {
404
523
  catch (err) {
405
524
  console.error('Error reclaiming orphaned messages:', err);
406
525
  }
526
+ try {
527
+ await this.drainScheduledRetries();
528
+ }
529
+ catch (err) {
530
+ console.error('Error draining scheduled retries:', err);
531
+ }
407
532
  }, this.options.reclaimIntervalMs);
408
533
  try {
409
534
  while (this.orchestratorRunning) {
@@ -412,7 +537,10 @@ class WorkflowManager {
412
537
  await new Promise((r) => setTimeout(r, 5000));
413
538
  continue;
414
539
  }
415
- 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
+ }));
416
544
  if (!response)
417
545
  continue;
418
546
  for (const stream of response) {
@@ -422,6 +550,7 @@ class WorkflowManager {
422
550
  await client.xAck(streamKey, this.options.streamConsumerGroup, message.id);
423
551
  continue;
424
552
  }
553
+ await this.applyEventThrottle();
425
554
  try {
426
555
  await this.processWorkflowEvent(event);
427
556
  await this.reliability.markEventProcessed(event.eventId);
@@ -434,7 +563,7 @@ class WorkflowManager {
434
563
  }
435
564
  catch (err) {
436
565
  console.error(`Error processing event ${event.eventId}:`, err);
437
- this.reliability.recordCircuitBreakerFailure();
566
+ await this.reliability.recordCircuitBreakerFailure();
438
567
  const retryKey = this.keys.eventRetryCount(event.eventId);
439
568
  const retryCount = Number(await this.redisClient.get(retryKey)) || 0;
440
569
  if (retryCount >= this.reliability.options.workflowMaxRetries) {
@@ -442,8 +571,12 @@ class WorkflowManager {
442
571
  await client.xAck(streamKey, this.options.streamConsumerGroup, message.id);
443
572
  }
444
573
  else {
445
- await this.redisClient.incr(retryKey);
574
+ const nextRetryCount = Number(await this.redisClient.incr(retryKey));
446
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);
447
580
  }
448
581
  }
449
582
  }
@@ -452,9 +585,27 @@ class WorkflowManager {
452
585
  catch (err) {
453
586
  if (this.orchestratorAbortController?.signal.aborted)
454
587
  break;
588
+ if (this.isNoGroupError(err)) {
589
+ await this.initStreamConsumerGroup();
590
+ continue;
591
+ }
455
592
  console.error('Orchestrator read error:', err);
456
- this.reliability.recordCircuitBreakerFailure();
457
- 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);
458
609
  }
459
610
  }
460
611
  }
@@ -485,26 +636,39 @@ class WorkflowManager {
485
636
  'workflow.step_id': event.stepId ?? '',
486
637
  });
487
638
  try {
488
- const instance = await this.getWorkflowInstance(event.workflowInstanceId);
489
- if (!instance || instance.status !== 'active') {
490
- endSpan();
491
- return;
492
- }
493
- const definition = instance.definitionSnapshot ?? await this.getWorkflowDefinition(instance.workflowDefinitionId);
494
- if (!definition) {
495
- endSpan();
496
- return;
497
- }
498
- switch (event.type) {
499
- case 'COMPLETED':
500
- 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') {
501
643
  break;
502
- case 'FAILED':
503
- await this.handleStepFailure(instance, definition, event);
644
+ }
645
+ const definition = instance.definitionSnapshot ?? (await this.getWorkflowDefinition(instance.workflowDefinitionId));
646
+ if (!definition) {
504
647
  break;
505
- case 'EXPIRED':
506
- 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
+ }
507
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
+ }
508
672
  }
509
673
  endSpan();
510
674
  }
@@ -644,14 +808,21 @@ class WorkflowManager {
644
808
  expectedValue = valueStr;
645
809
  switch (operator) {
646
810
  case '==':
647
- case '===': return actualValue === expectedValue;
811
+ case '===':
812
+ return actualValue === expectedValue;
648
813
  case '!=':
649
- case '!==': return actualValue !== expectedValue;
650
- case '>': return actualValue > expectedValue;
651
- case '<': return actualValue < expectedValue;
652
- case '>=': return actualValue >= expectedValue;
653
- case '<=': return actualValue <= expectedValue;
654
- 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;
655
826
  }
656
827
  }
657
828
  catch {
@@ -702,6 +873,10 @@ class WorkflowManager {
702
873
  }
703
874
  }
704
875
  catch (err) {
876
+ if (this.isNoGroupError(err)) {
877
+ await this.initStreamConsumerGroup();
878
+ return 0;
879
+ }
705
880
  console.error('Error in XAUTOCLAIM:', err);
706
881
  }
707
882
  return totalReclaimed;
@@ -712,10 +887,10 @@ class WorkflowManager {
712
887
  instance.updatedAt = Date.now();
713
888
  const newData = JSON.stringify(instance);
714
889
  if (this.luaScriptSha) {
715
- const result = await this.redisClient.evalSha(this.luaScriptSha, {
890
+ const result = (await this.redisClient.evalSha(this.luaScriptSha, {
716
891
  keys: [instanceKey],
717
892
  arguments: [String(expectedVersion), newData],
718
- });
893
+ }));
719
894
  const parsed = JSON.parse(result);
720
895
  if (parsed.err) {
721
896
  throw new Error(`Workflow transition failed: ${parsed.err}`);
@@ -724,6 +899,203 @@ class WorkflowManager {
724
899
  else {
725
900
  await this.redisClient.hSet(instanceKey, 'data', newData);
726
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
+ };
727
1099
  }
728
1100
  async atomicWorkflowTransition(instanceId, expectedVersion, newStatus, newStepId, updatedContext, historyEntry) {
729
1101
  const instance = await this.getWorkflowInstance(instanceId);