assignment-user-matcher 1.2.1 → 1.2.2
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.
- package/README.md +505 -0
- package/dist/index.d.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -1
- package/dist/learning/features.d.ts +19 -0
- package/dist/learning/features.d.ts.map +1 -0
- package/dist/learning/features.js +55 -0
- package/dist/managers/LearningManager.d.ts +94 -0
- package/dist/managers/LearningManager.d.ts.map +1 -0
- package/dist/managers/LearningManager.js +194 -0
- package/dist/managers/WorkflowManager.d.ts +3 -6
- package/dist/managers/WorkflowManager.d.ts.map +1 -1
- package/dist/managers/WorkflowManager.js +15 -4
- package/dist/matcher.class.d.ts +78 -8
- package/dist/matcher.class.d.ts.map +1 -1
- package/dist/matcher.class.js +329 -13
- package/dist/types/matcher.d.ts +119 -9
- package/dist/types/matcher.d.ts.map +1 -1
- package/dist/utils/keys.d.ts +5 -0
- package/dist/utils/keys.d.ts.map +1 -1
- package/dist/utils/keys.js +6 -0
- package/dist/workflow-builder.d.ts +2 -4
- package/dist/workflow-builder.d.ts.map +1 -1
- package/dist/workflow-builder.js +4 -46
- package/dist/workflow-validation.d.ts +4 -0
- package/dist/workflow-validation.d.ts.map +1 -0
- package/dist/workflow-validation.js +85 -0
- package/package.json +4 -2
package/dist/matcher.class.js
CHANGED
|
@@ -7,6 +7,8 @@ const cidr_1 = require("./utils/cidr");
|
|
|
7
7
|
const keys_1 = require("./utils/keys");
|
|
8
8
|
const pagination_1 = require("./queries/pagination");
|
|
9
9
|
const match_score_1 = require("./scoring/match-score");
|
|
10
|
+
const features_1 = require("./learning/features");
|
|
11
|
+
const LearningManager_1 = require("./managers/LearningManager");
|
|
10
12
|
const ReliabilityManager_1 = require("./managers/ReliabilityManager");
|
|
11
13
|
const TelemetryManager_1 = require("./managers/TelemetryManager");
|
|
12
14
|
const WorkflowManager_1 = require("./managers/WorkflowManager");
|
|
@@ -32,6 +34,7 @@ class AssignmentMatcher {
|
|
|
32
34
|
this.redisClient = redisClient;
|
|
33
35
|
this.luaScriptSha = null;
|
|
34
36
|
this.autoReleaseInterval = null;
|
|
37
|
+
this.idleUserInterval = null;
|
|
35
38
|
this.relevantBatchSize = options?.relevantBatchSize ?? 50;
|
|
36
39
|
this.enableDefaultMatching = options?.enableDefaultMatching ?? true;
|
|
37
40
|
this.redisPrefix = options?.redisPrefix ?? '';
|
|
@@ -42,6 +45,7 @@ class AssignmentMatcher {
|
|
|
42
45
|
this.assignmentsRefKey = this.keys.assignmentsRef();
|
|
43
46
|
this.maxUserBacklogSize = options?.maxUserBacklogSize ?? 9;
|
|
44
47
|
this.matchExpirationMs = options?.matchExpirationMs ?? 60000;
|
|
48
|
+
this.idleUserTimeoutMs = options?.idleUserTimeoutMs ?? null;
|
|
45
49
|
this.pendingAssignmentsKey = this.keys.pendingAssignmentsData();
|
|
46
50
|
this.pendingAssignmentsExpiryKey = this.keys.pendingAssignmentsExpiry();
|
|
47
51
|
this.assignmentOwnerKey = this.keys.assignmentOwner();
|
|
@@ -66,6 +70,19 @@ class AssignmentMatcher {
|
|
|
66
70
|
streamConsumerName: this.streamConsumerName,
|
|
67
71
|
});
|
|
68
72
|
this.telemetry = new TelemetryManager_1.TelemetryManager(options?.enableOpenTelemetry ?? false);
|
|
73
|
+
// Learning layer (opt-in contextual bandit re-ranking)
|
|
74
|
+
this.enableLearning = options?.enableLearning ?? false;
|
|
75
|
+
this.learningFeatureExtractor = options?.learningFeatureExtractor ?? features_1.extractMatchFeatures;
|
|
76
|
+
this.learning = new LearningManager_1.LearningManager(this.redisClient, this.keys, {
|
|
77
|
+
learningRate: options?.learningRate,
|
|
78
|
+
explorationRate: options?.learningExplorationRate,
|
|
79
|
+
shadowMode: options?.learningShadowMode,
|
|
80
|
+
boostFactor: options?.learningBoostFactor,
|
|
81
|
+
rewards: options?.learningRewards,
|
|
82
|
+
decisionTtlMs: options?.learningDecisionTtlMs,
|
|
83
|
+
signalWeights: options?.learningSignalWeights,
|
|
84
|
+
feedbackTtlMs: options?.learningFeedbackTtlMs,
|
|
85
|
+
});
|
|
69
86
|
this.workflow = new WorkflowManager_1.WorkflowManager(this.redisClient, this.keys, this.reliability, this.telemetry, this, {
|
|
70
87
|
enableWorkflows: this.enableWorkflows,
|
|
71
88
|
streamConsumerGroup: this.streamConsumerGroup,
|
|
@@ -73,7 +90,7 @@ class AssignmentMatcher {
|
|
|
73
90
|
reclaimIntervalMs: options?.workflowReclaimPollIntervalMs ?? 5000,
|
|
74
91
|
reclaimMinIdleMs: options?.workflowOrphanReclaimMs ?? 60000,
|
|
75
92
|
});
|
|
76
|
-
this.initRedis();
|
|
93
|
+
this.readyPromise = this.initRedis();
|
|
77
94
|
}
|
|
78
95
|
/** Keys for the three assignment stores (used by pagination queries) */
|
|
79
96
|
get assignmentStoreKeys() {
|
|
@@ -97,6 +114,12 @@ class AssignmentMatcher {
|
|
|
97
114
|
}
|
|
98
115
|
return this;
|
|
99
116
|
}
|
|
117
|
+
/**
|
|
118
|
+
* Wait until the matcher has connected and initialized workflow internals.
|
|
119
|
+
*/
|
|
120
|
+
async waitUntilReady() {
|
|
121
|
+
return this.readyPromise;
|
|
122
|
+
}
|
|
100
123
|
/**
|
|
101
124
|
* Load Lua scripts into Redis for atomic operations.
|
|
102
125
|
*/
|
|
@@ -112,27 +135,32 @@ class AssignmentMatcher {
|
|
|
112
135
|
}
|
|
113
136
|
}
|
|
114
137
|
async atomicWorkflowTransition(instanceId, expectedVersion, newStatus, newStepId, updatedContext, historyEntry) {
|
|
138
|
+
await this.readyPromise;
|
|
115
139
|
return this.workflow.atomicWorkflowTransition(instanceId, expectedVersion, newStatus, newStepId, updatedContext, historyEntry);
|
|
116
140
|
}
|
|
117
141
|
async reclaimOrphanedMessages() {
|
|
142
|
+
await this.readyPromise;
|
|
118
143
|
return this.workflow.reclaimOrphanedMessages();
|
|
119
144
|
}
|
|
120
145
|
/**
|
|
121
146
|
* Get events from the Dead Letter Queue.
|
|
122
147
|
*/
|
|
123
148
|
async getDeadLetterEvents(limit = 100, offset = 0) {
|
|
149
|
+
await this.readyPromise;
|
|
124
150
|
return this.reliability.getDeadLetterEvents(limit, offset);
|
|
125
151
|
}
|
|
126
152
|
/**
|
|
127
153
|
* Get Dead Letter Queue size.
|
|
128
154
|
*/
|
|
129
155
|
async getDeadLetterQueueSize() {
|
|
156
|
+
await this.readyPromise;
|
|
130
157
|
return this.reliability.getDeadLetterQueueSize();
|
|
131
158
|
}
|
|
132
159
|
/**
|
|
133
160
|
* Replay a Dead Letter Queue event.
|
|
134
161
|
*/
|
|
135
162
|
async replayDeadLetterEvent(eventJson) {
|
|
163
|
+
await this.readyPromise;
|
|
136
164
|
const entry = JSON.parse(eventJson);
|
|
137
165
|
// Reset retry count
|
|
138
166
|
await this.redisClient.del(this.keys.eventRetryCount(entry.event.eventId));
|
|
@@ -146,15 +174,70 @@ class AssignmentMatcher {
|
|
|
146
174
|
* Clear all events from the Dead Letter Queue.
|
|
147
175
|
*/
|
|
148
176
|
async clearDeadLetterQueue() {
|
|
177
|
+
await this.readyPromise;
|
|
149
178
|
return this.reliability.clearDeadLetterQueue();
|
|
150
179
|
}
|
|
151
180
|
/**
|
|
152
181
|
* Get audit events from the audit stream.
|
|
153
182
|
*/
|
|
154
183
|
async getAuditEvents(count = 100) {
|
|
184
|
+
await this.readyPromise;
|
|
155
185
|
return this.reliability.getAuditEvents(count);
|
|
156
186
|
}
|
|
157
187
|
// ============================================================================
|
|
188
|
+
// Learning (Contextual Bandit) Methods
|
|
189
|
+
// ============================================================================
|
|
190
|
+
/**
|
|
191
|
+
* Get the learned model weights (feature -> weight).
|
|
192
|
+
*/
|
|
193
|
+
async getLearningModel() {
|
|
194
|
+
await this.readyPromise;
|
|
195
|
+
return this.learning.getModel();
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Get aggregate learning statistics (decisions, rewards, average reward).
|
|
199
|
+
*/
|
|
200
|
+
async getLearningStats() {
|
|
201
|
+
await this.readyPromise;
|
|
202
|
+
return this.learning.getStats();
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Apply a manual reward to a matched assignment's decision context.
|
|
206
|
+
* Enables custom reward shaping beyond the built-in lifecycle outcomes.
|
|
207
|
+
* Returns false when no decision context exists for the assignment.
|
|
208
|
+
*/
|
|
209
|
+
async recordLearningReward(assignmentId, reward) {
|
|
210
|
+
await this.readyPromise;
|
|
211
|
+
return this.learning.recordReward(assignmentId, reward);
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* Feed external post-processing signals into the model for an assignment
|
|
215
|
+
* (e.g. { accuracy: 0.95, csat: 0.8 }). Works for live decisions and for
|
|
216
|
+
* archived episodes of already-completed assignments (within the feedback TTL).
|
|
217
|
+
* Signal values are weighted via the `learningSignalWeights` option (default 1).
|
|
218
|
+
* Returns false when no learning context exists for the assignment.
|
|
219
|
+
*/
|
|
220
|
+
async recordLearningFeedback(assignmentId, signals) {
|
|
221
|
+
await this.readyPromise;
|
|
222
|
+
return this.learning.recordFeedback(assignmentId, signals);
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* Train the model directly with raw (features, reward) samples from an
|
|
226
|
+
* external pipeline (offline evaluation jobs, historical data imports).
|
|
227
|
+
* Returns the number of samples applied.
|
|
228
|
+
*/
|
|
229
|
+
async trainLearningSamples(samples) {
|
|
230
|
+
await this.readyPromise;
|
|
231
|
+
return this.learning.trainSamples(samples);
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* Reset the learned model weights and statistics.
|
|
235
|
+
*/
|
|
236
|
+
async resetLearningModel() {
|
|
237
|
+
await this.readyPromise;
|
|
238
|
+
return this.learning.resetModel();
|
|
239
|
+
}
|
|
240
|
+
// ============================================================================
|
|
158
241
|
// OpenTelemetry Tracing Hooks
|
|
159
242
|
// ============================================================================
|
|
160
243
|
/**
|
|
@@ -183,13 +266,16 @@ class AssignmentMatcher {
|
|
|
183
266
|
}
|
|
184
267
|
}
|
|
185
268
|
async addUser(user) {
|
|
269
|
+
await this.readyPromise;
|
|
186
270
|
await this.redisClient.hSet(this.usersKey, user.id, JSON.stringify({
|
|
187
271
|
...user,
|
|
188
272
|
tags: [...user.tags, ...(this.enableDefaultMatching ? ['default'] : [])],
|
|
189
273
|
}));
|
|
274
|
+
await this.touchUser(user.id);
|
|
190
275
|
return user;
|
|
191
276
|
}
|
|
192
277
|
async addAssignment(assignment) {
|
|
278
|
+
await this.readyPromise;
|
|
193
279
|
let { id, tags, priority, latitude, longitude } = assignment;
|
|
194
280
|
if (!priority)
|
|
195
281
|
priority = await this.calculatePriority(assignment);
|
|
@@ -227,6 +313,7 @@ class AssignmentMatcher {
|
|
|
227
313
|
return assignment;
|
|
228
314
|
}
|
|
229
315
|
async removeAssignment(id) {
|
|
316
|
+
await this.readyPromise;
|
|
230
317
|
const assignmentPriorityKey = this.keys.assignmentPriority(id);
|
|
231
318
|
const assignmentTagsKey = this.keys.assignmentTags(id);
|
|
232
319
|
const assignmentGeoKey = this.keys.assignmentsGeo();
|
|
@@ -262,10 +349,12 @@ class AssignmentMatcher {
|
|
|
262
349
|
return id;
|
|
263
350
|
}
|
|
264
351
|
async removeUser(userId) {
|
|
352
|
+
await this.readyPromise;
|
|
265
353
|
const multi = this.redisClient
|
|
266
354
|
.multi()
|
|
267
355
|
.del(this.keys.userAssignments(userId))
|
|
268
356
|
.del(this.keys.userRejected(userId))
|
|
357
|
+
.zRem(this.keys.userActivity(), userId)
|
|
269
358
|
.hDel(this.usersKey, userId);
|
|
270
359
|
await multi.exec();
|
|
271
360
|
return userId;
|
|
@@ -275,6 +364,7 @@ class AssignmentMatcher {
|
|
|
275
364
|
* For large datasets, prefer using getAssignmentsPaginated() instead.
|
|
276
365
|
*/
|
|
277
366
|
async getAllAssignments() {
|
|
367
|
+
await this.readyPromise;
|
|
278
368
|
return (0, pagination_1.getAllAssignmentsFromStores)(this.redisClient, this.assignmentStoreKeys);
|
|
279
369
|
}
|
|
280
370
|
/**
|
|
@@ -287,6 +377,7 @@ class AssignmentMatcher {
|
|
|
287
377
|
* @param options.includeTotal - Whether to include total count (slower for large datasets)
|
|
288
378
|
*/
|
|
289
379
|
async getAssignmentsPaginated(options) {
|
|
380
|
+
await this.readyPromise;
|
|
290
381
|
return (0, pagination_1.getAssignmentsPaginatedFromStores)(this.redisClient, this.assignmentStoreKeys, options);
|
|
291
382
|
}
|
|
292
383
|
/**
|
|
@@ -294,20 +385,66 @@ class AssignmentMatcher {
|
|
|
294
385
|
* Efficient for dashboards and monitoring.
|
|
295
386
|
*/
|
|
296
387
|
async getAssignmentCounts() {
|
|
388
|
+
await this.readyPromise;
|
|
297
389
|
return (0, pagination_1.getAssignmentCountsFromStores)(this.redisClient, this.assignmentStoreKeys);
|
|
298
390
|
}
|
|
299
391
|
/**
|
|
300
392
|
* Get a single assignment by ID from any status.
|
|
301
393
|
*/
|
|
302
394
|
async getAssignment(id) {
|
|
395
|
+
await this.readyPromise;
|
|
303
396
|
return (0, pagination_1.getAssignmentById)(this.redisClient, this.assignmentStoreKeys, id);
|
|
304
397
|
}
|
|
305
398
|
/**
|
|
306
399
|
* Get multiple assignments by IDs efficiently.
|
|
307
400
|
*/
|
|
308
401
|
async getAssignmentsByIds(ids) {
|
|
402
|
+
await this.readyPromise;
|
|
309
403
|
return (0, pagination_1.getAssignmentsByIdsBatch)(this.redisClient, this.assignmentStoreKeys, ids);
|
|
310
404
|
}
|
|
405
|
+
/**
|
|
406
|
+
* Get all pending assignments with owner and pending duration metadata.
|
|
407
|
+
*/
|
|
408
|
+
async getPendingAssignmentsWithAge() {
|
|
409
|
+
await this.readyPromise;
|
|
410
|
+
const now = Date.now();
|
|
411
|
+
const pendingEntries = await this.redisClient.hGetAll(this.pendingAssignmentsKey);
|
|
412
|
+
const assignmentIds = Object.keys(pendingEntries);
|
|
413
|
+
if (assignmentIds.length === 0) {
|
|
414
|
+
return [];
|
|
415
|
+
}
|
|
416
|
+
const [owners, expiryScores] = await Promise.all([
|
|
417
|
+
this.redisClient.hmGet(this.assignmentOwnerKey, assignmentIds),
|
|
418
|
+
Promise.all(assignmentIds.map((id) => this.redisClient.zScore(this.pendingAssignmentsExpiryKey, id))),
|
|
419
|
+
]);
|
|
420
|
+
const results = [];
|
|
421
|
+
for (let i = 0; i < assignmentIds.length; i++) {
|
|
422
|
+
const id = assignmentIds[i];
|
|
423
|
+
const json = pendingEntries[id];
|
|
424
|
+
if (!json)
|
|
425
|
+
continue;
|
|
426
|
+
let assignment;
|
|
427
|
+
try {
|
|
428
|
+
assignment = JSON.parse(json);
|
|
429
|
+
}
|
|
430
|
+
catch {
|
|
431
|
+
continue;
|
|
432
|
+
}
|
|
433
|
+
const score = expiryScores[i];
|
|
434
|
+
const expiresAt = score === null ? null : Number(score);
|
|
435
|
+
const pendingSince = expiresAt === null ? null : expiresAt - this.matchExpirationMs;
|
|
436
|
+
const pendingForMs = pendingSince === null ? null : Math.max(0, now - pendingSince);
|
|
437
|
+
results.push({
|
|
438
|
+
assignment,
|
|
439
|
+
ownerId: owners[i] ?? null,
|
|
440
|
+
pendingForMs,
|
|
441
|
+
pendingSince,
|
|
442
|
+
expiresAt,
|
|
443
|
+
});
|
|
444
|
+
}
|
|
445
|
+
results.sort((a, b) => (b.pendingForMs ?? -1) - (a.pendingForMs ?? -1));
|
|
446
|
+
return results;
|
|
447
|
+
}
|
|
311
448
|
/** Default match score implementation using extracted scoring module */
|
|
312
449
|
defaultMatchScore(user, assignmentTags, assignmentPriority, _assignmentId, skillThresholds) {
|
|
313
450
|
return Promise.resolve((0, match_score_1.calculateMatchScore)(user, assignmentTags, assignmentPriority, this.enableDefaultMatching, skillThresholds));
|
|
@@ -495,33 +632,74 @@ class AssignmentMatcher {
|
|
|
495
632
|
const assignmentJson = flat[i * 3 + 2];
|
|
496
633
|
let allowedCidrs;
|
|
497
634
|
let skillThresholds;
|
|
635
|
+
let raw;
|
|
498
636
|
if (assignmentJson) {
|
|
499
637
|
try {
|
|
500
638
|
const parsed = JSON.parse(assignmentJson);
|
|
501
639
|
allowedCidrs = parsed.allowedCidrs;
|
|
502
640
|
skillThresholds = parsed.skillThresholds;
|
|
641
|
+
raw = parsed;
|
|
503
642
|
}
|
|
504
643
|
catch {
|
|
505
644
|
// Ignore JSON parse errors
|
|
506
645
|
}
|
|
507
646
|
}
|
|
508
|
-
details.push({ id: assignmentId, basePriority: priority, tags, allowedCidrs, skillThresholds });
|
|
647
|
+
details.push({ id: assignmentId, basePriority: priority, tags, allowedCidrs, skillThresholds, raw });
|
|
509
648
|
}
|
|
510
649
|
// Prefer higher base priority first to satisfy tests and practical expectations
|
|
511
650
|
details.sort((a, b) => b.basePriority - a.basePriority);
|
|
512
651
|
const selected = [];
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
652
|
+
if (this.enableLearning) {
|
|
653
|
+
// Learning path: evaluate all eligible candidates, then re-rank by
|
|
654
|
+
// base priority + predicted reward (hard filters still apply first).
|
|
655
|
+
const modelWeights = await this.learning.getModel();
|
|
656
|
+
const eligible = [];
|
|
657
|
+
for (const d of details) {
|
|
658
|
+
if (!(0, cidr_1.checkCidrMatch)(user.ip, d.allowedCidrs))
|
|
659
|
+
continue;
|
|
660
|
+
const [score, combinedPriority] = await this.matchScore(user, d.tags, d.basePriority, d.id, d.skillThresholds);
|
|
661
|
+
if (!score || !combinedPriority)
|
|
662
|
+
continue;
|
|
663
|
+
const context = {
|
|
664
|
+
...(d.raw ?? {}),
|
|
665
|
+
id: d.id,
|
|
666
|
+
tags: d.tags ? d.tags.split(',').filter(Boolean) : [],
|
|
667
|
+
};
|
|
668
|
+
const features = this.learningFeatureExtractor(user, context);
|
|
669
|
+
const predicted = this.learning.predict(features, modelWeights);
|
|
670
|
+
// Shadow mode observes without influencing ranking.
|
|
671
|
+
// Epsilon-greedy exploration adds random jitter to gather data on under-served candidates.
|
|
672
|
+
const exploration = !this.learning.shadowMode && this.learning.shouldExplore()
|
|
673
|
+
? Math.random() * this.learning.boostFactor
|
|
674
|
+
: 0;
|
|
675
|
+
const effectivePriority = this.learning.shadowMode
|
|
676
|
+
? combinedPriority
|
|
677
|
+
: combinedPriority + this.learning.boostFactor * predicted + exploration;
|
|
678
|
+
eligible.push({ detail: d, combinedPriority, features, predicted, effectivePriority });
|
|
519
679
|
}
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
680
|
+
eligible.sort((a, b) => b.effectivePriority - a.effectivePriority);
|
|
681
|
+
for (const c of eligible) {
|
|
682
|
+
if (userAssignments.length >= this.maxUserBacklogSize)
|
|
683
|
+
break;
|
|
684
|
+
userAssignments.push({ id: c.detail.id, priority: c.effectivePriority });
|
|
685
|
+
selected.push({ id: c.detail.id, tags: c.detail.tags });
|
|
686
|
+
await this.learning.recordDecision(user.id, c.detail.id, c.features, c.predicted);
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
else {
|
|
690
|
+
for (const d of details) {
|
|
691
|
+
if (userAssignments.length >= this.maxUserBacklogSize)
|
|
692
|
+
break;
|
|
693
|
+
// Check CIDR restrictions: if assignment has allowedCidrs, user must have matching IP
|
|
694
|
+
if (!(0, cidr_1.checkCidrMatch)(user.ip, d.allowedCidrs)) {
|
|
695
|
+
continue; // Skip this assignment - user IP doesn't match allowed CIDRs
|
|
696
|
+
}
|
|
697
|
+
// Use custom matchScore (supports weights and thresholds) for a final check and tie-break
|
|
698
|
+
const [score, combinedPriority] = await this.matchScore(user, d.tags, d.basePriority, d.id, d.skillThresholds);
|
|
699
|
+
if (score && combinedPriority) {
|
|
700
|
+
userAssignments.push({ id: d.id, priority: combinedPriority });
|
|
701
|
+
selected.push({ id: d.id, tags: d.tags });
|
|
702
|
+
}
|
|
525
703
|
}
|
|
526
704
|
}
|
|
527
705
|
// Batch-remove all selected assignments from indexes and references to reduce round trips
|
|
@@ -557,6 +735,7 @@ class AssignmentMatcher {
|
|
|
557
735
|
return userAssignments;
|
|
558
736
|
}
|
|
559
737
|
async matchUsersAssignments(userId) {
|
|
738
|
+
await this.readyPromise;
|
|
560
739
|
// If a specific userId is provided, process only that user for precise per-user matching.
|
|
561
740
|
if (userId) {
|
|
562
741
|
const userJson = await this.redisClient.hGet(this.usersKey, userId);
|
|
@@ -600,10 +779,12 @@ class AssignmentMatcher {
|
|
|
600
779
|
}));
|
|
601
780
|
}
|
|
602
781
|
async getCurrentAssignmentsForUser(userId) {
|
|
782
|
+
await this.readyPromise;
|
|
603
783
|
const userAssignments = await this.redisClient.sMembers(this.keys.userAssignments(userId));
|
|
604
784
|
return userAssignments.map((el) => el.split(':')[1]);
|
|
605
785
|
}
|
|
606
786
|
async acceptAssignment(userId, assignmentId) {
|
|
787
|
+
await this.readyPromise;
|
|
607
788
|
const isAssigned = await this.redisClient.sIsMember(this.keys.userAssignments(userId), `assignment:${assignmentId}`);
|
|
608
789
|
if (!isAssigned)
|
|
609
790
|
throw new Error('Assignment not found for user');
|
|
@@ -619,9 +800,14 @@ class AssignmentMatcher {
|
|
|
619
800
|
multi.hSet(this.acceptedAssignmentsKey, assignmentId, json);
|
|
620
801
|
}
|
|
621
802
|
await multi.exec();
|
|
803
|
+
if (this.enableLearning) {
|
|
804
|
+
await this.learning.applyOutcome(assignmentId, 'accept');
|
|
805
|
+
}
|
|
806
|
+
await this.touchUser(userId);
|
|
622
807
|
return true;
|
|
623
808
|
}
|
|
624
809
|
async rejectAssignment(userId, assignmentId) {
|
|
810
|
+
await this.readyPromise;
|
|
625
811
|
const isAssigned = await this.redisClient.sIsMember(this.keys.userAssignments(userId), `assignment:${assignmentId}`);
|
|
626
812
|
if (!isAssigned)
|
|
627
813
|
throw new Error('Assignment not found for user');
|
|
@@ -634,6 +820,10 @@ class AssignmentMatcher {
|
|
|
634
820
|
// Add to rejected list to prevent immediate re-assignment
|
|
635
821
|
multi.sAdd(this.keys.userRejected(userId), assignmentId);
|
|
636
822
|
await multi.exec();
|
|
823
|
+
if (this.enableLearning) {
|
|
824
|
+
await this.learning.applyOutcome(assignmentId, 'reject');
|
|
825
|
+
}
|
|
826
|
+
await this.touchUser(userId);
|
|
637
827
|
if (json) {
|
|
638
828
|
await this.addAssignment(JSON.parse(json));
|
|
639
829
|
}
|
|
@@ -649,6 +839,7 @@ class AssignmentMatcher {
|
|
|
649
839
|
* @param result - Optional result payload for routing decisions
|
|
650
840
|
*/
|
|
651
841
|
async completeAssignment(userId, assignmentId, result) {
|
|
842
|
+
await this.readyPromise;
|
|
652
843
|
// Verify assignment is in accepted state
|
|
653
844
|
const json = await this.redisClient.hGet(this.acceptedAssignmentsKey, assignmentId);
|
|
654
845
|
if (!json) {
|
|
@@ -668,6 +859,9 @@ class AssignmentMatcher {
|
|
|
668
859
|
};
|
|
669
860
|
multi.hSet(this.completedAssignmentsKey, assignmentId, JSON.stringify(completedData));
|
|
670
861
|
await multi.exec();
|
|
862
|
+
if (this.enableLearning) {
|
|
863
|
+
await this.learning.applyOutcome(assignmentId, 'complete');
|
|
864
|
+
}
|
|
671
865
|
// Publish workflow event if workflows are enabled
|
|
672
866
|
if (this.enableWorkflows) {
|
|
673
867
|
await this.publishWorkflowEvent({
|
|
@@ -689,6 +883,7 @@ class AssignmentMatcher {
|
|
|
689
883
|
* @param reason - Optional reason for failure
|
|
690
884
|
*/
|
|
691
885
|
async failAssignment(userId, assignmentId, reason) {
|
|
886
|
+
await this.readyPromise;
|
|
692
887
|
const json = await this.redisClient.hGet(this.acceptedAssignmentsKey, assignmentId);
|
|
693
888
|
if (!json) {
|
|
694
889
|
throw new Error('Assignment not found in accepted state');
|
|
@@ -706,6 +901,9 @@ class AssignmentMatcher {
|
|
|
706
901
|
};
|
|
707
902
|
multi.hSet(this.completedAssignmentsKey, assignmentId, JSON.stringify(failedData));
|
|
708
903
|
await multi.exec();
|
|
904
|
+
if (this.enableLearning) {
|
|
905
|
+
await this.learning.applyOutcome(assignmentId, 'fail');
|
|
906
|
+
}
|
|
709
907
|
// Publish workflow event if workflows are enabled
|
|
710
908
|
if (this.enableWorkflows) {
|
|
711
909
|
await this.publishWorkflowEvent({
|
|
@@ -731,48 +929,67 @@ class AssignmentMatcher {
|
|
|
731
929
|
* Register a new workflow definition.
|
|
732
930
|
*/
|
|
733
931
|
async registerWorkflow(definition) {
|
|
932
|
+
await this.readyPromise;
|
|
734
933
|
return this.workflow.registerWorkflow(definition);
|
|
735
934
|
}
|
|
736
935
|
/**
|
|
737
936
|
* Get a workflow definition by ID.
|
|
738
937
|
*/
|
|
739
938
|
async getWorkflowDefinition(id) {
|
|
939
|
+
await this.readyPromise;
|
|
740
940
|
return this.workflow.getWorkflowDefinition(id);
|
|
741
941
|
}
|
|
742
942
|
/**
|
|
743
943
|
* List all registered workflow definitions.
|
|
744
944
|
*/
|
|
745
945
|
async listWorkflowDefinitions() {
|
|
946
|
+
await this.readyPromise;
|
|
746
947
|
return this.workflow.listWorkflowDefinitions();
|
|
747
948
|
}
|
|
949
|
+
/**
|
|
950
|
+
* Register and start a workflow in one call, or start an already-registered workflow by ID.
|
|
951
|
+
*/
|
|
952
|
+
async executeWorkflow(workflowOrId, userId, initialContext) {
|
|
953
|
+
await this.readyPromise;
|
|
954
|
+
if (typeof workflowOrId === 'string') {
|
|
955
|
+
return this.workflow.startWorkflow(workflowOrId, userId, initialContext);
|
|
956
|
+
}
|
|
957
|
+
const definition = await this.workflow.registerWorkflow(workflowOrId);
|
|
958
|
+
return this.workflow.startWorkflow(definition.id, userId, initialContext);
|
|
959
|
+
}
|
|
748
960
|
/**
|
|
749
961
|
* Start a new workflow instance for a user.
|
|
750
962
|
*/
|
|
751
963
|
async startWorkflow(workflowDefinitionId, userId, initialContext) {
|
|
964
|
+
await this.readyPromise;
|
|
752
965
|
return this.workflow.startWorkflow(workflowDefinitionId, userId, initialContext);
|
|
753
966
|
}
|
|
754
967
|
/**
|
|
755
968
|
* Get a workflow instance by ID.
|
|
756
969
|
*/
|
|
757
970
|
async getWorkflowInstance(instanceId) {
|
|
971
|
+
await this.readyPromise;
|
|
758
972
|
return this.workflow.getWorkflowInstance(instanceId);
|
|
759
973
|
}
|
|
760
974
|
/**
|
|
761
975
|
* Get a workflow instance with its snapshot definition.
|
|
762
976
|
*/
|
|
763
977
|
async getWorkflowInstanceWithSnapshot(instanceId) {
|
|
978
|
+
await this.readyPromise;
|
|
764
979
|
return this.workflow.getWorkflowInstanceWithSnapshot(instanceId);
|
|
765
980
|
}
|
|
766
981
|
/**
|
|
767
982
|
* Get all active workflow instances for a user.
|
|
768
983
|
*/
|
|
769
984
|
async getActiveWorkflowsForUser(userId) {
|
|
985
|
+
await this.readyPromise;
|
|
770
986
|
return this.workflow.getActiveWorkflowsForUser(userId);
|
|
771
987
|
}
|
|
772
988
|
/**
|
|
773
989
|
* Cancel a workflow instance.
|
|
774
990
|
*/
|
|
775
991
|
async cancelWorkflow(instanceId) {
|
|
992
|
+
await this.readyPromise;
|
|
776
993
|
return this.workflow.cancelWorkflow(instanceId);
|
|
777
994
|
}
|
|
778
995
|
/**
|
|
@@ -780,12 +997,14 @@ class AssignmentMatcher {
|
|
|
780
997
|
* Should be called periodically.
|
|
781
998
|
*/
|
|
782
999
|
async processExpiredWorkflowSteps() {
|
|
1000
|
+
await this.readyPromise;
|
|
783
1001
|
return this.workflow.processExpiredWorkflowSteps();
|
|
784
1002
|
}
|
|
785
1003
|
/**
|
|
786
1004
|
* Publish a workflow event to the Redis Stream.
|
|
787
1005
|
*/
|
|
788
1006
|
async publishWorkflowEvent(event) {
|
|
1007
|
+
await this.readyPromise;
|
|
789
1008
|
return this.workflow.publishWorkflowEvent(event);
|
|
790
1009
|
}
|
|
791
1010
|
/**
|
|
@@ -793,15 +1012,18 @@ class AssignmentMatcher {
|
|
|
793
1012
|
* This listens to the event stream and processes workflow transitions.
|
|
794
1013
|
*/
|
|
795
1014
|
async startOrchestrator() {
|
|
1015
|
+
await this.readyPromise;
|
|
796
1016
|
return this.workflow.startOrchestrator();
|
|
797
1017
|
}
|
|
798
1018
|
/**
|
|
799
1019
|
* Stop the workflow orchestrator.
|
|
800
1020
|
*/
|
|
801
1021
|
async stopOrchestrator() {
|
|
1022
|
+
await this.readyPromise;
|
|
802
1023
|
return this.workflow.stopOrchestrator();
|
|
803
1024
|
}
|
|
804
1025
|
async processExpiredMatches() {
|
|
1026
|
+
await this.readyPromise;
|
|
805
1027
|
const now = Date.now();
|
|
806
1028
|
const expiredIds = await this.redisClient.zRangeByScore(this.pendingAssignmentsExpiryKey, '-inf', now);
|
|
807
1029
|
for (const id of expiredIds) {
|
|
@@ -815,6 +1037,9 @@ class AssignmentMatcher {
|
|
|
815
1037
|
multi.zRem(this.pendingAssignmentsExpiryKey, id);
|
|
816
1038
|
multi.hDel(this.assignmentOwnerKey, id);
|
|
817
1039
|
await multi.exec();
|
|
1040
|
+
if (this.enableLearning) {
|
|
1041
|
+
await this.learning.applyOutcome(id, 'expire');
|
|
1042
|
+
}
|
|
818
1043
|
// Publish workflow expired event if workflows are enabled
|
|
819
1044
|
if (this.enableWorkflows && owner) {
|
|
820
1045
|
await this.workflow.publishWorkflowEvent({
|
|
@@ -844,6 +1069,97 @@ class AssignmentMatcher {
|
|
|
844
1069
|
this.autoReleaseInterval = null;
|
|
845
1070
|
}
|
|
846
1071
|
}
|
|
1072
|
+
// ============================================================================
|
|
1073
|
+
// Idle User Auto-Rejection (opt-in via idleUserTimeoutMs)
|
|
1074
|
+
// ============================================================================
|
|
1075
|
+
/**
|
|
1076
|
+
* Record activity for a user (heartbeat). Resets the idle clock used by
|
|
1077
|
+
* processIdleUsers(). Called automatically on addUser, acceptAssignment,
|
|
1078
|
+
* and rejectAssignment; consumers can also call it directly as a heartbeat.
|
|
1079
|
+
*/
|
|
1080
|
+
async touchUser(userId) {
|
|
1081
|
+
await this.readyPromise;
|
|
1082
|
+
await this.redisClient.zAdd(this.keys.userActivity(), { score: Date.now(), value: userId });
|
|
1083
|
+
}
|
|
1084
|
+
/**
|
|
1085
|
+
* Detect users that have been idle longer than idleUserTimeoutMs while
|
|
1086
|
+
* holding pending (unactioned) assignments. Idle users are removed from
|
|
1087
|
+
* the matching pool and their pending assignments are requeued for
|
|
1088
|
+
* distribution to other users.
|
|
1089
|
+
*
|
|
1090
|
+
* No-op (returns []) when idleUserTimeoutMs is not configured.
|
|
1091
|
+
*
|
|
1092
|
+
* @returns IDs of users that were removed
|
|
1093
|
+
*/
|
|
1094
|
+
async processIdleUsers() {
|
|
1095
|
+
await this.readyPromise;
|
|
1096
|
+
if (this.idleUserTimeoutMs === null)
|
|
1097
|
+
return [];
|
|
1098
|
+
const cutoff = Date.now() - this.idleUserTimeoutMs;
|
|
1099
|
+
const idleCandidates = await this.redisClient.zRangeByScore(this.keys.userActivity(), '-inf', cutoff);
|
|
1100
|
+
const removed = [];
|
|
1101
|
+
for (const userId of idleCandidates) {
|
|
1102
|
+
// Skip users no longer in the pool (clean up stale activity entry)
|
|
1103
|
+
const exists = await this.redisClient.hExists(this.usersKey, userId);
|
|
1104
|
+
if (!exists) {
|
|
1105
|
+
await this.redisClient.zRem(this.keys.userActivity(), userId);
|
|
1106
|
+
continue;
|
|
1107
|
+
}
|
|
1108
|
+
// Only consider a user idle if they are sitting on unactioned assignments
|
|
1109
|
+
const pendingCount = await this.redisClient.sCard(this.keys.userAssignments(userId));
|
|
1110
|
+
if (pendingCount === 0)
|
|
1111
|
+
continue;
|
|
1112
|
+
await this.releaseUserPendingAssignments(userId);
|
|
1113
|
+
await this.removeUser(userId);
|
|
1114
|
+
removed.push(userId);
|
|
1115
|
+
}
|
|
1116
|
+
return removed;
|
|
1117
|
+
}
|
|
1118
|
+
/**
|
|
1119
|
+
* Requeue all pending assignments currently held by a user.
|
|
1120
|
+
*/
|
|
1121
|
+
async releaseUserPendingAssignments(userId) {
|
|
1122
|
+
const members = await this.redisClient.sMembers(this.keys.userAssignments(userId));
|
|
1123
|
+
const now = Date.now();
|
|
1124
|
+
for (const member of members) {
|
|
1125
|
+
const id = member.split(':')[1];
|
|
1126
|
+
const json = await this.redisClient.hGet(this.pendingAssignmentsKey, id);
|
|
1127
|
+
const multi = this.redisClient.multi();
|
|
1128
|
+
multi.sRem(this.keys.userAssignments(userId), member);
|
|
1129
|
+
multi.hDel(this.pendingAssignmentsKey, id);
|
|
1130
|
+
multi.zRem(this.pendingAssignmentsExpiryKey, id);
|
|
1131
|
+
multi.hDel(this.assignmentOwnerKey, id);
|
|
1132
|
+
await multi.exec();
|
|
1133
|
+
if (this.enableLearning) {
|
|
1134
|
+
await this.learning.applyOutcome(id, 'expire');
|
|
1135
|
+
}
|
|
1136
|
+
if (this.enableWorkflows) {
|
|
1137
|
+
await this.workflow.publishWorkflowEvent({
|
|
1138
|
+
eventId: (0, crypto_1.randomUUID)(),
|
|
1139
|
+
type: 'EXPIRED',
|
|
1140
|
+
userId,
|
|
1141
|
+
assignmentId: id,
|
|
1142
|
+
timestamp: now,
|
|
1143
|
+
});
|
|
1144
|
+
}
|
|
1145
|
+
if (json) {
|
|
1146
|
+
await this.addAssignment(JSON.parse(json));
|
|
1147
|
+
}
|
|
1148
|
+
}
|
|
1149
|
+
}
|
|
1150
|
+
startIdleUserInterval(intervalMs = 10000) {
|
|
1151
|
+
if (this.idleUserInterval)
|
|
1152
|
+
return;
|
|
1153
|
+
this.idleUserInterval = setInterval(() => {
|
|
1154
|
+
this.processIdleUsers().catch(console.error);
|
|
1155
|
+
}, intervalMs);
|
|
1156
|
+
}
|
|
1157
|
+
stopIdleUserInterval() {
|
|
1158
|
+
if (this.idleUserInterval) {
|
|
1159
|
+
clearInterval(this.idleUserInterval);
|
|
1160
|
+
this.idleUserInterval = null;
|
|
1161
|
+
}
|
|
1162
|
+
}
|
|
847
1163
|
/**
|
|
848
1164
|
* Get assignments specifically targeted at a user through active workflows.
|
|
849
1165
|
* These take priority over general pool assignments for deterministic matching.
|