assignment-user-matcher 1.1.6 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +18 -2
  2. package/dist/index.d.ts +4 -0
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +26 -1
  5. package/dist/managers/ReliabilityManager.d.ts +42 -0
  6. package/dist/managers/ReliabilityManager.d.ts.map +1 -0
  7. package/dist/managers/ReliabilityManager.js +115 -0
  8. package/dist/managers/TelemetryManager.d.ts +13 -0
  9. package/dist/managers/TelemetryManager.d.ts.map +1 -0
  10. package/dist/managers/TelemetryManager.js +52 -0
  11. package/dist/managers/WorkflowManager.d.ts +69 -0
  12. package/dist/managers/WorkflowManager.d.ts.map +1 -0
  13. package/dist/managers/WorkflowManager.js +735 -0
  14. package/dist/matcher.class.d.ts +143 -77
  15. package/dist/matcher.class.d.ts.map +1 -1
  16. package/dist/matcher.class.js +460 -447
  17. package/dist/queries/index.d.ts +5 -0
  18. package/dist/queries/index.d.ts.map +1 -0
  19. package/dist/queries/index.js +20 -0
  20. package/dist/queries/pagination.d.ts +51 -0
  21. package/dist/queries/pagination.d.ts.map +1 -0
  22. package/dist/queries/pagination.js +200 -0
  23. package/dist/scoring/index.d.ts +5 -0
  24. package/dist/scoring/index.d.ts.map +1 -0
  25. package/dist/scoring/index.js +20 -0
  26. package/dist/scoring/match-score.d.ts +29 -0
  27. package/dist/scoring/match-score.d.ts.map +1 -0
  28. package/dist/scoring/match-score.js +131 -0
  29. package/dist/types/matcher.d.ts +279 -0
  30. package/dist/types/matcher.d.ts.map +1 -0
  31. package/dist/types/matcher.js +2 -0
  32. package/dist/utils/cidr.d.ts +40 -0
  33. package/dist/utils/cidr.d.ts.map +1 -0
  34. package/dist/utils/cidr.js +150 -0
  35. package/dist/utils/index.d.ts +6 -0
  36. package/dist/utils/index.d.ts.map +1 -0
  37. package/dist/utils/index.js +21 -0
  38. package/dist/utils/keys.d.ts +45 -0
  39. package/dist/utils/keys.d.ts.map +1 -0
  40. package/dist/utils/keys.js +57 -0
  41. package/dist/workflow-builder.d.ts +195 -0
  42. package/dist/workflow-builder.d.ts.map +1 -0
  43. package/dist/workflow-builder.js +366 -0
  44. package/package.json +1 -1
@@ -1,33 +1,187 @@
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.usingDefaultMatchScore = !options?.matchingFunction;
53
+ this.matchScore = options?.matchingFunction ?? this.defaultMatchScore.bind(this);
54
+ // Workflow options
55
+ this.enableWorkflows = options?.enableWorkflows ?? false;
56
+ this.streamConsumerGroup = options?.streamConsumerGroup ?? 'orchestrator';
57
+ this.streamConsumerName = options?.streamConsumerName ?? (0, crypto_1.randomUUID)();
58
+ // Initialize managers
59
+ this.reliability = new ReliabilityManager_1.ReliabilityManager(this.redisClient, this.keys, {
60
+ workflowMaxRetries: options?.workflowMaxRetries ?? 3,
61
+ workflowIdempotencyTtlMs: options?.workflowIdempotencyTtlMs ?? 86400000,
62
+ workflowCircuitBreakerThreshold: options?.workflowCircuitBreakerThreshold ?? 5,
63
+ workflowCircuitBreakerResetMs: options?.workflowCircuitBreakerResetMs ?? 30000,
64
+ workflowAuditEnabled: options?.workflowAuditEnabled ?? false,
65
+ workflowSnapshotDefinitions: options?.workflowSnapshotDefinitions ?? true,
66
+ streamConsumerName: this.streamConsumerName,
67
+ });
68
+ this.telemetry = new TelemetryManager_1.TelemetryManager(options?.enableOpenTelemetry ?? false);
69
+ this.workflow = new WorkflowManager_1.WorkflowManager(this.redisClient, this.keys, this.reliability, this.telemetry, this, {
70
+ enableWorkflows: this.enableWorkflows,
71
+ streamConsumerGroup: this.streamConsumerGroup,
72
+ streamConsumerName: this.streamConsumerName,
73
+ reclaimIntervalMs: options?.workflowReclaimPollIntervalMs ?? 5000,
74
+ reclaimMinIdleMs: options?.workflowOrphanReclaimMs ?? 60000,
75
+ });
22
76
  this.initRedis();
23
77
  }
78
+ /** Keys for the three assignment stores (used by pagination queries) */
79
+ get assignmentStoreKeys() {
80
+ return {
81
+ queued: this.assignmentsRefKey,
82
+ pending: this.pendingAssignmentsKey,
83
+ accepted: this.acceptedAssignmentsKey,
84
+ completed: this.completedAssignmentsKey,
85
+ };
86
+ }
24
87
  async initRedis() {
25
88
  // Only attempt to connect if the client isn't already connected
26
89
  if (!this.redisClient.isOpen) {
27
90
  await this.redisClient.connect();
28
91
  }
92
+ // Initialize workflow stream consumer group if workflows are enabled
93
+ if (this.enableWorkflows) {
94
+ await this.workflow.init();
95
+ // Load Lua script for atomic transitions
96
+ await this.loadLuaScripts();
97
+ }
29
98
  return this;
30
99
  }
100
+ /**
101
+ * Load Lua scripts into Redis for atomic operations.
102
+ */
103
+ async loadLuaScripts() {
104
+ try {
105
+ this.luaScriptSha = await this.redisClient.scriptLoad(WORKFLOW_TRANSITION_LUA);
106
+ this.workflow.setLuaScriptSha(this.luaScriptSha);
107
+ }
108
+ catch (err) {
109
+ console.error('Failed to load Lua scripts:', err);
110
+ // Fallback to non-atomic mode
111
+ this.luaScriptSha = null;
112
+ }
113
+ }
114
+ async atomicWorkflowTransition(instanceId, expectedVersion, newStatus, newStepId, updatedContext, historyEntry) {
115
+ return this.workflow.atomicWorkflowTransition(instanceId, expectedVersion, newStatus, newStepId, updatedContext, historyEntry);
116
+ }
117
+ async reclaimOrphanedMessages() {
118
+ return this.workflow.reclaimOrphanedMessages();
119
+ }
120
+ /**
121
+ * Get events from the Dead Letter Queue.
122
+ */
123
+ async getDeadLetterEvents(limit = 100, offset = 0) {
124
+ return this.reliability.getDeadLetterEvents(limit, offset);
125
+ }
126
+ /**
127
+ * Get Dead Letter Queue size.
128
+ */
129
+ async getDeadLetterQueueSize() {
130
+ return this.reliability.getDeadLetterQueueSize();
131
+ }
132
+ /**
133
+ * Replay a Dead Letter Queue event.
134
+ */
135
+ async replayDeadLetterEvent(eventJson) {
136
+ const entry = JSON.parse(eventJson);
137
+ // Reset retry count
138
+ await this.redisClient.del(this.keys.eventRetryCount(entry.event.eventId));
139
+ // Re-publish the event
140
+ await this.publishWorkflowEvent(entry.event);
141
+ // Remove from DLQ
142
+ await this.redisClient.zRem(this.keys.deadLetterQueue(), eventJson);
143
+ return true;
144
+ }
145
+ /**
146
+ * Clear all events from the Dead Letter Queue.
147
+ */
148
+ async clearDeadLetterQueue() {
149
+ return this.reliability.clearDeadLetterQueue();
150
+ }
151
+ /**
152
+ * Get audit events from the audit stream.
153
+ */
154
+ async getAuditEvents(count = 100) {
155
+ return this.reliability.getAuditEvents(count);
156
+ }
157
+ // ============================================================================
158
+ // OpenTelemetry Tracing Hooks
159
+ // ============================================================================
160
+ /**
161
+ * Set the OpenTelemetry tracer instance.
162
+ */
163
+ setTracer(tracer) {
164
+ this.telemetry.setTracer(tracer);
165
+ }
166
+ /**
167
+ * Initialize the Redis Stream consumer group for workflow events.
168
+ * Creates the stream and consumer group if they don't exist.
169
+ */
170
+ async initStreamConsumerGroup() {
171
+ const streamKey = this.keys.eventStream();
172
+ try {
173
+ // Try to create the consumer group (and stream if needed)
174
+ await this.redisClient.xGroupCreate(streamKey, this.streamConsumerGroup, '0', {
175
+ MKSTREAM: true,
176
+ });
177
+ }
178
+ catch (err) {
179
+ // Ignore "BUSYGROUP" error - group already exists
180
+ if (!err.message?.includes('BUSYGROUP')) {
181
+ throw err;
182
+ }
183
+ }
184
+ }
31
185
  async addUser(user) {
32
186
  await this.redisClient.hSet(this.usersKey, user.id, JSON.stringify({
33
187
  ...user,
@@ -39,9 +193,9 @@ class AssignmentMatcher {
39
193
  let { id, tags, priority, latitude, longitude } = assignment;
40
194
  if (!priority)
41
195
  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`;
196
+ const assignmentPriorityKey = this.keys.assignmentPriority(id);
197
+ const assignmentTagsKey = this.keys.assignmentTags(id);
198
+ const assignmentGeoKey = this.keys.assignmentsGeo();
45
199
  const multi = this.redisClient
46
200
  .multi()
47
201
  .hSet(this.assignmentsRefKey, id, JSON.stringify(assignment))
@@ -63,7 +217,7 @@ class AssignmentMatcher {
63
217
  // This enables efficient weighted matching via ZUNIONSTORE.
64
218
  const indexTags = [...tags, ...(this.enableDefaultMatching ? ['default'] : [])];
65
219
  for (const tag of indexTags) {
66
- multi.zAdd(this.redisPrefix + `tag:${tag}:assignments`, {
220
+ multi.zAdd(this.keys.tagAssignments(tag), {
67
221
  score: Number(priority),
68
222
  value: id,
69
223
  });
@@ -73,33 +227,45 @@ class AssignmentMatcher {
73
227
  return assignment;
74
228
  }
75
229
  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();
230
+ const assignmentPriorityKey = this.keys.assignmentPriority(id);
231
+ const assignmentTagsKey = this.keys.assignmentTags(id);
232
+ const assignmentGeoKey = this.keys.assignmentsGeo();
233
+ // Fetch tags and owner in case it's pending
234
+ const [tagsCsv, owner] = await Promise.all([
235
+ this.redisClient.hGet(assignmentTagsKey, 'tags'),
236
+ this.redisClient.hGet(this.assignmentOwnerKey, id)
237
+ ]);
80
238
  let tags = [];
81
239
  if (tagsCsv && tagsCsv.length > 0) {
82
240
  tags = tagsCsv.split(',');
83
241
  }
84
242
  const multi = this.redisClient.multi();
85
- // Remove from reference and per-assignment hashes
243
+ // 1. Remove from Queued state
86
244
  multi.hDel(this.assignmentsRefKey, id);
87
245
  multi.del(assignmentPriorityKey);
88
246
  multi.del(assignmentTagsKey);
89
- // Remove from global zset
90
247
  multi.zRem(this.assignmentsKey, id.toString());
91
- // Remove from per-tag zsets
92
248
  for (const tag of tags) {
93
- multi.zRem(this.redisPrefix + `tag:${tag}:assignments`, id.toString());
94
- }
249
+ multi.zRem(this.keys.tagAssignments(tag), id.toString());
250
+ }
251
+ multi.zRem(assignmentGeoKey, id.toString());
252
+ // 2. Remove from Pending state
253
+ multi.hDel(this.pendingAssignmentsKey, id);
254
+ multi.zRem(this.pendingAssignmentsExpiryKey, id);
255
+ multi.hDel(this.assignmentOwnerKey, id);
256
+ if (owner) {
257
+ multi.sRem(this.keys.userAssignments(owner), `assignment:${id}`);
258
+ }
259
+ // 3. Remove from Accepted state
260
+ multi.hDel(this.acceptedAssignmentsKey, id);
95
261
  await multi.exec();
96
262
  return id;
97
263
  }
98
264
  async removeUser(userId) {
99
265
  const multi = this.redisClient
100
266
  .multi()
101
- .del(this.redisPrefix + `user:${userId}:assignments`)
102
- .del(this.redisPrefix + `user:${userId}:rejected`)
267
+ .del(this.keys.userAssignments(userId))
268
+ .del(this.keys.userRejected(userId))
103
269
  .hDel(this.usersKey, userId);
104
270
  await multi.exec();
105
271
  return userId;
@@ -109,13 +275,7 @@ class AssignmentMatcher {
109
275
  * For large datasets, prefer using getAssignmentsPaginated() instead.
110
276
  */
111
277
  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));
278
+ return (0, pagination_1.getAllAssignmentsFromStores)(this.redisClient, this.assignmentStoreKeys);
119
279
  }
120
280
  /**
121
281
  * Get assignments with pagination support for efficient querying of large datasets.
@@ -127,399 +287,34 @@ class AssignmentMatcher {
127
287
  * @param options.includeTotal - Whether to include total count (slower for large datasets)
128
288
  */
129
289
  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;
290
+ return (0, pagination_1.getAssignmentsPaginatedFromStores)(this.redisClient, this.assignmentStoreKeys, options);
242
291
  }
243
292
  /**
244
293
  * Get assignment counts by status without fetching the data.
245
294
  * Efficient for dashboards and monitoring.
246
295
  */
247
296
  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
- };
297
+ return (0, pagination_1.getAssignmentCountsFromStores)(this.redisClient, this.assignmentStoreKeys);
259
298
  }
260
299
  /**
261
300
  * Get a single assignment by ID from any status.
262
301
  */
263
302
  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;
303
+ return (0, pagination_1.getAssignmentById)(this.redisClient, this.assignmentStoreKeys, id);
286
304
  }
287
305
  /**
288
306
  * Get multiple assignments by IDs efficiently.
289
307
  */
290
308
  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;
309
+ return (0, pagination_1.getAssignmentsByIdsBatch)(this.redisClient, this.assignmentStoreKeys, ids);
376
310
  }
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;
398
- }
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)];
311
+ /** Default match score implementation using extracted scoring module */
312
+ defaultMatchScore(user, assignmentTags, assignmentPriority, _assignmentId, skillThresholds) {
313
+ return Promise.resolve((0, match_score_1.calculateMatchScore)(user, assignmentTags, assignmentPriority, this.enableDefaultMatching, skillThresholds));
519
314
  }
520
315
  async calculatePriority(...args) {
521
316
  const [assignment] = args;
522
- return new Date().getTime() - assignment?.createdAt || 0;
317
+ return (0, match_score_1.calculateDefaultPriority)(assignment?.createdAt);
523
318
  }
524
319
  get stats() {
525
320
  return (async () => {
@@ -547,9 +342,9 @@ class AssignmentMatcher {
547
342
  })();
548
343
  }
549
344
  async setAssignmentPriority(id, priority) {
550
- const assignmentPriorityKey = this.redisPrefix + `assignment:${id}:priority`;
345
+ const assignmentPriorityKey = this.keys.assignmentPriority(id);
551
346
  // Fetch tags to update per-tag indices
552
- const assignmentTagsKey = this.redisPrefix + `assignment:${id}:tags`;
347
+ const assignmentTagsKey = this.keys.assignmentTags(id);
553
348
  const [existsRef, tagsCsv] = await this.redisClient
554
349
  .multi()
555
350
  .hExists(this.assignmentsRefKey, id)
@@ -562,7 +357,7 @@ class AssignmentMatcher {
562
357
  // Update global zset score and per-tag zset scores only if assignment still exists
563
358
  multi.zAdd(this.assignmentsKey, { score: Number(priority), value: id });
564
359
  for (const tag of tags) {
565
- multi.zAdd(this.redisPrefix + `tag:${tag}:assignments`, { score: Number(priority), value: id });
360
+ multi.zAdd(this.keys.tagAssignments(tag), { score: Number(priority), value: id });
566
361
  }
567
362
  }
568
363
  await multi.exec();
@@ -579,7 +374,7 @@ class AssignmentMatcher {
579
374
  const multi = this.redisClient.multi();
580
375
  for (const assignment of relevantAssignments) {
581
376
  const id = assignment.id;
582
- const assignmentPriorityKey = this.redisPrefix + `assignment:${id}:priority`;
377
+ const assignmentPriorityKey = this.keys.assignmentPriority(id);
583
378
  // Update the stored priority
584
379
  multi.hSet(assignmentPriorityKey, 'priority', priority);
585
380
  // Update global zset score
@@ -587,7 +382,7 @@ class AssignmentMatcher {
587
382
  // Update per-tag zset scores
588
383
  const idxTags = [...assignment.tags, ...(this.enableDefaultMatching ? ['default'] : [])];
589
384
  for (const tag of idxTags) {
590
- multi.zAdd(this.redisPrefix + `tag:${tag}:assignments`, { score: Number(priority), value: id });
385
+ multi.zAdd(this.keys.tagAssignments(tag), { score: Number(priority), value: id });
591
386
  }
592
387
  }
593
388
  await multi.exec();
@@ -595,11 +390,25 @@ class AssignmentMatcher {
595
390
  return relevantAssignments.map((assignment) => ({ id: assignment.id, priority }));
596
391
  }
597
392
  async getUserRelatedAssignments(user) {
598
- // Build candidate assignments using per-tag zset union with user weights for scalability.
393
+ const userAssignments = [];
394
+ const routingWeights = user.routingWeights;
395
+ const hasRoutingWeights = Boolean(routingWeights && Object.keys(routingWeights).length > 0);
396
+ // Priority 1: Check for workflow-targeted assignments (deterministic matching)
397
+ if (this.enableWorkflows) {
398
+ const workflowAssignments = await this.getWorkflowTargetedAssignments(user.id);
399
+ if (workflowAssignments.length > 0) {
400
+ // Workflow assignments take precedence - add them first with highest priority
401
+ userAssignments.push(...workflowAssignments);
402
+ if (userAssignments.length >= this.maxUserBacklogSize) {
403
+ return userAssignments;
404
+ }
405
+ }
406
+ }
407
+ // Priority 2: Build candidate assignments using per-tag zset union with user weights for scalability.
599
408
  const positiveWeights = [];
600
409
  const zeroWeightTags = [];
601
- if (user.routingWeights && Object.keys(user.routingWeights).length > 0) {
602
- for (const [tag, w] of Object.entries(user.routingWeights)) {
410
+ if (hasRoutingWeights) {
411
+ for (const [tag, w] of Object.entries(routingWeights)) {
603
412
  if (typeof w === 'number' && w > 0)
604
413
  positiveWeights.push({ tag, weight: w });
605
414
  else if (w === 0)
@@ -612,28 +421,35 @@ class AssignmentMatcher {
612
421
  positiveWeights.push({ tag, weight: 1 });
613
422
  }
614
423
  }
615
- // Ensure default tag is included if enabled and not explicitly weighted to zero
616
- if (this.enableDefaultMatching) {
424
+ // Ensure default tag is included for unweighted users.
425
+ // In weighted + default scoring path, only explicit positive weights may match.
426
+ if (this.enableDefaultMatching && !hasRoutingWeights) {
617
427
  const defaultInPos = positiveWeights.find((t) => t.tag === 'default');
618
- const defaultZero = zeroWeightTags.includes('default');
428
+ const defaultZero = zeroWeightTags.some((tag) => tag === 'default' || (tag.endsWith('*') && 'default'.startsWith(tag.slice(0, -1))));
619
429
  if (!defaultInPos && !defaultZero)
620
430
  positiveWeights.push({ tag: 'default', weight: 1 });
621
431
  }
622
- const userAssignments = [];
432
+ // In weighted default matching, users must define at least one positive weight.
433
+ // If they don't, nothing should be assigned and queue remains intact.
434
+ if (hasRoutingWeights && this.usingDefaultMatchScore && positiveWeights.length === 0) {
435
+ return userAssignments;
436
+ }
623
437
  if (positiveWeights.length === 0)
624
438
  return userAssignments;
625
439
  // Expand wildcards
626
440
  const expandedPositive = await this.expandTagWildcards(positiveWeights);
627
- const expandedZero = await this.expandTagWildcards(zeroWeightTags.map((t) => ({ tag: t, weight: 0 })));
441
+ const expandedZero = this.usingDefaultMatchScore
442
+ ? await this.expandTagWildcards(zeroWeightTags.map((t) => ({ tag: t, weight: 0 })))
443
+ : [];
628
444
  const finalZeroTags = expandedZero.map((t) => t.tag);
629
445
  if (expandedPositive.length === 0)
630
446
  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`;
447
+ const tempKey = this.keys.tempUserCandidates(user.id);
448
+ const tempZeroKey = this.keys.tempUserExclude(user.id);
449
+ const tempFinalKey = this.keys.tempUserFinal(user.id);
450
+ const rejectedKey = this.keys.userRejected(user.id);
635
451
  const unionKeysWithWeights = expandedPositive.map((pw) => ({
636
- key: this.redisPrefix + `tag:${pw.tag}:assignments`,
452
+ key: this.keys.tagAssignments(pw.tag),
637
453
  weight: pw.weight
638
454
  }));
639
455
  const multi = this.redisClient.multi();
@@ -644,7 +460,7 @@ class AssignmentMatcher {
644
460
  const excludeKeys = [];
645
461
  // Optional exclude set for zero-weight tags
646
462
  if (finalZeroTags.length > 0) {
647
- const zeroKeys = finalZeroTags.map((t) => this.redisPrefix + `tag:${t}:assignments`);
463
+ const zeroKeys = finalZeroTags.map((t) => this.keys.tagAssignments(t));
648
464
  multi.zUnionStore(tempZeroKey, zeroKeys);
649
465
  multi.expire(tempZeroKey, 5);
650
466
  excludeKeys.push(tempZeroKey);
@@ -665,10 +481,8 @@ class AssignmentMatcher {
665
481
  const batched = this.redisClient.multi();
666
482
  for (const entry of top) {
667
483
  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');
484
+ batched.hGet(this.keys.assignmentPriority(assignmentId), 'priority');
485
+ batched.hGet(this.keys.assignmentTags(assignmentId), 'tags');
672
486
  // Also fetch assignment JSON to access allowedCidrs for network matching
673
487
  batched.hGet(this.assignmentsRefKey, assignmentId);
674
488
  }
@@ -680,16 +494,18 @@ class AssignmentMatcher {
680
494
  const tags = String(flat[i * 3 + 1] || '');
681
495
  const assignmentJson = flat[i * 3 + 2];
682
496
  let allowedCidrs;
497
+ let skillThresholds;
683
498
  if (assignmentJson) {
684
499
  try {
685
500
  const parsed = JSON.parse(assignmentJson);
686
501
  allowedCidrs = parsed.allowedCidrs;
502
+ skillThresholds = parsed.skillThresholds;
687
503
  }
688
504
  catch {
689
505
  // Ignore JSON parse errors
690
506
  }
691
507
  }
692
- details.push({ id: assignmentId, basePriority: priority, tags, allowedCidrs });
508
+ details.push({ id: assignmentId, basePriority: priority, tags, allowedCidrs, skillThresholds });
693
509
  }
694
510
  // Prefer higher base priority first to satisfy tests and practical expectations
695
511
  details.sort((a, b) => b.basePriority - a.basePriority);
@@ -698,11 +514,11 @@ class AssignmentMatcher {
698
514
  if (userAssignments.length >= this.maxUserBacklogSize)
699
515
  break;
700
516
  // Check CIDR restrictions: if assignment has allowedCidrs, user must have matching IP
701
- if (!this.checkCidrMatch(user.ip, d.allowedCidrs)) {
517
+ if (!(0, cidr_1.checkCidrMatch)(user.ip, d.allowedCidrs)) {
702
518
  continue; // Skip this assignment - user IP doesn't match allowed CIDRs
703
519
  }
704
- // Use custom matchScore (supports weights) for a final check and tie-break
705
- const [score, combinedPriority] = await this.matchScore(user, d.tags, d.basePriority, d.id);
520
+ // Use custom matchScore (supports weights and thresholds) for a final check and tie-break
521
+ const [score, combinedPriority] = await this.matchScore(user, d.tags, d.basePriority, d.id, d.skillThresholds);
706
522
  if (score && combinedPriority) {
707
523
  userAssignments.push({ id: d.id, priority: combinedPriority });
708
524
  selected.push({ id: d.id, tags: d.tags });
@@ -718,18 +534,16 @@ class AssignmentMatcher {
718
534
  for (let i = 0; i < selected.length; i++) {
719
535
  const s = selected[i];
720
536
  const json = jsons[i];
721
- const assignmentPriorityKey = this.redisPrefix + `assignment:${s.id}:priority`;
722
- const assignmentTagsKey = this.redisPrefix + `assignment:${s.id}:tags`;
723
537
  // Remove from reference and per-assignment hashes
724
538
  rm.hDel(this.assignmentsRefKey, s.id);
725
- rm.del(assignmentPriorityKey);
726
- rm.del(assignmentTagsKey);
539
+ rm.del(this.keys.assignmentPriority(s.id));
540
+ rm.del(this.keys.assignmentTags(s.id));
727
541
  // Remove from global zset
728
542
  rm.zRem(this.assignmentsKey, s.id);
729
543
  // Remove from per-tag zsets
730
544
  const tags = (s.tags ? s.tags.split(',').filter(Boolean) : []);
731
545
  for (const tag of tags) {
732
- rm.zRem(this.redisPrefix + `tag:${tag}:assignments`, s.id);
546
+ rm.zRem(this.keys.tagAssignments(tag), s.id);
733
547
  }
734
548
  // Add to pending structures
735
549
  if (json) {
@@ -749,7 +563,7 @@ class AssignmentMatcher {
749
563
  if (!userJson)
750
564
  return;
751
565
  const user = JSON.parse(userJson);
752
- const userMatchesCount = await this.redisClient.sCard(this.redisPrefix + `user:${user.id}:assignments`);
566
+ const userMatchesCount = await this.redisClient.sCard(this.keys.userAssignments(user.id));
753
567
  if (userMatchesCount >= this.maxUserBacklogSize)
754
568
  return;
755
569
  const relevantAssignments = await this.getUserRelatedAssignments(user);
@@ -757,7 +571,7 @@ class AssignmentMatcher {
757
571
  .sort((a, b) => b.priority - a.priority)
758
572
  .map((a) => `assignment:${a.id}`);
759
573
  if (relevantAssignmentKeys.length > 0) {
760
- await this.redisClient.sAdd(this.redisPrefix + `user:${user.id}:assignments`, relevantAssignmentKeys);
574
+ await this.redisClient.sAdd(this.keys.userAssignments(user.id), relevantAssignmentKeys);
761
575
  }
762
576
  return;
763
577
  }
@@ -772,7 +586,7 @@ class AssignmentMatcher {
772
586
  } while (cursor !== '0');
773
587
  // Process users in parallel
774
588
  await Promise.all(users.map(async (user) => {
775
- const userMatchesCount = await this.redisClient.sCard(this.redisPrefix + `user:${user.id}:assignments`);
589
+ const userMatchesCount = await this.redisClient.sCard(this.keys.userAssignments(user.id));
776
590
  if (userMatchesCount >= this.maxUserBacklogSize) {
777
591
  return;
778
592
  }
@@ -781,22 +595,22 @@ class AssignmentMatcher {
781
595
  .sort((a, b) => b.priority - a.priority)
782
596
  .map((a) => `assignment:${a.id}`);
783
597
  if (relevantAssignmentKeys.length > 0) {
784
- await this.redisClient.sAdd(this.redisPrefix + `user:${user.id}:assignments`, relevantAssignmentKeys);
598
+ await this.redisClient.sAdd(this.keys.userAssignments(user.id), relevantAssignmentKeys);
785
599
  }
786
600
  }));
787
601
  }
788
602
  async getCurrentAssignmentsForUser(userId) {
789
- const userAssignments = await this.redisClient.sMembers(this.redisPrefix + `user:${userId}:assignments`);
603
+ const userAssignments = await this.redisClient.sMembers(this.keys.userAssignments(userId));
790
604
  return userAssignments.map((el) => el.split(':')[1]);
791
605
  }
792
606
  async acceptAssignment(userId, assignmentId) {
793
- const isAssigned = await this.redisClient.sIsMember(this.redisPrefix + `user:${userId}:assignments`, `assignment:${assignmentId}`);
607
+ const isAssigned = await this.redisClient.sIsMember(this.keys.userAssignments(userId), `assignment:${assignmentId}`);
794
608
  if (!isAssigned)
795
609
  throw new Error('Assignment not found for user');
796
610
  // Get the assignment JSON before removing from pending
797
611
  const json = await this.redisClient.hGet(this.pendingAssignmentsKey, assignmentId);
798
612
  const multi = this.redisClient.multi();
799
- multi.sRem(this.redisPrefix + `user:${userId}:assignments`, `assignment:${assignmentId}`);
613
+ multi.sRem(this.keys.userAssignments(userId), `assignment:${assignmentId}`);
800
614
  multi.hDel(this.pendingAssignmentsKey, assignmentId);
801
615
  multi.zRem(this.pendingAssignmentsExpiryKey, assignmentId);
802
616
  multi.hDel(this.assignmentOwnerKey, assignmentId);
@@ -808,23 +622,185 @@ class AssignmentMatcher {
808
622
  return true;
809
623
  }
810
624
  async rejectAssignment(userId, assignmentId) {
811
- const isAssigned = await this.redisClient.sIsMember(this.redisPrefix + `user:${userId}:assignments`, `assignment:${assignmentId}`);
625
+ const isAssigned = await this.redisClient.sIsMember(this.keys.userAssignments(userId), `assignment:${assignmentId}`);
812
626
  if (!isAssigned)
813
627
  throw new Error('Assignment not found for user');
814
628
  const json = await this.redisClient.hGet(this.pendingAssignmentsKey, assignmentId);
815
629
  const multi = this.redisClient.multi();
816
- multi.sRem(this.redisPrefix + `user:${userId}:assignments`, `assignment:${assignmentId}`);
630
+ multi.sRem(this.keys.userAssignments(userId), `assignment:${assignmentId}`);
817
631
  multi.hDel(this.pendingAssignmentsKey, assignmentId);
818
632
  multi.zRem(this.pendingAssignmentsExpiryKey, assignmentId);
819
633
  multi.hDel(this.assignmentOwnerKey, assignmentId);
820
634
  // Add to rejected list to prevent immediate re-assignment
821
- multi.sAdd(this.redisPrefix + `user:${userId}:rejected`, assignmentId);
635
+ multi.sAdd(this.keys.userRejected(userId), assignmentId);
822
636
  await multi.exec();
823
637
  if (json) {
824
638
  await this.addAssignment(JSON.parse(json));
825
639
  }
826
640
  return true;
827
641
  }
642
+ /**
643
+ * Complete an assignment with a result payload.
644
+ * Moves the assignment from 'accepted' to 'completed' state and publishes an event
645
+ * for workflow orchestration.
646
+ *
647
+ * @param userId - The user completing the assignment
648
+ * @param assignmentId - The assignment being completed
649
+ * @param result - Optional result payload for routing decisions
650
+ */
651
+ async completeAssignment(userId, assignmentId, result) {
652
+ // Verify assignment is in accepted state
653
+ const json = await this.redisClient.hGet(this.acceptedAssignmentsKey, assignmentId);
654
+ if (!json) {
655
+ throw new Error('Assignment not found in accepted state');
656
+ }
657
+ const assignment = JSON.parse(json);
658
+ const now = Date.now();
659
+ // Move from accepted to completed
660
+ const multi = this.redisClient.multi();
661
+ multi.hDel(this.acceptedAssignmentsKey, assignmentId);
662
+ // Store in completed with result metadata
663
+ const completedData = {
664
+ ...assignment,
665
+ _completedBy: userId,
666
+ _completedAt: now,
667
+ _result: result,
668
+ };
669
+ multi.hSet(this.completedAssignmentsKey, assignmentId, JSON.stringify(completedData));
670
+ await multi.exec();
671
+ // Publish workflow event if workflows are enabled
672
+ if (this.enableWorkflows) {
673
+ await this.publishWorkflowEvent({
674
+ eventId: (0, crypto_1.randomUUID)(),
675
+ type: 'COMPLETED',
676
+ userId,
677
+ assignmentId,
678
+ timestamp: now,
679
+ payload: result?.data,
680
+ });
681
+ }
682
+ return true;
683
+ }
684
+ /**
685
+ * Fail an assignment explicitly (e.g., user reports inability to complete).
686
+ *
687
+ * @param userId - The user failing the assignment
688
+ * @param assignmentId - The assignment being failed
689
+ * @param reason - Optional reason for failure
690
+ */
691
+ async failAssignment(userId, assignmentId, reason) {
692
+ const json = await this.redisClient.hGet(this.acceptedAssignmentsKey, assignmentId);
693
+ if (!json) {
694
+ throw new Error('Assignment not found in accepted state');
695
+ }
696
+ const assignment = JSON.parse(json);
697
+ const now = Date.now();
698
+ // Move from accepted to completed (with failed status)
699
+ const multi = this.redisClient.multi();
700
+ multi.hDel(this.acceptedAssignmentsKey, assignmentId);
701
+ const failedData = {
702
+ ...assignment,
703
+ _failedBy: userId,
704
+ _failedAt: now,
705
+ _failureReason: reason,
706
+ };
707
+ multi.hSet(this.completedAssignmentsKey, assignmentId, JSON.stringify(failedData));
708
+ await multi.exec();
709
+ // Publish workflow event if workflows are enabled
710
+ if (this.enableWorkflows) {
711
+ await this.publishWorkflowEvent({
712
+ eventId: (0, crypto_1.randomUUID)(),
713
+ type: 'FAILED',
714
+ userId,
715
+ assignmentId,
716
+ timestamp: now,
717
+ payload: { reason },
718
+ });
719
+ }
720
+ return true;
721
+ }
722
+ // ============================================================================
723
+ // Workflow Management Methods
724
+ // ============================================================================
725
+ /**
726
+ * Register a workflow definition.
727
+ *
728
+ * @param definition - The workflow definition to register
729
+ */
730
+ /**
731
+ * Register a new workflow definition.
732
+ */
733
+ async registerWorkflow(definition) {
734
+ return this.workflow.registerWorkflow(definition);
735
+ }
736
+ /**
737
+ * Get a workflow definition by ID.
738
+ */
739
+ async getWorkflowDefinition(id) {
740
+ return this.workflow.getWorkflowDefinition(id);
741
+ }
742
+ /**
743
+ * List all registered workflow definitions.
744
+ */
745
+ async listWorkflowDefinitions() {
746
+ return this.workflow.listWorkflowDefinitions();
747
+ }
748
+ /**
749
+ * Start a new workflow instance for a user.
750
+ */
751
+ async startWorkflow(workflowDefinitionId, userId, initialContext) {
752
+ return this.workflow.startWorkflow(workflowDefinitionId, userId, initialContext);
753
+ }
754
+ /**
755
+ * Get a workflow instance by ID.
756
+ */
757
+ async getWorkflowInstance(instanceId) {
758
+ return this.workflow.getWorkflowInstance(instanceId);
759
+ }
760
+ /**
761
+ * Get a workflow instance with its snapshot definition.
762
+ */
763
+ async getWorkflowInstanceWithSnapshot(instanceId) {
764
+ return this.workflow.getWorkflowInstanceWithSnapshot(instanceId);
765
+ }
766
+ /**
767
+ * Get all active workflow instances for a user.
768
+ */
769
+ async getActiveWorkflowsForUser(userId) {
770
+ return this.workflow.getActiveWorkflowsForUser(userId);
771
+ }
772
+ /**
773
+ * Cancel a workflow instance.
774
+ */
775
+ async cancelWorkflow(instanceId) {
776
+ return this.workflow.cancelWorkflow(instanceId);
777
+ }
778
+ /**
779
+ * Check and process expired workflow steps.
780
+ * Should be called periodically.
781
+ */
782
+ async processExpiredWorkflowSteps() {
783
+ return this.workflow.processExpiredWorkflowSteps();
784
+ }
785
+ /**
786
+ * Publish a workflow event to the Redis Stream.
787
+ */
788
+ async publishWorkflowEvent(event) {
789
+ return this.workflow.publishWorkflowEvent(event);
790
+ }
791
+ /**
792
+ * Start the workflow orchestrator.
793
+ * This listens to the event stream and processes workflow transitions.
794
+ */
795
+ async startOrchestrator() {
796
+ return this.workflow.startOrchestrator();
797
+ }
798
+ /**
799
+ * Stop the workflow orchestrator.
800
+ */
801
+ async stopOrchestrator() {
802
+ return this.workflow.stopOrchestrator();
803
+ }
828
804
  async processExpiredMatches() {
829
805
  const now = Date.now();
830
806
  const expiredIds = await this.redisClient.zRangeByScore(this.pendingAssignmentsExpiryKey, '-inf', now);
@@ -833,12 +809,22 @@ class AssignmentMatcher {
833
809
  const json = await this.redisClient.hGet(this.pendingAssignmentsKey, id);
834
810
  const multi = this.redisClient.multi();
835
811
  if (owner) {
836
- multi.sRem(this.redisPrefix + `user:${owner}:assignments`, `assignment:${id}`);
812
+ multi.sRem(this.keys.userAssignments(owner), `assignment:${id}`);
837
813
  }
838
814
  multi.hDel(this.pendingAssignmentsKey, id);
839
815
  multi.zRem(this.pendingAssignmentsExpiryKey, id);
840
816
  multi.hDel(this.assignmentOwnerKey, id);
841
817
  await multi.exec();
818
+ // Publish workflow expired event if workflows are enabled
819
+ if (this.enableWorkflows && owner) {
820
+ await this.workflow.publishWorkflowEvent({
821
+ eventId: (0, crypto_1.randomUUID)(),
822
+ type: 'EXPIRED',
823
+ userId: owner,
824
+ assignmentId: id,
825
+ timestamp: now,
826
+ });
827
+ }
842
828
  if (json) {
843
829
  await this.addAssignment(JSON.parse(json));
844
830
  }
@@ -858,6 +844,33 @@ class AssignmentMatcher {
858
844
  this.autoReleaseInterval = null;
859
845
  }
860
846
  }
847
+ /**
848
+ * Get assignments specifically targeted at a user through active workflows.
849
+ * These take priority over general pool assignments for deterministic matching.
850
+ */
851
+ async getWorkflowTargetedAssignments(userId) {
852
+ const targeted = [];
853
+ // Scan queued assignments for those with _targetUserId matching this user
854
+ const queuedAssignments = await this.redisClient.hGetAll(this.assignmentsRefKey);
855
+ for (const [assignmentId, json] of Object.entries(queuedAssignments)) {
856
+ try {
857
+ const assignment = JSON.parse(json);
858
+ if (assignment._targetUserId === userId && assignment._workflowInstanceId) {
859
+ // This is a workflow assignment targeted at this user
860
+ targeted.push({
861
+ id: assignmentId,
862
+ priority: assignment.priority ?? 1000,
863
+ });
864
+ }
865
+ }
866
+ catch {
867
+ // Ignore parse errors
868
+ }
869
+ }
870
+ // Sort by priority (higher first)
871
+ targeted.sort((a, b) => b.priority - a.priority);
872
+ return targeted;
873
+ }
861
874
  async expandTagWildcards(tags) {
862
875
  const expanded = [];
863
876
  const wildcards = tags.filter((t) => t.tag.endsWith('*'));