assignment-user-matcher 1.1.2 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/index.d.ts +4 -0
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +26 -1
  4. package/dist/managers/ReliabilityManager.d.ts +42 -0
  5. package/dist/managers/ReliabilityManager.d.ts.map +1 -0
  6. package/dist/managers/ReliabilityManager.js +115 -0
  7. package/dist/managers/TelemetryManager.d.ts +13 -0
  8. package/dist/managers/TelemetryManager.d.ts.map +1 -0
  9. package/dist/managers/TelemetryManager.js +52 -0
  10. package/dist/managers/WorkflowManager.d.ts +62 -0
  11. package/dist/managers/WorkflowManager.d.ts.map +1 -0
  12. package/dist/managers/WorkflowManager.js +654 -0
  13. package/dist/matcher.class.d.ts +161 -51
  14. package/dist/matcher.class.d.ts.map +1 -1
  15. package/dist/matcher.class.js +472 -254
  16. package/dist/queries/index.d.ts +5 -0
  17. package/dist/queries/index.d.ts.map +1 -0
  18. package/dist/queries/index.js +20 -0
  19. package/dist/queries/pagination.d.ts +51 -0
  20. package/dist/queries/pagination.d.ts.map +1 -0
  21. package/dist/queries/pagination.js +200 -0
  22. package/dist/scoring/index.d.ts +5 -0
  23. package/dist/scoring/index.d.ts.map +1 -0
  24. package/dist/scoring/index.js +20 -0
  25. package/dist/scoring/match-score.d.ts +19 -0
  26. package/dist/scoring/match-score.d.ts.map +1 -0
  27. package/dist/scoring/match-score.js +84 -0
  28. package/dist/types/matcher.d.ts +261 -0
  29. package/dist/types/matcher.d.ts.map +1 -0
  30. package/dist/types/matcher.js +2 -0
  31. package/dist/utils/cidr.d.ts +40 -0
  32. package/dist/utils/cidr.d.ts.map +1 -0
  33. package/dist/utils/cidr.js +150 -0
  34. package/dist/utils/index.d.ts +6 -0
  35. package/dist/utils/index.d.ts.map +1 -0
  36. package/dist/utils/index.js +21 -0
  37. package/dist/utils/keys.d.ts +45 -0
  38. package/dist/utils/keys.d.ts.map +1 -0
  39. package/dist/utils/keys.js +57 -0
  40. package/dist/workflow-builder.d.ts +182 -0
  41. package/dist/workflow-builder.d.ts.map +1 -0
  42. package/dist/workflow-builder.js +341 -0
  43. package/package.json +6 -2
@@ -0,0 +1,654 @@
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
+ for (const parallelStepId of step.parallelStepIds) {
159
+ const parallelStep = definition.steps.find((s) => s.id === parallelStepId);
160
+ if (!parallelStep)
161
+ continue;
162
+ const assignment = await this.createWorkflowAssignment(instance, parallelStep, definition);
163
+ branches.push({
164
+ stepId: parallelStepId,
165
+ assignmentId: assignment.id,
166
+ status: 'pending',
167
+ });
168
+ if (parallelStep.timeoutMs) {
169
+ await this.setStepTimeout(instance.id, parallelStepId, parallelStep.timeoutMs);
170
+ }
171
+ }
172
+ instance.parallelBranches = branches;
173
+ instance.currentStepId = null;
174
+ }
175
+ else {
176
+ const assignment = await this.createWorkflowAssignment(instance, step, definition);
177
+ instance.currentAssignmentId = assignment.id;
178
+ instance.currentStepId = stepId;
179
+ if (step.timeoutMs) {
180
+ await this.setStepTimeout(instance.id, stepId, step.timeoutMs);
181
+ }
182
+ }
183
+ await this.saveInstance(instance, expectedVersion);
184
+ }
185
+ async setStepTimeout(instanceId, stepId, timeoutMs) {
186
+ const expiryKey = this.keys.workflowStepExpiry(instanceId, stepId);
187
+ const expiryTime = Date.now() + timeoutMs;
188
+ await this.redisClient.set(expiryKey, String(expiryTime), { PX: timeoutMs });
189
+ }
190
+ async processExpiredWorkflowSteps() {
191
+ if (!this.options.enableWorkflows)
192
+ return 0;
193
+ const instances = await this.redisClient.hGetAll(this.keys.workflowInstances());
194
+ let expiredCount = 0;
195
+ for (const [instanceId] of Object.entries(instances)) {
196
+ const instance = await this.getWorkflowInstance(instanceId);
197
+ if (!instance || instance.status !== 'active')
198
+ continue;
199
+ const currentStepId = instance.currentStepId;
200
+ if (!currentStepId)
201
+ continue;
202
+ const expiryKey = this.keys.workflowStepExpiry(instanceId, currentStepId);
203
+ const expiryTimeStr = await this.redisClient.get(expiryKey);
204
+ if (expiryTimeStr === null) {
205
+ const definition = await this.getWorkflowDefinition(instance.workflowDefinitionId);
206
+ if (!definition)
207
+ continue;
208
+ const step = definition.steps.find((s) => s.id === currentStepId);
209
+ if (!step?.timeoutMs)
210
+ continue;
211
+ await this.publishWorkflowEvent({
212
+ eventId: (0, crypto_1.randomUUID)(),
213
+ type: 'EXPIRED',
214
+ userId: instance.initiatorUserId,
215
+ assignmentId: instance.currentAssignmentId ?? '',
216
+ workflowInstanceId: instanceId,
217
+ stepId: currentStepId,
218
+ timestamp: Date.now(),
219
+ });
220
+ expiredCount++;
221
+ }
222
+ }
223
+ return expiredCount;
224
+ }
225
+ async createWorkflowAssignment(instance, step, definition) {
226
+ let targetUserId;
227
+ if (step.targetUser === 'initiator') {
228
+ targetUserId = instance.initiatorUserId;
229
+ }
230
+ else if (step.targetUser === 'previous') {
231
+ const lastEntry = instance.history[instance.history.length - 1];
232
+ targetUserId = lastEntry?.userId ?? instance.initiatorUserId;
233
+ }
234
+ else if (typeof step.targetUser === 'object' && 'tag' in step.targetUser) {
235
+ targetUserId = '';
236
+ }
237
+ else {
238
+ targetUserId = step.targetUser;
239
+ }
240
+ const assignmentId = (0, crypto_1.randomUUID)();
241
+ const assignment = {
242
+ id: assignmentId,
243
+ tags: step.assignmentTemplate.tags ?? ['workflow'],
244
+ priority: step.assignmentTemplate.priority ?? 1000,
245
+ ...step.assignmentTemplate,
246
+ _workflowInstanceId: instance.id,
247
+ _workflowStepId: step.id,
248
+ _workflowContext: instance.context,
249
+ _targetUserId: targetUserId || undefined,
250
+ };
251
+ await this.host.addAssignment(assignment);
252
+ await this.redisClient.set(this.keys.workflowAssignmentLink(assignmentId), JSON.stringify({
253
+ instanceId: instance.id,
254
+ stepId: step.id,
255
+ definitionId: definition.id,
256
+ }));
257
+ if (targetUserId) {
258
+ await this.host.matchUsersAssignments(targetUserId);
259
+ }
260
+ return assignment;
261
+ }
262
+ async publishWorkflowEvent(event) {
263
+ const streamKey = this.keys.eventStream();
264
+ if (!event.workflowInstanceId && event.assignmentId) {
265
+ const linkJson = await this.redisClient.get(this.keys.workflowAssignmentLink(event.assignmentId));
266
+ if (linkJson) {
267
+ const link = JSON.parse(linkJson);
268
+ event.workflowInstanceId = link.instanceId;
269
+ event.stepId = link.stepId;
270
+ }
271
+ }
272
+ const messageId = await this.redisClient.xAdd(streamKey, '*', {
273
+ eventId: event.eventId,
274
+ type: event.type,
275
+ userId: event.userId,
276
+ assignmentId: event.assignmentId,
277
+ workflowInstanceId: event.workflowInstanceId ?? '',
278
+ stepId: event.stepId ?? '',
279
+ timestamp: String(event.timestamp),
280
+ payload: event.payload ? JSON.stringify(event.payload) : '',
281
+ });
282
+ return messageId;
283
+ }
284
+ async startOrchestrator() {
285
+ if (!this.options.enableWorkflows) {
286
+ throw new Error('Workflows are not enabled. Set enableWorkflows: true in options.');
287
+ }
288
+ if (this.orchestratorRunning)
289
+ return;
290
+ this.orchestratorRunning = true;
291
+ this.orchestratorAbortController = new AbortController();
292
+ this.subscriberClient = this.redisClient.duplicate();
293
+ await this.subscriberClient.connect();
294
+ this.orchestratorLoop().catch((err) => {
295
+ if (!this.orchestratorAbortController?.signal.aborted) {
296
+ console.error('Orchestrator error:', err);
297
+ }
298
+ });
299
+ }
300
+ async stopOrchestrator() {
301
+ this.orchestratorRunning = false;
302
+ this.orchestratorAbortController?.abort();
303
+ if (this.subscriberClient?.isOpen) {
304
+ await this.subscriberClient.quit();
305
+ this.subscriberClient = null;
306
+ }
307
+ }
308
+ async orchestratorLoop() {
309
+ const streamKey = this.keys.eventStream();
310
+ const client = this.subscriberClient;
311
+ const reclaimIntervalHandle = setInterval(async () => {
312
+ try {
313
+ await this.reclaimOrphanedMessages();
314
+ }
315
+ catch (err) {
316
+ console.error('Error reclaiming orphaned messages:', err);
317
+ }
318
+ }, this.options.reclaimIntervalMs);
319
+ try {
320
+ while (this.orchestratorRunning) {
321
+ try {
322
+ if (!this.reliability.shouldProcessCircuitBreaker()) {
323
+ await new Promise((r) => setTimeout(r, 5000));
324
+ continue;
325
+ }
326
+ const response = await client.xReadGroup(this.options.streamConsumerGroup, this.options.streamConsumerName, [{ key: streamKey, id: '>' }], { COUNT: 10, BLOCK: 5000 });
327
+ if (!response)
328
+ continue;
329
+ for (const stream of response) {
330
+ for (const message of stream.messages) {
331
+ const event = this.parseStreamMessage(message);
332
+ if (await this.reliability.isEventProcessed(event.eventId)) {
333
+ await client.xAck(streamKey, this.options.streamConsumerGroup, message.id);
334
+ continue;
335
+ }
336
+ try {
337
+ await this.processWorkflowEvent(event);
338
+ await this.reliability.markEventProcessed(event.eventId);
339
+ await client.xAck(streamKey, this.options.streamConsumerGroup, message.id);
340
+ this.reliability.recordCircuitBreakerSuccess();
341
+ await this.reliability.emitAuditEvent('EVENT_PROCESSED', event.eventId, {
342
+ type: event.type,
343
+ workflowInstanceId: event.workflowInstanceId,
344
+ }, 'event');
345
+ }
346
+ catch (err) {
347
+ console.error(`Error processing event ${event.eventId}:`, err);
348
+ this.reliability.recordCircuitBreakerFailure();
349
+ const retryKey = this.keys.eventRetryCount(event.eventId);
350
+ const retryCount = Number(await this.redisClient.get(retryKey)) || 0;
351
+ if (retryCount >= this.reliability.options.workflowMaxRetries) {
352
+ await this.reliability.moveToDeadLetter(event, 'Processing failed after max retries', err instanceof Error ? err : new Error(String(err)));
353
+ await client.xAck(streamKey, this.options.streamConsumerGroup, message.id);
354
+ }
355
+ else {
356
+ await this.redisClient.incr(retryKey);
357
+ await this.redisClient.expire(retryKey, 86400);
358
+ }
359
+ }
360
+ }
361
+ }
362
+ }
363
+ catch (err) {
364
+ if (this.orchestratorAbortController?.signal.aborted)
365
+ break;
366
+ console.error('Orchestrator read error:', err);
367
+ this.reliability.recordCircuitBreakerFailure();
368
+ await new Promise((r) => setTimeout(r, 1000));
369
+ }
370
+ }
371
+ }
372
+ finally {
373
+ clearInterval(reclaimIntervalHandle);
374
+ }
375
+ }
376
+ parseStreamMessage(message) {
377
+ const m = message.message;
378
+ return {
379
+ eventId: m.eventId,
380
+ type: m.type,
381
+ userId: m.userId,
382
+ assignmentId: m.assignmentId,
383
+ workflowInstanceId: m.workflowInstanceId || undefined,
384
+ stepId: m.stepId || undefined,
385
+ timestamp: Number(m.timestamp),
386
+ payload: m.payload ? JSON.parse(m.payload) : undefined,
387
+ };
388
+ }
389
+ async processWorkflowEvent(event) {
390
+ if (!event.workflowInstanceId)
391
+ return;
392
+ const { span, end: endSpan } = this.telemetry.startSpan('workflow.process_event', {
393
+ 'workflow.event_type': event.type,
394
+ 'workflow.event_id': event.eventId,
395
+ 'workflow.instance_id': event.workflowInstanceId,
396
+ 'workflow.step_id': event.stepId ?? '',
397
+ });
398
+ try {
399
+ const instance = await this.getWorkflowInstance(event.workflowInstanceId);
400
+ if (!instance || instance.status !== 'active') {
401
+ endSpan();
402
+ return;
403
+ }
404
+ const definition = instance.definitionSnapshot ?? await this.getWorkflowDefinition(instance.workflowDefinitionId);
405
+ if (!definition) {
406
+ endSpan();
407
+ return;
408
+ }
409
+ switch (event.type) {
410
+ case 'COMPLETED':
411
+ await this.handleStepCompletion(instance, definition, event);
412
+ break;
413
+ case 'FAILED':
414
+ await this.handleStepFailure(instance, definition, event);
415
+ break;
416
+ case 'EXPIRED':
417
+ await this.handleStepExpiry(instance, definition, event);
418
+ break;
419
+ }
420
+ endSpan();
421
+ }
422
+ catch (err) {
423
+ this.telemetry.recordSpanError(span, err instanceof Error ? err : new Error(String(err)));
424
+ endSpan();
425
+ throw err;
426
+ }
427
+ }
428
+ async handleStepCompletion(instance, definition, event) {
429
+ const stepId = event.stepId;
430
+ if (!stepId)
431
+ return;
432
+ const step = definition.steps.find((s) => s.id === stepId);
433
+ if (!step)
434
+ return;
435
+ instance.history.push({
436
+ stepId,
437
+ assignmentId: event.assignmentId,
438
+ userId: event.userId,
439
+ completedAt: event.timestamp,
440
+ result: event.payload,
441
+ });
442
+ if (event.payload) {
443
+ instance.context = { ...instance.context, [`step_${stepId}`]: event.payload };
444
+ }
445
+ const expectedVersion = instance.version;
446
+ if (instance.parallelBranches) {
447
+ const branch = instance.parallelBranches.find((b) => b.stepId === stepId);
448
+ if (branch) {
449
+ branch.status = 'completed';
450
+ branch.result = event.payload;
451
+ const allComplete = instance.parallelBranches.every((b) => b.status === 'completed');
452
+ if (!allComplete && step.waitForAll !== false) {
453
+ await this.saveInstance(instance, expectedVersion);
454
+ return;
455
+ }
456
+ instance.parallelBranches = undefined;
457
+ }
458
+ }
459
+ let nextStepId = null;
460
+ if (step.routing && step.routing.length > 0) {
461
+ for (const route of step.routing) {
462
+ if (this.evaluateCondition(route.condition, event.payload, instance.context)) {
463
+ nextStepId = route.targetStepId;
464
+ break;
465
+ }
466
+ }
467
+ }
468
+ if (!nextStepId && step.defaultNextStepId !== undefined) {
469
+ nextStepId = step.defaultNextStepId;
470
+ }
471
+ if (nextStepId) {
472
+ instance.currentStepId = nextStepId;
473
+ instance.currentAssignmentId = undefined;
474
+ await this.executeWorkflowStep(instance, nextStepId, definition);
475
+ }
476
+ else {
477
+ instance.status = 'completed';
478
+ instance.currentStepId = null;
479
+ instance.currentAssignmentId = undefined;
480
+ await this.saveInstance(instance, expectedVersion);
481
+ }
482
+ }
483
+ async handleStepFailure(instance, definition, event) {
484
+ const stepId = event.stepId;
485
+ if (!stepId)
486
+ return;
487
+ const step = definition.steps.find((s) => s.id === stepId);
488
+ if (!step)
489
+ return;
490
+ const maxRetries = step.maxRetries ?? 0;
491
+ const expectedVersion = instance.version;
492
+ // Handle parallel branch failure
493
+ if (instance.parallelBranches) {
494
+ const branch = instance.parallelBranches.find((b) => b.stepId === stepId);
495
+ if (branch) {
496
+ branch.status = 'failed';
497
+ const policy = step.failurePolicy ?? 'abort';
498
+ if (policy === 'abort') {
499
+ // Fail entire workflow
500
+ instance.status = 'failed';
501
+ await this.saveInstance(instance, expectedVersion);
502
+ return;
503
+ }
504
+ else if (policy === 'continue') {
505
+ // Check if remaining branches can complete
506
+ const allDone = instance.parallelBranches.every((b) => b.status === 'completed' || b.status === 'failed');
507
+ if (allDone) {
508
+ // Proceed with partial results
509
+ await this.handleStepCompletion(instance, definition, {
510
+ ...event,
511
+ type: 'COMPLETED',
512
+ });
513
+ }
514
+ return;
515
+ }
516
+ }
517
+ }
518
+ // Retry logic
519
+ if (instance.retryCount < maxRetries) {
520
+ instance.retryCount += 1;
521
+ await this.executeWorkflowStep(instance, stepId, definition);
522
+ }
523
+ else {
524
+ // Workflow failed
525
+ instance.status = 'failed';
526
+ await this.saveInstance(instance, expectedVersion);
527
+ }
528
+ }
529
+ async handleStepExpiry(instance, definition, event) {
530
+ await this.handleStepFailure(instance, definition, event);
531
+ }
532
+ evaluateCondition(condition, result, context) {
533
+ try {
534
+ const match = condition.match(/^(result|context)\.(\w+)\s*(===|!==|==|!=|>=|<=|>|<)\s*(.+)$/);
535
+ if (!match)
536
+ return false;
537
+ const [, source, field, operator, valueStr] = match;
538
+ const sourceObj = source === 'result' ? result : context;
539
+ const actualValue = sourceObj?.[field];
540
+ let expectedValue;
541
+ if (valueStr === 'true')
542
+ expectedValue = true;
543
+ else if (valueStr === 'false')
544
+ expectedValue = false;
545
+ else if (valueStr === 'null')
546
+ expectedValue = null;
547
+ else if (/^['"].*['"]$/.test(valueStr))
548
+ expectedValue = valueStr.slice(1, -1);
549
+ else if (!isNaN(Number(valueStr)))
550
+ expectedValue = Number(valueStr);
551
+ else
552
+ expectedValue = valueStr;
553
+ switch (operator) {
554
+ case '==':
555
+ case '===': return actualValue === expectedValue;
556
+ case '!=':
557
+ case '!==': return actualValue !== expectedValue;
558
+ case '>': return actualValue > expectedValue;
559
+ case '<': return actualValue < expectedValue;
560
+ case '>=': return actualValue >= expectedValue;
561
+ case '<=': return actualValue <= expectedValue;
562
+ default: return false;
563
+ }
564
+ }
565
+ catch {
566
+ return false;
567
+ }
568
+ }
569
+ async reclaimOrphanedMessages() {
570
+ if (!this.subscriberClient?.isOpen)
571
+ return 0;
572
+ const streamKey = this.keys.eventStream();
573
+ let totalReclaimed = 0;
574
+ try {
575
+ const result = await this.subscriberClient.xAutoClaim(streamKey, this.options.streamConsumerGroup, this.options.streamConsumerName, this.options.reclaimIntervalMs, '0-0', { COUNT: 100 });
576
+ if (result && result.messages && result.messages.length > 0) {
577
+ for (const message of result.messages) {
578
+ if (!message)
579
+ continue;
580
+ const event = this.parseStreamMessage(message);
581
+ try {
582
+ if (await this.reliability.isEventProcessed(event.eventId)) {
583
+ await this.subscriberClient.xAck(streamKey, this.options.streamConsumerGroup, message.id);
584
+ continue;
585
+ }
586
+ const retryKey = this.keys.eventRetryCount(event.eventId);
587
+ const retryCount = Number(await this.redisClient.get(retryKey)) || 0;
588
+ if (retryCount >= this.reliability.options.workflowMaxRetries) {
589
+ await this.reliability.moveToDeadLetter(event, 'Max retries exceeded');
590
+ await this.subscriberClient.xAck(streamKey, this.options.streamConsumerGroup, message.id);
591
+ }
592
+ else {
593
+ try {
594
+ await this.processWorkflowEvent(event);
595
+ await this.reliability.markEventProcessed(event.eventId);
596
+ await this.subscriberClient.xAck(streamKey, this.options.streamConsumerGroup, message.id);
597
+ totalReclaimed++;
598
+ }
599
+ catch (err) {
600
+ await this.redisClient.incr(retryKey);
601
+ await this.redisClient.expire(retryKey, 86400);
602
+ throw err;
603
+ }
604
+ }
605
+ }
606
+ catch (err) {
607
+ console.error(`Error processing reclaimed message ${message.id}:`, err);
608
+ }
609
+ }
610
+ }
611
+ }
612
+ catch (err) {
613
+ console.error('Error in XAUTOCLAIM:', err);
614
+ }
615
+ return totalReclaimed;
616
+ }
617
+ async saveInstance(instance, expectedVersion) {
618
+ const instanceKey = this.keys.workflowInstance(instance.id);
619
+ instance.version += 1;
620
+ instance.updatedAt = Date.now();
621
+ const newData = JSON.stringify(instance);
622
+ if (this.luaScriptSha) {
623
+ const result = await this.redisClient.evalSha(this.luaScriptSha, {
624
+ keys: [instanceKey],
625
+ arguments: [String(expectedVersion), newData],
626
+ });
627
+ const parsed = JSON.parse(result);
628
+ if (parsed.err) {
629
+ throw new Error(`Workflow transition failed: ${parsed.err}`);
630
+ }
631
+ }
632
+ else {
633
+ await this.redisClient.hSet(instanceKey, 'data', newData);
634
+ }
635
+ }
636
+ async atomicWorkflowTransition(instanceId, expectedVersion, newStatus, newStepId, updatedContext, historyEntry) {
637
+ const instance = await this.getWorkflowInstance(instanceId);
638
+ if (!instance)
639
+ return { ok: false, error: 'Instance not found' };
640
+ instance.status = newStatus;
641
+ instance.currentStepId = newStepId;
642
+ instance.context = { ...instance.context, ...updatedContext };
643
+ if (historyEntry)
644
+ instance.history.push(historyEntry);
645
+ try {
646
+ await this.saveInstance(instance, expectedVersion);
647
+ return { ok: true, instance };
648
+ }
649
+ catch (err) {
650
+ return { ok: false, error: err.message };
651
+ }
652
+ }
653
+ }
654
+ exports.WorkflowManager = WorkflowManager;