assignment-user-matcher 1.1.6 → 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 +142 -77
  14. package/dist/matcher.class.d.ts.map +1 -1
  15. package/dist/matcher.class.js +437 -438
  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 +1 -1
@@ -1,33 +1,185 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ const crypto_1 = require("crypto");
4
+ const fs_1 = require("fs");
5
+ const path_1 = require("path");
6
+ const cidr_1 = require("./utils/cidr");
7
+ const keys_1 = require("./utils/keys");
8
+ const pagination_1 = require("./queries/pagination");
9
+ const match_score_1 = require("./scoring/match-score");
10
+ const ReliabilityManager_1 = require("./managers/ReliabilityManager");
11
+ const TelemetryManager_1 = require("./managers/TelemetryManager");
12
+ const WorkflowManager_1 = require("./managers/WorkflowManager");
13
+ // Load Lua scripts from files
14
+ const LUA_SCRIPTS_DIR = (0, path_1.join)(__dirname, 'lua');
15
+ /**
16
+ * Load a Lua script from the lua directory.
17
+ * Falls back to empty string if file not found.
18
+ */
19
+ function loadLuaScript(filename) {
20
+ try {
21
+ return (0, fs_1.readFileSync)((0, path_1.join)(LUA_SCRIPTS_DIR, filename), 'utf-8');
22
+ }
23
+ catch {
24
+ console.warn(`Lua script not found: ${filename}`);
25
+ return '';
26
+ }
27
+ }
28
+ // Lua script for atomic workflow transitions
29
+ const WORKFLOW_TRANSITION_LUA = loadLuaScript('workflow-transition.lua');
3
30
  class AssignmentMatcher {
4
31
  constructor(redisClient, options) {
5
32
  this.redisClient = redisClient;
33
+ this.luaScriptSha = null;
6
34
  this.autoReleaseInterval = null;
7
35
  this.relevantBatchSize = options?.relevantBatchSize ?? 50;
8
36
  this.enableDefaultMatching = options?.enableDefaultMatching ?? true;
9
37
  this.redisPrefix = options?.redisPrefix ?? '';
10
- this.usersKey = this.redisPrefix + 'users';
11
- this.assignmentsKey = this.redisPrefix + 'assignments';
12
- this.assignmentsRefKey = this.redisPrefix + 'assignments:ref';
38
+ // Initialize key builders
39
+ this.keys = (0, keys_1.createKeyBuilders)({ prefix: this.redisPrefix });
40
+ this.usersKey = this.keys.users();
41
+ this.assignmentsKey = this.keys.assignments();
42
+ this.assignmentsRefKey = this.keys.assignmentsRef();
13
43
  this.maxUserBacklogSize = options?.maxUserBacklogSize ?? 9;
14
44
  this.matchExpirationMs = options?.matchExpirationMs ?? 60000;
15
- this.pendingAssignmentsKey = this.redisPrefix + 'assignments:pending:data';
16
- this.pendingAssignmentsExpiryKey = this.redisPrefix + 'assignments:pending:expiry';
17
- this.assignmentOwnerKey = this.redisPrefix + 'assignments:pending:owner';
18
- this.allTagsKey = this.redisPrefix + 'all:tags';
19
- this.acceptedAssignmentsKey = this.redisPrefix + 'assignments:accepted';
45
+ this.pendingAssignmentsKey = this.keys.pendingAssignmentsData();
46
+ this.pendingAssignmentsExpiryKey = this.keys.pendingAssignmentsExpiry();
47
+ this.assignmentOwnerKey = this.keys.assignmentOwner();
48
+ this.allTagsKey = this.keys.allTags();
49
+ this.acceptedAssignmentsKey = this.keys.acceptedAssignments();
50
+ this.completedAssignmentsKey = this.keys.completedAssignments();
20
51
  this.calculatePriority = options?.prioritizationFunction ?? this.calculatePriority;
21
- this.matchScore = options?.matchingFunction ?? this.matchScore;
52
+ this.matchScore = options?.matchingFunction ?? this.defaultMatchScore.bind(this);
53
+ // Workflow options
54
+ this.enableWorkflows = options?.enableWorkflows ?? false;
55
+ this.streamConsumerGroup = options?.streamConsumerGroup ?? 'orchestrator';
56
+ this.streamConsumerName = options?.streamConsumerName ?? (0, crypto_1.randomUUID)();
57
+ // Initialize managers
58
+ this.reliability = new ReliabilityManager_1.ReliabilityManager(this.redisClient, this.keys, {
59
+ workflowMaxRetries: options?.workflowMaxRetries ?? 3,
60
+ workflowIdempotencyTtlMs: options?.workflowIdempotencyTtlMs ?? 86400000,
61
+ workflowCircuitBreakerThreshold: options?.workflowCircuitBreakerThreshold ?? 5,
62
+ workflowCircuitBreakerResetMs: options?.workflowCircuitBreakerResetMs ?? 30000,
63
+ workflowAuditEnabled: options?.workflowAuditEnabled ?? false,
64
+ workflowSnapshotDefinitions: options?.workflowSnapshotDefinitions ?? true,
65
+ streamConsumerName: this.streamConsumerName,
66
+ });
67
+ this.telemetry = new TelemetryManager_1.TelemetryManager(options?.enableOpenTelemetry ?? false);
68
+ this.workflow = new WorkflowManager_1.WorkflowManager(this.redisClient, this.keys, this.reliability, this.telemetry, this, {
69
+ enableWorkflows: this.enableWorkflows,
70
+ streamConsumerGroup: this.streamConsumerGroup,
71
+ streamConsumerName: this.streamConsumerName,
72
+ reclaimIntervalMs: options?.workflowOrphanReclaimMs ?? 60000,
73
+ });
22
74
  this.initRedis();
23
75
  }
76
+ /** Keys for the three assignment stores (used by pagination queries) */
77
+ get assignmentStoreKeys() {
78
+ return {
79
+ queued: this.assignmentsRefKey,
80
+ pending: this.pendingAssignmentsKey,
81
+ accepted: this.acceptedAssignmentsKey,
82
+ completed: this.completedAssignmentsKey,
83
+ };
84
+ }
24
85
  async initRedis() {
25
86
  // Only attempt to connect if the client isn't already connected
26
87
  if (!this.redisClient.isOpen) {
27
88
  await this.redisClient.connect();
28
89
  }
90
+ // Initialize workflow stream consumer group if workflows are enabled
91
+ if (this.enableWorkflows) {
92
+ await this.workflow.init();
93
+ // Load Lua script for atomic transitions
94
+ await this.loadLuaScripts();
95
+ }
29
96
  return this;
30
97
  }
98
+ /**
99
+ * Load Lua scripts into Redis for atomic operations.
100
+ */
101
+ async loadLuaScripts() {
102
+ try {
103
+ this.luaScriptSha = await this.redisClient.scriptLoad(WORKFLOW_TRANSITION_LUA);
104
+ this.workflow.setLuaScriptSha(this.luaScriptSha);
105
+ }
106
+ catch (err) {
107
+ console.error('Failed to load Lua scripts:', err);
108
+ // Fallback to non-atomic mode
109
+ this.luaScriptSha = null;
110
+ }
111
+ }
112
+ async atomicWorkflowTransition(instanceId, expectedVersion, newStatus, newStepId, updatedContext, historyEntry) {
113
+ return this.workflow.atomicWorkflowTransition(instanceId, expectedVersion, newStatus, newStepId, updatedContext, historyEntry);
114
+ }
115
+ async reclaimOrphanedMessages() {
116
+ return this.workflow.reclaimOrphanedMessages();
117
+ }
118
+ /**
119
+ * Get events from the Dead Letter Queue.
120
+ */
121
+ async getDeadLetterEvents(limit = 100, offset = 0) {
122
+ return this.reliability.getDeadLetterEvents(limit, offset);
123
+ }
124
+ /**
125
+ * Get Dead Letter Queue size.
126
+ */
127
+ async getDeadLetterQueueSize() {
128
+ return this.reliability.getDeadLetterQueueSize();
129
+ }
130
+ /**
131
+ * Replay a Dead Letter Queue event.
132
+ */
133
+ async replayDeadLetterEvent(eventJson) {
134
+ const entry = JSON.parse(eventJson);
135
+ // Reset retry count
136
+ await this.redisClient.del(this.keys.eventRetryCount(entry.event.eventId));
137
+ // Re-publish the event
138
+ await this.publishWorkflowEvent(entry.event);
139
+ // Remove from DLQ
140
+ await this.redisClient.zRem(this.keys.deadLetterQueue(), eventJson);
141
+ return true;
142
+ }
143
+ /**
144
+ * Clear all events from the Dead Letter Queue.
145
+ */
146
+ async clearDeadLetterQueue() {
147
+ return this.reliability.clearDeadLetterQueue();
148
+ }
149
+ /**
150
+ * Get audit events from the audit stream.
151
+ */
152
+ async getAuditEvents(count = 100) {
153
+ return this.reliability.getAuditEvents(count);
154
+ }
155
+ // ============================================================================
156
+ // OpenTelemetry Tracing Hooks
157
+ // ============================================================================
158
+ /**
159
+ * Set the OpenTelemetry tracer instance.
160
+ */
161
+ setTracer(tracer) {
162
+ this.telemetry.setTracer(tracer);
163
+ }
164
+ /**
165
+ * Initialize the Redis Stream consumer group for workflow events.
166
+ * Creates the stream and consumer group if they don't exist.
167
+ */
168
+ async initStreamConsumerGroup() {
169
+ const streamKey = this.keys.eventStream();
170
+ try {
171
+ // Try to create the consumer group (and stream if needed)
172
+ await this.redisClient.xGroupCreate(streamKey, this.streamConsumerGroup, '0', {
173
+ MKSTREAM: true,
174
+ });
175
+ }
176
+ catch (err) {
177
+ // Ignore "BUSYGROUP" error - group already exists
178
+ if (!err.message?.includes('BUSYGROUP')) {
179
+ throw err;
180
+ }
181
+ }
182
+ }
31
183
  async addUser(user) {
32
184
  await this.redisClient.hSet(this.usersKey, user.id, JSON.stringify({
33
185
  ...user,
@@ -39,9 +191,9 @@ class AssignmentMatcher {
39
191
  let { id, tags, priority, latitude, longitude } = assignment;
40
192
  if (!priority)
41
193
  priority = await this.calculatePriority(assignment);
42
- const assignmentPriorityKey = this.redisPrefix + `assignment:${id}:priority`;
43
- const assignmentTagsKey = this.redisPrefix + `assignment:${id}:tags`;
44
- const assignmentGeoKey = this.redisPrefix + `assignments:geo`;
194
+ const assignmentPriorityKey = this.keys.assignmentPriority(id);
195
+ const assignmentTagsKey = this.keys.assignmentTags(id);
196
+ const assignmentGeoKey = this.keys.assignmentsGeo();
45
197
  const multi = this.redisClient
46
198
  .multi()
47
199
  .hSet(this.assignmentsRefKey, id, JSON.stringify(assignment))
@@ -63,7 +215,7 @@ class AssignmentMatcher {
63
215
  // This enables efficient weighted matching via ZUNIONSTORE.
64
216
  const indexTags = [...tags, ...(this.enableDefaultMatching ? ['default'] : [])];
65
217
  for (const tag of indexTags) {
66
- multi.zAdd(this.redisPrefix + `tag:${tag}:assignments`, {
218
+ multi.zAdd(this.keys.tagAssignments(tag), {
67
219
  score: Number(priority),
68
220
  value: id,
69
221
  });
@@ -73,33 +225,45 @@ class AssignmentMatcher {
73
225
  return assignment;
74
226
  }
75
227
  async removeAssignment(id) {
76
- const assignmentPriorityKey = this.redisPrefix + `assignment:${id}:priority`;
77
- const assignmentTagsKey = this.redisPrefix + `assignment:${id}:tags`;
78
- // Fetch tags to remove from per-tag indices
79
- const [tagsCsv] = await this.redisClient.multi().hGet(assignmentTagsKey, 'tags').exec();
228
+ const assignmentPriorityKey = this.keys.assignmentPriority(id);
229
+ const assignmentTagsKey = this.keys.assignmentTags(id);
230
+ const assignmentGeoKey = this.keys.assignmentsGeo();
231
+ // Fetch tags and owner in case it's pending
232
+ const [tagsCsv, owner] = await Promise.all([
233
+ this.redisClient.hGet(assignmentTagsKey, 'tags'),
234
+ this.redisClient.hGet(this.assignmentOwnerKey, id)
235
+ ]);
80
236
  let tags = [];
81
237
  if (tagsCsv && tagsCsv.length > 0) {
82
238
  tags = tagsCsv.split(',');
83
239
  }
84
240
  const multi = this.redisClient.multi();
85
- // Remove from reference and per-assignment hashes
241
+ // 1. Remove from Queued state
86
242
  multi.hDel(this.assignmentsRefKey, id);
87
243
  multi.del(assignmentPriorityKey);
88
244
  multi.del(assignmentTagsKey);
89
- // Remove from global zset
90
245
  multi.zRem(this.assignmentsKey, id.toString());
91
- // Remove from per-tag zsets
92
246
  for (const tag of tags) {
93
- multi.zRem(this.redisPrefix + `tag:${tag}:assignments`, id.toString());
94
- }
247
+ multi.zRem(this.keys.tagAssignments(tag), id.toString());
248
+ }
249
+ multi.zRem(assignmentGeoKey, id.toString());
250
+ // 2. Remove from Pending state
251
+ multi.hDel(this.pendingAssignmentsKey, id);
252
+ multi.zRem(this.pendingAssignmentsExpiryKey, id);
253
+ multi.hDel(this.assignmentOwnerKey, id);
254
+ if (owner) {
255
+ multi.sRem(this.keys.userAssignments(owner), `assignment:${id}`);
256
+ }
257
+ // 3. Remove from Accepted state
258
+ multi.hDel(this.acceptedAssignmentsKey, id);
95
259
  await multi.exec();
96
260
  return id;
97
261
  }
98
262
  async removeUser(userId) {
99
263
  const multi = this.redisClient
100
264
  .multi()
101
- .del(this.redisPrefix + `user:${userId}:assignments`)
102
- .del(this.redisPrefix + `user:${userId}:rejected`)
265
+ .del(this.keys.userAssignments(userId))
266
+ .del(this.keys.userRejected(userId))
103
267
  .hDel(this.usersKey, userId);
104
268
  await multi.exec();
105
269
  return userId;
@@ -109,13 +273,7 @@ class AssignmentMatcher {
109
273
  * For large datasets, prefer using getAssignmentsPaginated() instead.
110
274
  */
111
275
  async getAllAssignments() {
112
- const [queuedAssignments, pendingAssignments, acceptedAssignments] = await Promise.all([
113
- this.redisClient.hGetAll(this.assignmentsRefKey),
114
- this.redisClient.hGetAll(this.pendingAssignmentsKey),
115
- this.redisClient.hGetAll(this.acceptedAssignmentsKey),
116
- ]);
117
- const allAssignments = { ...queuedAssignments, ...pendingAssignments, ...acceptedAssignments };
118
- return Object.values(allAssignments).map((assignment) => JSON.parse(assignment));
276
+ return (0, pagination_1.getAllAssignmentsFromStores)(this.redisClient, this.assignmentStoreKeys);
119
277
  }
120
278
  /**
121
279
  * Get assignments with pagination support for efficient querying of large datasets.
@@ -127,399 +285,34 @@ class AssignmentMatcher {
127
285
  * @param options.includeTotal - Whether to include total count (slower for large datasets)
128
286
  */
129
287
  async getAssignmentsPaginated(options) {
130
- const limit = options?.limit ?? 100;
131
- const status = options?.status ?? 'all';
132
- const includeTotal = options?.includeTotal ?? false;
133
- const getKeyForStatus = (s) => {
134
- switch (s) {
135
- case 'queued': return this.assignmentsRefKey;
136
- case 'pending': return this.pendingAssignmentsKey;
137
- case 'accepted': return this.acceptedAssignmentsKey;
138
- }
139
- };
140
- const statusOrder = status === 'all' ? ['queued', 'pending', 'accepted'] : [status];
141
- // Parse cursor: "statusIndex:offset" where offset is how many we've seen in current status
142
- let statusIndex = 0;
143
- let offset = 0;
144
- if (options?.cursor) {
145
- const parts = options.cursor.split(':');
146
- statusIndex = parseInt(parts[0], 10) || 0;
147
- offset = parseInt(parts[1], 10) || 0;
148
- }
149
- const assignments = [];
150
- let nextCursor = null;
151
- let hasMore = false;
152
- while (assignments.length < limit && statusIndex < statusOrder.length) {
153
- const scanStatus = statusOrder[statusIndex];
154
- const key = getKeyForStatus(scanStatus);
155
- // Get count for this status
156
- const totalInStatus = await this.redisClient.hLen(key);
157
- const remainingInStatus = totalInStatus - offset;
158
- if (remainingInStatus <= 0) {
159
- // Move to next status
160
- statusIndex++;
161
- offset = 0;
162
- continue;
163
- }
164
- // Scan to get entries - we need to scan through and skip offset entries
165
- const needed = limit - assignments.length;
166
- let scanned = 0;
167
- let cursor = '0';
168
- const seenIds = new Set();
169
- do {
170
- const { cursor: newCursor, entries } = await this.redisClient.hScan(key, cursor, {
171
- COUNT: Math.max(needed + offset - scanned, 100),
172
- });
173
- for (const entry of entries) {
174
- if (seenIds.has(entry.field))
175
- continue; // Skip duplicates from HSCAN
176
- seenIds.add(entry.field);
177
- if (scanned < offset) {
178
- scanned++;
179
- continue; // Skip already-seen entries
180
- }
181
- if (assignments.length >= limit) {
182
- // We have enough, set cursor for next page
183
- nextCursor = `${statusIndex}:${offset + (assignments.length - (assignments.filter(a => a._status === scanStatus).length - 1))}`;
184
- hasMore = true;
185
- break;
186
- }
187
- try {
188
- const assignment = JSON.parse(entry.value);
189
- assignment._status = scanStatus;
190
- assignments.push(assignment);
191
- }
192
- catch {
193
- // Skip invalid JSON
194
- }
195
- scanned++;
196
- }
197
- cursor = newCursor;
198
- } while (cursor !== '0' && assignments.length < limit);
199
- if (assignments.length >= limit) {
200
- // Calculate correct offset for resume
201
- const countFromCurrentStatus = assignments.filter(a => a._status === scanStatus).length;
202
- nextCursor = `${statusIndex}:${offset + countFromCurrentStatus}`;
203
- hasMore = true;
204
- break;
205
- }
206
- // Move to next status
207
- statusIndex++;
208
- offset = 0;
209
- }
210
- // Check if there's more data in remaining statuses
211
- if (!hasMore && statusIndex < statusOrder.length) {
212
- for (let i = statusIndex; i < statusOrder.length; i++) {
213
- const count = await this.redisClient.hLen(getKeyForStatus(statusOrder[i]));
214
- const processedInThisStatus = i === statusIndex ? offset : 0;
215
- if (count > processedInThisStatus) {
216
- nextCursor = `${i}:${processedInThisStatus}`;
217
- hasMore = true;
218
- break;
219
- }
220
- }
221
- }
222
- const result = {
223
- assignments,
224
- nextCursor: hasMore ? nextCursor : null,
225
- hasMore,
226
- };
227
- // Optionally include total count
228
- if (includeTotal) {
229
- if (status === 'all') {
230
- const [queuedCount, pendingCount, acceptedCount] = await Promise.all([
231
- this.redisClient.hLen(this.assignmentsRefKey),
232
- this.redisClient.hLen(this.pendingAssignmentsKey),
233
- this.redisClient.hLen(this.acceptedAssignmentsKey),
234
- ]);
235
- result.total = queuedCount + pendingCount + acceptedCount;
236
- }
237
- else {
238
- result.total = await this.redisClient.hLen(getKeyForStatus(status));
239
- }
240
- }
241
- return result;
288
+ return (0, pagination_1.getAssignmentsPaginatedFromStores)(this.redisClient, this.assignmentStoreKeys, options);
242
289
  }
243
290
  /**
244
291
  * Get assignment counts by status without fetching the data.
245
292
  * Efficient for dashboards and monitoring.
246
293
  */
247
294
  async getAssignmentCounts() {
248
- const [queued, pending, accepted] = await Promise.all([
249
- this.redisClient.hLen(this.assignmentsRefKey),
250
- this.redisClient.hLen(this.pendingAssignmentsKey),
251
- this.redisClient.hLen(this.acceptedAssignmentsKey),
252
- ]);
253
- return {
254
- queued,
255
- pending,
256
- accepted,
257
- total: queued + pending + accepted,
258
- };
295
+ return (0, pagination_1.getAssignmentCountsFromStores)(this.redisClient, this.assignmentStoreKeys);
259
296
  }
260
297
  /**
261
298
  * Get a single assignment by ID from any status.
262
299
  */
263
300
  async getAssignment(id) {
264
- // Check all three stores in parallel
265
- const [queued, pending, accepted] = await Promise.all([
266
- this.redisClient.hGet(this.assignmentsRefKey, id),
267
- this.redisClient.hGet(this.pendingAssignmentsKey, id),
268
- this.redisClient.hGet(this.acceptedAssignmentsKey, id),
269
- ]);
270
- if (queued) {
271
- const assignment = JSON.parse(queued);
272
- assignment._status = 'queued';
273
- return assignment;
274
- }
275
- if (pending) {
276
- const assignment = JSON.parse(pending);
277
- assignment._status = 'pending';
278
- return assignment;
279
- }
280
- if (accepted) {
281
- const assignment = JSON.parse(accepted);
282
- assignment._status = 'accepted';
283
- return assignment;
284
- }
285
- return null;
301
+ return (0, pagination_1.getAssignmentById)(this.redisClient, this.assignmentStoreKeys, id);
286
302
  }
287
303
  /**
288
304
  * Get multiple assignments by IDs efficiently.
289
305
  */
290
306
  async getAssignmentsByIds(ids) {
291
- if (ids.length === 0)
292
- return [];
293
- const multi = this.redisClient.multi();
294
- for (const id of ids) {
295
- multi.hGet(this.assignmentsRefKey, id);
296
- multi.hGet(this.pendingAssignmentsKey, id);
297
- multi.hGet(this.acceptedAssignmentsKey, id);
298
- }
299
- const results = await multi.exec();
300
- const assignments = [];
301
- for (let i = 0; i < ids.length; i++) {
302
- const queued = results[i * 3];
303
- const pending = results[i * 3 + 1];
304
- const accepted = results[i * 3 + 2];
305
- const json = queued || pending || accepted;
306
- if (json) {
307
- try {
308
- const assignment = JSON.parse(json);
309
- assignment._status = queued ? 'queued' : pending ? 'pending' : 'accepted';
310
- assignments.push(assignment);
311
- }
312
- catch {
313
- // Skip invalid JSON
314
- }
315
- }
316
- }
317
- return assignments;
318
- }
319
- // ==================== CIDR/IP Matching Utilities ====================
320
- /**
321
- * Parse an IPv4 address into a BigInt representation
322
- */
323
- parseIPv4(ip) {
324
- const parts = ip.split('.');
325
- if (parts.length !== 4)
326
- return null;
327
- let result = 0n;
328
- for (const part of parts) {
329
- const num = parseInt(part, 10);
330
- if (isNaN(num) || num < 0 || num > 255)
331
- return null;
332
- result = (result << 8n) | BigInt(num);
333
- }
334
- return result;
335
- }
336
- /**
337
- * Parse an IPv6 address into a BigInt representation
338
- * Handles full, compressed (::), and IPv4-mapped formats
339
- */
340
- parseIPv6(ip) {
341
- // Handle IPv4-mapped IPv6 (::ffff:192.168.1.1)
342
- const ipv4MappedMatch = ip.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i);
343
- if (ipv4MappedMatch) {
344
- const ipv4 = this.parseIPv4(ipv4MappedMatch[1]);
345
- if (ipv4 === null)
346
- return null;
347
- return 0xffff00000000n | ipv4;
348
- }
349
- // Handle :: expansion
350
- let fullIp = ip.toLowerCase();
351
- if (fullIp.includes('::')) {
352
- const parts = fullIp.split('::');
353
- if (parts.length > 2)
354
- return null; // Invalid: more than one ::
355
- const leftParts = parts[0] ? parts[0].split(':') : [];
356
- const rightParts = parts[1] ? parts[1].split(':') : [];
357
- const missingGroups = 8 - leftParts.length - rightParts.length;
358
- if (missingGroups < 0)
359
- return null;
360
- const allParts = [...leftParts, ...Array(missingGroups).fill('0'), ...rightParts];
361
- fullIp = allParts.join(':');
362
- }
363
- const groups = fullIp.split(':');
364
- if (groups.length !== 8)
365
- return null;
366
- let result = 0n;
367
- for (const group of groups) {
368
- if (group.length === 0 || group.length > 4)
369
- return null;
370
- const num = parseInt(group, 16);
371
- if (isNaN(num) || num < 0 || num > 0xffff)
372
- return null;
373
- result = (result << 16n) | BigInt(num);
374
- }
375
- return result;
376
- }
377
- /**
378
- * Parse an IP address (auto-detect IPv4 or IPv6)
379
- * Returns { value: BigInt, isIPv6: boolean } or null if invalid
380
- */
381
- parseIP(ip) {
382
- if (!ip || typeof ip !== 'string')
383
- return null;
384
- const trimmed = ip.trim();
385
- // Try IPv4 first (contains dots, no colons)
386
- if (trimmed.includes('.') && !trimmed.includes(':')) {
387
- const value = this.parseIPv4(trimmed);
388
- if (value !== null)
389
- return { value, isIPv6: false };
390
- }
391
- // Try IPv6 (contains colons)
392
- if (trimmed.includes(':')) {
393
- const value = this.parseIPv6(trimmed);
394
- if (value !== null)
395
- return { value, isIPv6: true };
396
- }
397
- return null;
307
+ return (0, pagination_1.getAssignmentsByIdsBatch)(this.redisClient, this.assignmentStoreKeys, ids);
398
308
  }
399
- /**
400
- * Parse a CIDR notation string (e.g., '192.168.1.0/24' or '2001:db8::/32')
401
- * Returns { network: BigInt, prefixLength: number, isIPv6: boolean } or null
402
- */
403
- parseCIDR(cidr) {
404
- if (!cidr || typeof cidr !== 'string')
405
- return null;
406
- const parts = cidr.trim().split('/');
407
- if (parts.length !== 2)
408
- return null;
409
- const ip = this.parseIP(parts[0]);
410
- if (!ip)
411
- return null;
412
- const prefixLength = parseInt(parts[1], 10);
413
- const maxPrefix = ip.isIPv6 ? 128 : 32;
414
- if (isNaN(prefixLength) || prefixLength < 0 || prefixLength > maxPrefix)
415
- return null;
416
- // Calculate network address by masking
417
- const totalBits = ip.isIPv6 ? 128 : 32;
418
- const hostBits = totalBits - prefixLength;
419
- const mask = hostBits === totalBits ? 0n : ((1n << BigInt(totalBits)) - 1n) ^ ((1n << BigInt(hostBits)) - 1n);
420
- const network = ip.value & mask;
421
- return { network, prefixLength, isIPv6: ip.isIPv6 };
422
- }
423
- /**
424
- * Check if an IP address is within a CIDR range
425
- */
426
- isIpInCidr(ip, cidr) {
427
- const parsedIp = this.parseIP(ip);
428
- const parsedCidr = this.parseCIDR(cidr);
429
- if (!parsedIp || !parsedCidr)
430
- return false;
431
- // IP version must match CIDR version
432
- if (parsedIp.isIPv6 !== parsedCidr.isIPv6)
433
- return false;
434
- const totalBits = parsedIp.isIPv6 ? 128 : 32;
435
- const hostBits = totalBits - parsedCidr.prefixLength;
436
- const mask = hostBits === totalBits ? 0n : ((1n << BigInt(totalBits)) - 1n) ^ ((1n << BigInt(hostBits)) - 1n);
437
- return (parsedIp.value & mask) === parsedCidr.network;
438
- }
439
- /**
440
- * Check if a user's IP matches any of the allowed CIDRs
441
- * Returns true if no CIDRs are specified (open assignment) or if IP matches any CIDR
442
- */
443
- checkCidrMatch(userIp, allowedCidrs) {
444
- // If no CIDR restrictions, assignment is open to all
445
- if (!allowedCidrs || allowedCidrs.length === 0)
446
- return true;
447
- // If CIDRs are specified but user has no IP, deny match
448
- if (!userIp)
449
- return false;
450
- // Check if user IP matches any allowed CIDR
451
- for (const cidr of allowedCidrs) {
452
- if (this.isIpInCidr(userIp, cidr))
453
- return true;
454
- }
455
- return false;
456
- }
457
- // ==================== End CIDR/IP Matching Utilities ====================
458
- async matchScore(user, assignmentTags, assignmentPriority, assignmentId) {
459
- const aTags = assignmentTags ? assignmentTags.split(',') : [];
460
- const matchesPattern = (pattern, tag) => {
461
- if (pattern === tag)
462
- return true;
463
- if (pattern.endsWith('*')) {
464
- const prefix = pattern.slice(0, -1);
465
- return tag.startsWith(prefix);
466
- }
467
- return false;
468
- };
469
- // If weighted skills are present, use them for scoring
470
- if (user.routingWeights && Object.keys(user.routingWeights).length > 0) {
471
- // Check for exclusions (weight 0)
472
- for (const [pattern, weight] of Object.entries(user.routingWeights)) {
473
- if (weight === 0) {
474
- for (const t of aTags) {
475
- if (matchesPattern(pattern, t)) {
476
- return [0, Number(assignmentPriority) || 0];
477
- }
478
- }
479
- }
480
- }
481
- let weightSum = 0;
482
- for (const t of aTags) {
483
- let matchedByRouting = false;
484
- for (const [pattern, weight] of Object.entries(user.routingWeights)) {
485
- if (typeof weight === 'number' && weight > 0) {
486
- if (matchesPattern(pattern, t)) {
487
- weightSum += weight;
488
- matchedByRouting = true;
489
- }
490
- }
491
- }
492
- // If enableDefaultMatching is true, and the tag is 'default', and it wasn't matched by any routing weight,
493
- // we give it default weight 1.
494
- if (this.enableDefaultMatching && t === 'default' && !matchedByRouting) {
495
- weightSum += 1;
496
- }
497
- }
498
- const base = Number(assignmentPriority) || 0;
499
- return [weightSum, base + weightSum];
500
- }
501
- // Fallback to default tag-intersection scoring
502
- const userTagSet = new Set(user.tags);
503
- const assignmentTagSet = new Set(aTags);
504
- let intersectionSize = 0;
505
- for (const userTag of userTagSet) {
506
- let matched = false;
507
- for (const assignmentTag of assignmentTagSet) {
508
- if (matchesPattern(userTag, assignmentTag)) {
509
- matched = true;
510
- break;
511
- }
512
- }
513
- if (matched)
514
- intersectionSize++;
515
- }
516
- const score = userTagSet.size > 0 ? intersectionSize / userTagSet.size : 0;
517
- const base = Number(assignmentPriority) || 0;
518
- return [score || 0, base + (score || 0)];
309
+ /** Default match score implementation using extracted scoring module */
310
+ defaultMatchScore(user, assignmentTags, assignmentPriority, _assignmentId) {
311
+ return Promise.resolve((0, match_score_1.calculateMatchScore)(user, assignmentTags, assignmentPriority, this.enableDefaultMatching));
519
312
  }
520
313
  async calculatePriority(...args) {
521
314
  const [assignment] = args;
522
- return new Date().getTime() - assignment?.createdAt || 0;
315
+ return (0, match_score_1.calculateDefaultPriority)(assignment?.createdAt);
523
316
  }
524
317
  get stats() {
525
318
  return (async () => {
@@ -547,9 +340,9 @@ class AssignmentMatcher {
547
340
  })();
548
341
  }
549
342
  async setAssignmentPriority(id, priority) {
550
- const assignmentPriorityKey = this.redisPrefix + `assignment:${id}:priority`;
343
+ const assignmentPriorityKey = this.keys.assignmentPriority(id);
551
344
  // Fetch tags to update per-tag indices
552
- const assignmentTagsKey = this.redisPrefix + `assignment:${id}:tags`;
345
+ const assignmentTagsKey = this.keys.assignmentTags(id);
553
346
  const [existsRef, tagsCsv] = await this.redisClient
554
347
  .multi()
555
348
  .hExists(this.assignmentsRefKey, id)
@@ -562,7 +355,7 @@ class AssignmentMatcher {
562
355
  // Update global zset score and per-tag zset scores only if assignment still exists
563
356
  multi.zAdd(this.assignmentsKey, { score: Number(priority), value: id });
564
357
  for (const tag of tags) {
565
- multi.zAdd(this.redisPrefix + `tag:${tag}:assignments`, { score: Number(priority), value: id });
358
+ multi.zAdd(this.keys.tagAssignments(tag), { score: Number(priority), value: id });
566
359
  }
567
360
  }
568
361
  await multi.exec();
@@ -579,7 +372,7 @@ class AssignmentMatcher {
579
372
  const multi = this.redisClient.multi();
580
373
  for (const assignment of relevantAssignments) {
581
374
  const id = assignment.id;
582
- const assignmentPriorityKey = this.redisPrefix + `assignment:${id}:priority`;
375
+ const assignmentPriorityKey = this.keys.assignmentPriority(id);
583
376
  // Update the stored priority
584
377
  multi.hSet(assignmentPriorityKey, 'priority', priority);
585
378
  // Update global zset score
@@ -587,7 +380,7 @@ class AssignmentMatcher {
587
380
  // Update per-tag zset scores
588
381
  const idxTags = [...assignment.tags, ...(this.enableDefaultMatching ? ['default'] : [])];
589
382
  for (const tag of idxTags) {
590
- multi.zAdd(this.redisPrefix + `tag:${tag}:assignments`, { score: Number(priority), value: id });
383
+ multi.zAdd(this.keys.tagAssignments(tag), { score: Number(priority), value: id });
591
384
  }
592
385
  }
593
386
  await multi.exec();
@@ -595,7 +388,19 @@ class AssignmentMatcher {
595
388
  return relevantAssignments.map((assignment) => ({ id: assignment.id, priority }));
596
389
  }
597
390
  async getUserRelatedAssignments(user) {
598
- // Build candidate assignments using per-tag zset union with user weights for scalability.
391
+ const userAssignments = [];
392
+ // Priority 1: Check for workflow-targeted assignments (deterministic matching)
393
+ if (this.enableWorkflows) {
394
+ const workflowAssignments = await this.getWorkflowTargetedAssignments(user.id);
395
+ if (workflowAssignments.length > 0) {
396
+ // Workflow assignments take precedence - add them first with highest priority
397
+ userAssignments.push(...workflowAssignments);
398
+ if (userAssignments.length >= this.maxUserBacklogSize) {
399
+ return userAssignments;
400
+ }
401
+ }
402
+ }
403
+ // Priority 2: Build candidate assignments using per-tag zset union with user weights for scalability.
599
404
  const positiveWeights = [];
600
405
  const zeroWeightTags = [];
601
406
  if (user.routingWeights && Object.keys(user.routingWeights).length > 0) {
@@ -619,7 +424,6 @@ class AssignmentMatcher {
619
424
  if (!defaultInPos && !defaultZero)
620
425
  positiveWeights.push({ tag: 'default', weight: 1 });
621
426
  }
622
- const userAssignments = [];
623
427
  if (positiveWeights.length === 0)
624
428
  return userAssignments;
625
429
  // Expand wildcards
@@ -628,12 +432,12 @@ class AssignmentMatcher {
628
432
  const finalZeroTags = expandedZero.map((t) => t.tag);
629
433
  if (expandedPositive.length === 0)
630
434
  return userAssignments;
631
- const tempKey = this.redisPrefix + `tmp:user:${user.id}:candidates`;
632
- const tempZeroKey = this.redisPrefix + `tmp:user:${user.id}:exclude`;
633
- const tempFinalKey = this.redisPrefix + `tmp:user:${user.id}:final`;
634
- const rejectedKey = this.redisPrefix + `user:${user.id}:rejected`;
435
+ const tempKey = this.keys.tempUserCandidates(user.id);
436
+ const tempZeroKey = this.keys.tempUserExclude(user.id);
437
+ const tempFinalKey = this.keys.tempUserFinal(user.id);
438
+ const rejectedKey = this.keys.userRejected(user.id);
635
439
  const unionKeysWithWeights = expandedPositive.map((pw) => ({
636
- key: this.redisPrefix + `tag:${pw.tag}:assignments`,
440
+ key: this.keys.tagAssignments(pw.tag),
637
441
  weight: pw.weight
638
442
  }));
639
443
  const multi = this.redisClient.multi();
@@ -644,7 +448,7 @@ class AssignmentMatcher {
644
448
  const excludeKeys = [];
645
449
  // Optional exclude set for zero-weight tags
646
450
  if (finalZeroTags.length > 0) {
647
- const zeroKeys = finalZeroTags.map((t) => this.redisPrefix + `tag:${t}:assignments`);
451
+ const zeroKeys = finalZeroTags.map((t) => this.keys.tagAssignments(t));
648
452
  multi.zUnionStore(tempZeroKey, zeroKeys);
649
453
  multi.expire(tempZeroKey, 5);
650
454
  excludeKeys.push(tempZeroKey);
@@ -665,10 +469,8 @@ class AssignmentMatcher {
665
469
  const batched = this.redisClient.multi();
666
470
  for (const entry of top) {
667
471
  const assignmentId = entry.value;
668
- const assignmentPriorityKey = this.redisPrefix + `assignment:${assignmentId}:priority`;
669
- const assignmentTagsKey = this.redisPrefix + `assignment:${assignmentId}:tags`;
670
- batched.hGet(assignmentPriorityKey, 'priority');
671
- batched.hGet(assignmentTagsKey, 'tags');
472
+ batched.hGet(this.keys.assignmentPriority(assignmentId), 'priority');
473
+ batched.hGet(this.keys.assignmentTags(assignmentId), 'tags');
672
474
  // Also fetch assignment JSON to access allowedCidrs for network matching
673
475
  batched.hGet(this.assignmentsRefKey, assignmentId);
674
476
  }
@@ -698,7 +500,7 @@ class AssignmentMatcher {
698
500
  if (userAssignments.length >= this.maxUserBacklogSize)
699
501
  break;
700
502
  // Check CIDR restrictions: if assignment has allowedCidrs, user must have matching IP
701
- if (!this.checkCidrMatch(user.ip, d.allowedCidrs)) {
503
+ if (!(0, cidr_1.checkCidrMatch)(user.ip, d.allowedCidrs)) {
702
504
  continue; // Skip this assignment - user IP doesn't match allowed CIDRs
703
505
  }
704
506
  // Use custom matchScore (supports weights) for a final check and tie-break
@@ -718,18 +520,16 @@ class AssignmentMatcher {
718
520
  for (let i = 0; i < selected.length; i++) {
719
521
  const s = selected[i];
720
522
  const json = jsons[i];
721
- const assignmentPriorityKey = this.redisPrefix + `assignment:${s.id}:priority`;
722
- const assignmentTagsKey = this.redisPrefix + `assignment:${s.id}:tags`;
723
523
  // Remove from reference and per-assignment hashes
724
524
  rm.hDel(this.assignmentsRefKey, s.id);
725
- rm.del(assignmentPriorityKey);
726
- rm.del(assignmentTagsKey);
525
+ rm.del(this.keys.assignmentPriority(s.id));
526
+ rm.del(this.keys.assignmentTags(s.id));
727
527
  // Remove from global zset
728
528
  rm.zRem(this.assignmentsKey, s.id);
729
529
  // Remove from per-tag zsets
730
530
  const tags = (s.tags ? s.tags.split(',').filter(Boolean) : []);
731
531
  for (const tag of tags) {
732
- rm.zRem(this.redisPrefix + `tag:${tag}:assignments`, s.id);
532
+ rm.zRem(this.keys.tagAssignments(tag), s.id);
733
533
  }
734
534
  // Add to pending structures
735
535
  if (json) {
@@ -749,7 +549,7 @@ class AssignmentMatcher {
749
549
  if (!userJson)
750
550
  return;
751
551
  const user = JSON.parse(userJson);
752
- const userMatchesCount = await this.redisClient.sCard(this.redisPrefix + `user:${user.id}:assignments`);
552
+ const userMatchesCount = await this.redisClient.sCard(this.keys.userAssignments(user.id));
753
553
  if (userMatchesCount >= this.maxUserBacklogSize)
754
554
  return;
755
555
  const relevantAssignments = await this.getUserRelatedAssignments(user);
@@ -757,7 +557,7 @@ class AssignmentMatcher {
757
557
  .sort((a, b) => b.priority - a.priority)
758
558
  .map((a) => `assignment:${a.id}`);
759
559
  if (relevantAssignmentKeys.length > 0) {
760
- await this.redisClient.sAdd(this.redisPrefix + `user:${user.id}:assignments`, relevantAssignmentKeys);
560
+ await this.redisClient.sAdd(this.keys.userAssignments(user.id), relevantAssignmentKeys);
761
561
  }
762
562
  return;
763
563
  }
@@ -772,7 +572,7 @@ class AssignmentMatcher {
772
572
  } while (cursor !== '0');
773
573
  // Process users in parallel
774
574
  await Promise.all(users.map(async (user) => {
775
- const userMatchesCount = await this.redisClient.sCard(this.redisPrefix + `user:${user.id}:assignments`);
575
+ const userMatchesCount = await this.redisClient.sCard(this.keys.userAssignments(user.id));
776
576
  if (userMatchesCount >= this.maxUserBacklogSize) {
777
577
  return;
778
578
  }
@@ -781,22 +581,22 @@ class AssignmentMatcher {
781
581
  .sort((a, b) => b.priority - a.priority)
782
582
  .map((a) => `assignment:${a.id}`);
783
583
  if (relevantAssignmentKeys.length > 0) {
784
- await this.redisClient.sAdd(this.redisPrefix + `user:${user.id}:assignments`, relevantAssignmentKeys);
584
+ await this.redisClient.sAdd(this.keys.userAssignments(user.id), relevantAssignmentKeys);
785
585
  }
786
586
  }));
787
587
  }
788
588
  async getCurrentAssignmentsForUser(userId) {
789
- const userAssignments = await this.redisClient.sMembers(this.redisPrefix + `user:${userId}:assignments`);
589
+ const userAssignments = await this.redisClient.sMembers(this.keys.userAssignments(userId));
790
590
  return userAssignments.map((el) => el.split(':')[1]);
791
591
  }
792
592
  async acceptAssignment(userId, assignmentId) {
793
- const isAssigned = await this.redisClient.sIsMember(this.redisPrefix + `user:${userId}:assignments`, `assignment:${assignmentId}`);
593
+ const isAssigned = await this.redisClient.sIsMember(this.keys.userAssignments(userId), `assignment:${assignmentId}`);
794
594
  if (!isAssigned)
795
595
  throw new Error('Assignment not found for user');
796
596
  // Get the assignment JSON before removing from pending
797
597
  const json = await this.redisClient.hGet(this.pendingAssignmentsKey, assignmentId);
798
598
  const multi = this.redisClient.multi();
799
- multi.sRem(this.redisPrefix + `user:${userId}:assignments`, `assignment:${assignmentId}`);
599
+ multi.sRem(this.keys.userAssignments(userId), `assignment:${assignmentId}`);
800
600
  multi.hDel(this.pendingAssignmentsKey, assignmentId);
801
601
  multi.zRem(this.pendingAssignmentsExpiryKey, assignmentId);
802
602
  multi.hDel(this.assignmentOwnerKey, assignmentId);
@@ -808,23 +608,185 @@ class AssignmentMatcher {
808
608
  return true;
809
609
  }
810
610
  async rejectAssignment(userId, assignmentId) {
811
- const isAssigned = await this.redisClient.sIsMember(this.redisPrefix + `user:${userId}:assignments`, `assignment:${assignmentId}`);
611
+ const isAssigned = await this.redisClient.sIsMember(this.keys.userAssignments(userId), `assignment:${assignmentId}`);
812
612
  if (!isAssigned)
813
613
  throw new Error('Assignment not found for user');
814
614
  const json = await this.redisClient.hGet(this.pendingAssignmentsKey, assignmentId);
815
615
  const multi = this.redisClient.multi();
816
- multi.sRem(this.redisPrefix + `user:${userId}:assignments`, `assignment:${assignmentId}`);
616
+ multi.sRem(this.keys.userAssignments(userId), `assignment:${assignmentId}`);
817
617
  multi.hDel(this.pendingAssignmentsKey, assignmentId);
818
618
  multi.zRem(this.pendingAssignmentsExpiryKey, assignmentId);
819
619
  multi.hDel(this.assignmentOwnerKey, assignmentId);
820
620
  // Add to rejected list to prevent immediate re-assignment
821
- multi.sAdd(this.redisPrefix + `user:${userId}:rejected`, assignmentId);
621
+ multi.sAdd(this.keys.userRejected(userId), assignmentId);
822
622
  await multi.exec();
823
623
  if (json) {
824
624
  await this.addAssignment(JSON.parse(json));
825
625
  }
826
626
  return true;
827
627
  }
628
+ /**
629
+ * Complete an assignment with a result payload.
630
+ * Moves the assignment from 'accepted' to 'completed' state and publishes an event
631
+ * for workflow orchestration.
632
+ *
633
+ * @param userId - The user completing the assignment
634
+ * @param assignmentId - The assignment being completed
635
+ * @param result - Optional result payload for routing decisions
636
+ */
637
+ async completeAssignment(userId, assignmentId, result) {
638
+ // Verify assignment is in accepted state
639
+ const json = await this.redisClient.hGet(this.acceptedAssignmentsKey, assignmentId);
640
+ if (!json) {
641
+ throw new Error('Assignment not found in accepted state');
642
+ }
643
+ const assignment = JSON.parse(json);
644
+ const now = Date.now();
645
+ // Move from accepted to completed
646
+ const multi = this.redisClient.multi();
647
+ multi.hDel(this.acceptedAssignmentsKey, assignmentId);
648
+ // Store in completed with result metadata
649
+ const completedData = {
650
+ ...assignment,
651
+ _completedBy: userId,
652
+ _completedAt: now,
653
+ _result: result,
654
+ };
655
+ multi.hSet(this.completedAssignmentsKey, assignmentId, JSON.stringify(completedData));
656
+ await multi.exec();
657
+ // Publish workflow event if workflows are enabled
658
+ if (this.enableWorkflows) {
659
+ await this.publishWorkflowEvent({
660
+ eventId: (0, crypto_1.randomUUID)(),
661
+ type: 'COMPLETED',
662
+ userId,
663
+ assignmentId,
664
+ timestamp: now,
665
+ payload: result?.data,
666
+ });
667
+ }
668
+ return true;
669
+ }
670
+ /**
671
+ * Fail an assignment explicitly (e.g., user reports inability to complete).
672
+ *
673
+ * @param userId - The user failing the assignment
674
+ * @param assignmentId - The assignment being failed
675
+ * @param reason - Optional reason for failure
676
+ */
677
+ async failAssignment(userId, assignmentId, reason) {
678
+ const json = await this.redisClient.hGet(this.acceptedAssignmentsKey, assignmentId);
679
+ if (!json) {
680
+ throw new Error('Assignment not found in accepted state');
681
+ }
682
+ const assignment = JSON.parse(json);
683
+ const now = Date.now();
684
+ // Move from accepted to completed (with failed status)
685
+ const multi = this.redisClient.multi();
686
+ multi.hDel(this.acceptedAssignmentsKey, assignmentId);
687
+ const failedData = {
688
+ ...assignment,
689
+ _failedBy: userId,
690
+ _failedAt: now,
691
+ _failureReason: reason,
692
+ };
693
+ multi.hSet(this.completedAssignmentsKey, assignmentId, JSON.stringify(failedData));
694
+ await multi.exec();
695
+ // Publish workflow event if workflows are enabled
696
+ if (this.enableWorkflows) {
697
+ await this.publishWorkflowEvent({
698
+ eventId: (0, crypto_1.randomUUID)(),
699
+ type: 'FAILED',
700
+ userId,
701
+ assignmentId,
702
+ timestamp: now,
703
+ payload: { reason },
704
+ });
705
+ }
706
+ return true;
707
+ }
708
+ // ============================================================================
709
+ // Workflow Management Methods
710
+ // ============================================================================
711
+ /**
712
+ * Register a workflow definition.
713
+ *
714
+ * @param definition - The workflow definition to register
715
+ */
716
+ /**
717
+ * Register a new workflow definition.
718
+ */
719
+ async registerWorkflow(definition) {
720
+ return this.workflow.registerWorkflow(definition);
721
+ }
722
+ /**
723
+ * Get a workflow definition by ID.
724
+ */
725
+ async getWorkflowDefinition(id) {
726
+ return this.workflow.getWorkflowDefinition(id);
727
+ }
728
+ /**
729
+ * List all registered workflow definitions.
730
+ */
731
+ async listWorkflowDefinitions() {
732
+ return this.workflow.listWorkflowDefinitions();
733
+ }
734
+ /**
735
+ * Start a new workflow instance for a user.
736
+ */
737
+ async startWorkflow(workflowDefinitionId, userId, initialContext) {
738
+ return this.workflow.startWorkflow(workflowDefinitionId, userId, initialContext);
739
+ }
740
+ /**
741
+ * Get a workflow instance by ID.
742
+ */
743
+ async getWorkflowInstance(instanceId) {
744
+ return this.workflow.getWorkflowInstance(instanceId);
745
+ }
746
+ /**
747
+ * Get a workflow instance with its snapshot definition.
748
+ */
749
+ async getWorkflowInstanceWithSnapshot(instanceId) {
750
+ return this.workflow.getWorkflowInstanceWithSnapshot(instanceId);
751
+ }
752
+ /**
753
+ * Get all active workflow instances for a user.
754
+ */
755
+ async getActiveWorkflowsForUser(userId) {
756
+ return this.workflow.getActiveWorkflowsForUser(userId);
757
+ }
758
+ /**
759
+ * Cancel a workflow instance.
760
+ */
761
+ async cancelWorkflow(instanceId) {
762
+ return this.workflow.cancelWorkflow(instanceId);
763
+ }
764
+ /**
765
+ * Check and process expired workflow steps.
766
+ * Should be called periodically.
767
+ */
768
+ async processExpiredWorkflowSteps() {
769
+ return this.workflow.processExpiredWorkflowSteps();
770
+ }
771
+ /**
772
+ * Publish a workflow event to the Redis Stream.
773
+ */
774
+ async publishWorkflowEvent(event) {
775
+ return this.workflow.publishWorkflowEvent(event);
776
+ }
777
+ /**
778
+ * Start the workflow orchestrator.
779
+ * This listens to the event stream and processes workflow transitions.
780
+ */
781
+ async startOrchestrator() {
782
+ return this.workflow.startOrchestrator();
783
+ }
784
+ /**
785
+ * Stop the workflow orchestrator.
786
+ */
787
+ async stopOrchestrator() {
788
+ return this.workflow.stopOrchestrator();
789
+ }
828
790
  async processExpiredMatches() {
829
791
  const now = Date.now();
830
792
  const expiredIds = await this.redisClient.zRangeByScore(this.pendingAssignmentsExpiryKey, '-inf', now);
@@ -833,12 +795,22 @@ class AssignmentMatcher {
833
795
  const json = await this.redisClient.hGet(this.pendingAssignmentsKey, id);
834
796
  const multi = this.redisClient.multi();
835
797
  if (owner) {
836
- multi.sRem(this.redisPrefix + `user:${owner}:assignments`, `assignment:${id}`);
798
+ multi.sRem(this.keys.userAssignments(owner), `assignment:${id}`);
837
799
  }
838
800
  multi.hDel(this.pendingAssignmentsKey, id);
839
801
  multi.zRem(this.pendingAssignmentsExpiryKey, id);
840
802
  multi.hDel(this.assignmentOwnerKey, id);
841
803
  await multi.exec();
804
+ // Publish workflow expired event if workflows are enabled
805
+ if (this.enableWorkflows && owner) {
806
+ await this.workflow.publishWorkflowEvent({
807
+ eventId: (0, crypto_1.randomUUID)(),
808
+ type: 'EXPIRED',
809
+ userId: owner,
810
+ assignmentId: id,
811
+ timestamp: now,
812
+ });
813
+ }
842
814
  if (json) {
843
815
  await this.addAssignment(JSON.parse(json));
844
816
  }
@@ -858,6 +830,33 @@ class AssignmentMatcher {
858
830
  this.autoReleaseInterval = null;
859
831
  }
860
832
  }
833
+ /**
834
+ * Get assignments specifically targeted at a user through active workflows.
835
+ * These take priority over general pool assignments for deterministic matching.
836
+ */
837
+ async getWorkflowTargetedAssignments(userId) {
838
+ const targeted = [];
839
+ // Scan queued assignments for those with _targetUserId matching this user
840
+ const queuedAssignments = await this.redisClient.hGetAll(this.assignmentsRefKey);
841
+ for (const [assignmentId, json] of Object.entries(queuedAssignments)) {
842
+ try {
843
+ const assignment = JSON.parse(json);
844
+ if (assignment._targetUserId === userId && assignment._workflowInstanceId) {
845
+ // This is a workflow assignment targeted at this user
846
+ targeted.push({
847
+ id: assignmentId,
848
+ priority: assignment.priority ?? 1000,
849
+ });
850
+ }
851
+ }
852
+ catch {
853
+ // Ignore parse errors
854
+ }
855
+ }
856
+ // Sort by priority (higher first)
857
+ targeted.sort((a, b) => b.priority - a.priority);
858
+ return targeted;
859
+ }
861
860
  async expandTagWildcards(tags) {
862
861
  const expanded = [];
863
862
  const wildcards = tags.filter((t) => t.tag.endsWith('*'));