assignment-user-matcher 1.2.1 → 1.2.3
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 +609 -5
- package/dist/index.d.ts +7 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +13 -1
- package/dist/learning/auto-weights.d.ts +31 -0
- package/dist/learning/auto-weights.d.ts.map +1 -0
- package/dist/learning/auto-weights.js +65 -0
- 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/lua/workflow-transition.lua +29 -0
- package/dist/managers/LearningManager.d.ts +129 -0
- package/dist/managers/LearningManager.d.ts.map +1 -0
- package/dist/managers/LearningManager.js +269 -0
- package/dist/managers/ReliabilityManager.d.ts +60 -2
- package/dist/managers/ReliabilityManager.d.ts.map +1 -1
- package/dist/managers/ReliabilityManager.js +190 -9
- package/dist/managers/TelemetryManager.d.ts.map +1 -1
- package/dist/managers/WorkflowManager.d.ts +80 -6
- package/dist/managers/WorkflowManager.d.ts.map +1 -1
- package/dist/managers/WorkflowManager.js +464 -81
- package/dist/matcher.class.d.ts +180 -13
- package/dist/matcher.class.d.ts.map +1 -1
- package/dist/matcher.class.js +632 -46
- package/dist/queries/pagination.d.ts.map +1 -1
- package/dist/queries/pagination.js +9 -6
- package/dist/scoring/match-score.d.ts.map +1 -1
- package/dist/scoring/match-score.js +1 -1
- package/dist/types/matcher.d.ts +258 -9
- package/dist/types/matcher.d.ts.map +1 -1
- package/dist/utils/geo.d.ts +26 -0
- package/dist/utils/geo.d.ts.map +1 -0
- package/dist/utils/geo.js +62 -0
- package/dist/utils/keys.d.ts +15 -0
- package/dist/utils/keys.d.ts.map +1 -1
- package/dist/utils/keys.js +17 -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
|
@@ -4,9 +4,12 @@ const crypto_1 = require("crypto");
|
|
|
4
4
|
const fs_1 = require("fs");
|
|
5
5
|
const path_1 = require("path");
|
|
6
6
|
const cidr_1 = require("./utils/cidr");
|
|
7
|
+
const geo_1 = require("./utils/geo");
|
|
7
8
|
const keys_1 = require("./utils/keys");
|
|
8
9
|
const pagination_1 = require("./queries/pagination");
|
|
9
10
|
const match_score_1 = require("./scoring/match-score");
|
|
11
|
+
const features_1 = require("./learning/features");
|
|
12
|
+
const LearningManager_1 = require("./managers/LearningManager");
|
|
10
13
|
const ReliabilityManager_1 = require("./managers/ReliabilityManager");
|
|
11
14
|
const TelemetryManager_1 = require("./managers/TelemetryManager");
|
|
12
15
|
const WorkflowManager_1 = require("./managers/WorkflowManager");
|
|
@@ -32,6 +35,7 @@ class AssignmentMatcher {
|
|
|
32
35
|
this.redisClient = redisClient;
|
|
33
36
|
this.luaScriptSha = null;
|
|
34
37
|
this.autoReleaseInterval = null;
|
|
38
|
+
this.idleUserInterval = null;
|
|
35
39
|
this.relevantBatchSize = options?.relevantBatchSize ?? 50;
|
|
36
40
|
this.enableDefaultMatching = options?.enableDefaultMatching ?? true;
|
|
37
41
|
this.redisPrefix = options?.redisPrefix ?? '';
|
|
@@ -42,6 +46,7 @@ class AssignmentMatcher {
|
|
|
42
46
|
this.assignmentsRefKey = this.keys.assignmentsRef();
|
|
43
47
|
this.maxUserBacklogSize = options?.maxUserBacklogSize ?? 9;
|
|
44
48
|
this.matchExpirationMs = options?.matchExpirationMs ?? 60000;
|
|
49
|
+
this.idleUserTimeoutMs = options?.idleUserTimeoutMs ?? null;
|
|
45
50
|
this.pendingAssignmentsKey = this.keys.pendingAssignmentsData();
|
|
46
51
|
this.pendingAssignmentsExpiryKey = this.keys.pendingAssignmentsExpiry();
|
|
47
52
|
this.assignmentOwnerKey = this.keys.assignmentOwner();
|
|
@@ -51,6 +56,10 @@ class AssignmentMatcher {
|
|
|
51
56
|
this.calculatePriority = options?.prioritizationFunction ?? this.calculatePriority;
|
|
52
57
|
this.usingDefaultMatchScore = !options?.matchingFunction;
|
|
53
58
|
this.matchScore = options?.matchingFunction ?? this.defaultMatchScore.bind(this);
|
|
59
|
+
this.enableGeoMatching = options?.enableGeoMatching ?? false;
|
|
60
|
+
this.geoDefaultMaxDistanceKm = options?.geoDefaultMaxDistanceKm;
|
|
61
|
+
this.geoScoreWeight = options?.geoScoreWeight ?? 0;
|
|
62
|
+
this.geoMatchingFunction = options?.geoMatchingFunction;
|
|
54
63
|
// Workflow options
|
|
55
64
|
this.enableWorkflows = options?.enableWorkflows ?? false;
|
|
56
65
|
this.streamConsumerGroup = options?.streamConsumerGroup ?? 'orchestrator';
|
|
@@ -64,16 +73,41 @@ class AssignmentMatcher {
|
|
|
64
73
|
workflowAuditEnabled: options?.workflowAuditEnabled ?? false,
|
|
65
74
|
workflowSnapshotDefinitions: options?.workflowSnapshotDefinitions ?? true,
|
|
66
75
|
streamConsumerName: this.streamConsumerName,
|
|
76
|
+
circuitBreakerPersistState: options?.circuitBreakerPersistState ?? false,
|
|
77
|
+
circuitBreakerShared: options?.circuitBreakerShared ?? false,
|
|
78
|
+
enableReliabilityMetrics: options?.enableReliabilityMetrics ?? true,
|
|
79
|
+
deadLetterQueueAlertThreshold: options?.deadLetterQueueAlertThreshold ?? 100,
|
|
67
80
|
});
|
|
68
81
|
this.telemetry = new TelemetryManager_1.TelemetryManager(options?.enableOpenTelemetry ?? false);
|
|
82
|
+
// Learning layer (opt-in contextual bandit re-ranking)
|
|
83
|
+
this.enableLearning = options?.enableLearning ?? false;
|
|
84
|
+
this.enableAutoRoutingWeights = options?.enableAutoRoutingWeights ?? false;
|
|
85
|
+
this.learningFeatureExtractor = options?.learningFeatureExtractor ?? features_1.extractMatchFeatures;
|
|
86
|
+
this.learning = new LearningManager_1.LearningManager(this.redisClient, this.keys, {
|
|
87
|
+
learningRate: options?.learningRate,
|
|
88
|
+
explorationRate: options?.learningExplorationRate,
|
|
89
|
+
shadowMode: options?.learningShadowMode,
|
|
90
|
+
boostFactor: options?.learningBoostFactor,
|
|
91
|
+
rewards: options?.learningRewards,
|
|
92
|
+
decisionTtlMs: options?.learningDecisionTtlMs,
|
|
93
|
+
signalWeights: options?.learningSignalWeights,
|
|
94
|
+
feedbackTtlMs: options?.learningFeedbackTtlMs,
|
|
95
|
+
trackTagStats: this.enableAutoRoutingWeights,
|
|
96
|
+
autoWeights: options?.autoRoutingWeights,
|
|
97
|
+
});
|
|
69
98
|
this.workflow = new WorkflowManager_1.WorkflowManager(this.redisClient, this.keys, this.reliability, this.telemetry, this, {
|
|
70
99
|
enableWorkflows: this.enableWorkflows,
|
|
71
100
|
streamConsumerGroup: this.streamConsumerGroup,
|
|
72
101
|
streamConsumerName: this.streamConsumerName,
|
|
73
102
|
reclaimIntervalMs: options?.workflowReclaimPollIntervalMs ?? 5000,
|
|
74
103
|
reclaimMinIdleMs: options?.workflowOrphanReclaimMs ?? 60000,
|
|
104
|
+
retentionMs: options?.workflowInstanceRetentionMs,
|
|
105
|
+
retryBackoffMs: options?.workflowRetryBackoffMs,
|
|
106
|
+
eventBatchSize: options?.workflowEventBatchSize,
|
|
107
|
+
pollBlockMs: options?.workflowPollBlockMs,
|
|
108
|
+
maxEventsPerSecond: options?.workflowMaxEventsPerSecond,
|
|
75
109
|
});
|
|
76
|
-
this.initRedis();
|
|
110
|
+
this.readyPromise = this.initRedis();
|
|
77
111
|
}
|
|
78
112
|
/** Keys for the three assignment stores (used by pagination queries) */
|
|
79
113
|
get assignmentStoreKeys() {
|
|
@@ -89,6 +123,8 @@ class AssignmentMatcher {
|
|
|
89
123
|
if (!this.redisClient.isOpen) {
|
|
90
124
|
await this.redisClient.connect();
|
|
91
125
|
}
|
|
126
|
+
// Initialize reliability manager (load persisted circuit breaker state if enabled)
|
|
127
|
+
await this.reliability.init();
|
|
92
128
|
// Initialize workflow stream consumer group if workflows are enabled
|
|
93
129
|
if (this.enableWorkflows) {
|
|
94
130
|
await this.workflow.init();
|
|
@@ -97,6 +133,12 @@ class AssignmentMatcher {
|
|
|
97
133
|
}
|
|
98
134
|
return this;
|
|
99
135
|
}
|
|
136
|
+
/**
|
|
137
|
+
* Wait until the matcher has connected and initialized workflow internals.
|
|
138
|
+
*/
|
|
139
|
+
async waitUntilReady() {
|
|
140
|
+
return this.readyPromise;
|
|
141
|
+
}
|
|
100
142
|
/**
|
|
101
143
|
* Load Lua scripts into Redis for atomic operations.
|
|
102
144
|
*/
|
|
@@ -112,27 +154,32 @@ class AssignmentMatcher {
|
|
|
112
154
|
}
|
|
113
155
|
}
|
|
114
156
|
async atomicWorkflowTransition(instanceId, expectedVersion, newStatus, newStepId, updatedContext, historyEntry) {
|
|
157
|
+
await this.readyPromise;
|
|
115
158
|
return this.workflow.atomicWorkflowTransition(instanceId, expectedVersion, newStatus, newStepId, updatedContext, historyEntry);
|
|
116
159
|
}
|
|
117
160
|
async reclaimOrphanedMessages() {
|
|
161
|
+
await this.readyPromise;
|
|
118
162
|
return this.workflow.reclaimOrphanedMessages();
|
|
119
163
|
}
|
|
120
164
|
/**
|
|
121
165
|
* Get events from the Dead Letter Queue.
|
|
122
166
|
*/
|
|
123
167
|
async getDeadLetterEvents(limit = 100, offset = 0) {
|
|
168
|
+
await this.readyPromise;
|
|
124
169
|
return this.reliability.getDeadLetterEvents(limit, offset);
|
|
125
170
|
}
|
|
126
171
|
/**
|
|
127
172
|
* Get Dead Letter Queue size.
|
|
128
173
|
*/
|
|
129
174
|
async getDeadLetterQueueSize() {
|
|
175
|
+
await this.readyPromise;
|
|
130
176
|
return this.reliability.getDeadLetterQueueSize();
|
|
131
177
|
}
|
|
132
178
|
/**
|
|
133
179
|
* Replay a Dead Letter Queue event.
|
|
134
180
|
*/
|
|
135
181
|
async replayDeadLetterEvent(eventJson) {
|
|
182
|
+
await this.readyPromise;
|
|
136
183
|
const entry = JSON.parse(eventJson);
|
|
137
184
|
// Reset retry count
|
|
138
185
|
await this.redisClient.del(this.keys.eventRetryCount(entry.event.eventId));
|
|
@@ -146,15 +193,226 @@ class AssignmentMatcher {
|
|
|
146
193
|
* Clear all events from the Dead Letter Queue.
|
|
147
194
|
*/
|
|
148
195
|
async clearDeadLetterQueue() {
|
|
196
|
+
await this.readyPromise;
|
|
149
197
|
return this.reliability.clearDeadLetterQueue();
|
|
150
198
|
}
|
|
151
199
|
/**
|
|
152
200
|
* Get audit events from the audit stream.
|
|
153
201
|
*/
|
|
154
202
|
async getAuditEvents(count = 100) {
|
|
203
|
+
await this.readyPromise;
|
|
155
204
|
return this.reliability.getAuditEvents(count);
|
|
156
205
|
}
|
|
157
206
|
// ============================================================================
|
|
207
|
+
// Reliability & Health Check Methods
|
|
208
|
+
// ============================================================================
|
|
209
|
+
/**
|
|
210
|
+
* Get comprehensive reliability metrics including circuit breaker state,
|
|
211
|
+
* Dead Letter Queue size, and Redis health status.
|
|
212
|
+
*/
|
|
213
|
+
async getReliabilityMetrics() {
|
|
214
|
+
await this.readyPromise;
|
|
215
|
+
return this.reliability.getMetrics();
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* Get current circuit breaker state
|
|
219
|
+
*/
|
|
220
|
+
async getCircuitBreakerState() {
|
|
221
|
+
await this.readyPromise;
|
|
222
|
+
return this.reliability.getCircuitBreakerState();
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* Check if Dead Letter Queue size exceeds alert threshold
|
|
226
|
+
*/
|
|
227
|
+
async checkDeadLetterQueueAlert() {
|
|
228
|
+
await this.readyPromise;
|
|
229
|
+
return this.reliability.checkDeadLetterQueueAlert();
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* Perform a health check on Redis connection
|
|
233
|
+
* Returns true if Redis is healthy, false otherwise
|
|
234
|
+
*/
|
|
235
|
+
async healthCheck() {
|
|
236
|
+
await this.readyPromise;
|
|
237
|
+
const details = {
|
|
238
|
+
timestamp: Date.now(),
|
|
239
|
+
};
|
|
240
|
+
try {
|
|
241
|
+
// Check if Redis client is connected
|
|
242
|
+
details.redisConnected = this.redisClient.isOpen;
|
|
243
|
+
// Try to ping Redis
|
|
244
|
+
const pingResult = await this.redisClient.ping();
|
|
245
|
+
details.redisPing = pingResult;
|
|
246
|
+
// Get reliability metrics
|
|
247
|
+
const metrics = await this.getReliabilityMetrics();
|
|
248
|
+
details.circuitBreakerState = metrics.circuitBreakerState;
|
|
249
|
+
details.deadLetterQueueSize = metrics.deadLetterQueueSize;
|
|
250
|
+
details.circuitBreakerAllowingRequests = metrics.circuitBreakerAllowingRequests;
|
|
251
|
+
// Check if circuit breaker is allowing requests
|
|
252
|
+
const healthy = details.redisConnected && pingResult === 'PONG' && details.circuitBreakerAllowingRequests;
|
|
253
|
+
return {
|
|
254
|
+
healthy,
|
|
255
|
+
details,
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
catch (err) {
|
|
259
|
+
details.error = err instanceof Error ? err.message : String(err);
|
|
260
|
+
return {
|
|
261
|
+
healthy: false,
|
|
262
|
+
details,
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
// ============================================================================
|
|
267
|
+
// Learning (Contextual Bandit) Methods
|
|
268
|
+
// ============================================================================
|
|
269
|
+
/**
|
|
270
|
+
* Get the learned model weights (feature -> weight).
|
|
271
|
+
*/
|
|
272
|
+
async getLearningModel() {
|
|
273
|
+
await this.readyPromise;
|
|
274
|
+
return this.learning.getModel();
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* Get aggregate learning statistics (decisions, rewards, average reward).
|
|
278
|
+
*/
|
|
279
|
+
async getLearningStats() {
|
|
280
|
+
await this.readyPromise;
|
|
281
|
+
return this.learning.getStats();
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* Apply a manual reward to a matched assignment's decision context.
|
|
285
|
+
* Enables custom reward shaping beyond the built-in lifecycle outcomes.
|
|
286
|
+
* Returns false when no decision context exists for the assignment.
|
|
287
|
+
*/
|
|
288
|
+
async recordLearningReward(assignmentId, reward) {
|
|
289
|
+
await this.readyPromise;
|
|
290
|
+
return this.learning.recordReward(assignmentId, reward);
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* Feed external post-processing signals into the model for an assignment
|
|
294
|
+
* (e.g. { accuracy: 0.95, csat: 0.8 }). Works for live decisions and for
|
|
295
|
+
* archived episodes of already-completed assignments (within the feedback TTL).
|
|
296
|
+
* Signal values are weighted via the `learningSignalWeights` option (default 1).
|
|
297
|
+
* Returns false when no learning context exists for the assignment.
|
|
298
|
+
*/
|
|
299
|
+
async recordLearningFeedback(assignmentId, signals) {
|
|
300
|
+
await this.readyPromise;
|
|
301
|
+
return this.learning.recordFeedback(assignmentId, signals);
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* Train the model directly with raw (features, reward) samples from an
|
|
305
|
+
* external pipeline (offline evaluation jobs, historical data imports).
|
|
306
|
+
* Returns the number of samples applied.
|
|
307
|
+
*/
|
|
308
|
+
async trainLearningSamples(samples) {
|
|
309
|
+
await this.readyPromise;
|
|
310
|
+
return this.learning.trainSamples(samples);
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
* Reset the learned model weights and statistics.
|
|
314
|
+
*/
|
|
315
|
+
async resetLearningModel() {
|
|
316
|
+
await this.readyPromise;
|
|
317
|
+
return this.learning.resetModel();
|
|
318
|
+
}
|
|
319
|
+
/**
|
|
320
|
+
* Toggle learning shadow mode at runtime without losing model/state.
|
|
321
|
+
*
|
|
322
|
+
* `true`: learn-only, ranking unaffected.
|
|
323
|
+
* `false`: learning predictions can influence ranking.
|
|
324
|
+
*/
|
|
325
|
+
async setLearningShadowMode(enabled) {
|
|
326
|
+
await this.readyPromise;
|
|
327
|
+
this.learning.setShadowMode(enabled);
|
|
328
|
+
}
|
|
329
|
+
/** Current runtime shadow mode state. */
|
|
330
|
+
async getLearningShadowMode() {
|
|
331
|
+
await this.readyPromise;
|
|
332
|
+
return this.learning.shadowMode;
|
|
333
|
+
}
|
|
334
|
+
// ============================================================================
|
|
335
|
+
// Auto Routing Weights (RL-generated tags/weights)
|
|
336
|
+
// ============================================================================
|
|
337
|
+
/**
|
|
338
|
+
* Per-user, per-tag reward statistics aggregated from learned outcomes.
|
|
339
|
+
* Requires `enableLearning` and `enableAutoRoutingWeights`.
|
|
340
|
+
*/
|
|
341
|
+
async getLearnedTagStats(userId) {
|
|
342
|
+
await this.readyPromise;
|
|
343
|
+
return this.learning.getUserTagStats(userId);
|
|
344
|
+
}
|
|
345
|
+
/**
|
|
346
|
+
* Synthesize a routingWeights map for a user from learned tag statistics
|
|
347
|
+
* using a UCB1 bandit policy: high weights for rewarding tags, weight 0
|
|
348
|
+
* (hard veto) for consistently bad tags, and optimistic priors for
|
|
349
|
+
* under-explored tags. Does not persist anything.
|
|
350
|
+
*
|
|
351
|
+
* @param opts.includeUnexploredTags also assign the exploration prior to
|
|
352
|
+
* every known tag in the system the user has no data for yet
|
|
353
|
+
*/
|
|
354
|
+
async getLearnedRoutingWeights(userId, opts) {
|
|
355
|
+
await this.readyPromise;
|
|
356
|
+
const knownTags = opts?.includeUnexploredTags ? await this.getKnownTagsForAutoWeights() : undefined;
|
|
357
|
+
const userJson = await this.redisClient.hGet(this.usersKey, userId);
|
|
358
|
+
const existingWeights = userJson ? JSON.parse(userJson).routingWeights : undefined;
|
|
359
|
+
return this.learning.getLearnedRoutingWeights(userId, knownTags, existingWeights);
|
|
360
|
+
}
|
|
361
|
+
/**
|
|
362
|
+
* Apply learned routing weights to one user (or every tracked user when
|
|
363
|
+
* no id is given), automating tags/weights generation from RL outcomes.
|
|
364
|
+
*
|
|
365
|
+
* Merge semantics: learned tags always take their learned value; manual
|
|
366
|
+
* routingWeights entries for tags the learner has no data on are
|
|
367
|
+
* preserved (set `opts.overrideManual` to replace the map entirely).
|
|
368
|
+
* The applied learned map is stored on the user as `learnedRoutingWeights`
|
|
369
|
+
* for observability.
|
|
370
|
+
*
|
|
371
|
+
* Returns the applied weights per user id.
|
|
372
|
+
*/
|
|
373
|
+
async syncLearnedRoutingWeights(userId, opts) {
|
|
374
|
+
await this.readyPromise;
|
|
375
|
+
const targets = userId ? [userId] : await this.learning.listTrackedUsers();
|
|
376
|
+
const knownTags = opts?.includeUnexploredTags ? await this.getKnownTagsForAutoWeights() : undefined;
|
|
377
|
+
const applied = {};
|
|
378
|
+
for (const id of targets) {
|
|
379
|
+
const userJson = await this.redisClient.hGet(this.usersKey, id);
|
|
380
|
+
if (!userJson)
|
|
381
|
+
continue;
|
|
382
|
+
const user = JSON.parse(userJson);
|
|
383
|
+
// Pass the user's current routingWeights as warm per-tag priors
|
|
384
|
+
// so under-sampled tags start from the existing value rather than
|
|
385
|
+
// the flat priorWeight.
|
|
386
|
+
const previousLearned = user.learnedRoutingWeights ?? {};
|
|
387
|
+
const existingForSynthesis = user.routingWeights
|
|
388
|
+
? Object.fromEntries(Object.entries(user.routingWeights).filter(([tag]) => !(tag in previousLearned)))
|
|
389
|
+
: undefined;
|
|
390
|
+
const learned = await this.learning.getLearnedRoutingWeights(id, knownTags, existingForSynthesis);
|
|
391
|
+
if (Object.keys(learned).length === 0)
|
|
392
|
+
continue;
|
|
393
|
+
let routingWeights;
|
|
394
|
+
if (opts?.overrideManual) {
|
|
395
|
+
routingWeights = learned;
|
|
396
|
+
}
|
|
397
|
+
else {
|
|
398
|
+
const manualEntries = {};
|
|
399
|
+
for (const [tag, weight] of Object.entries(user.routingWeights ?? {})) {
|
|
400
|
+
if (!(tag in previousLearned) && !(tag in learned))
|
|
401
|
+
manualEntries[tag] = weight;
|
|
402
|
+
}
|
|
403
|
+
routingWeights = { ...manualEntries, ...learned };
|
|
404
|
+
}
|
|
405
|
+
await this.redisClient.hSet(this.usersKey, id, JSON.stringify({ ...user, routingWeights, learnedRoutingWeights: learned }));
|
|
406
|
+
applied[id] = routingWeights;
|
|
407
|
+
}
|
|
408
|
+
return applied;
|
|
409
|
+
}
|
|
410
|
+
/** All known tags except the internal 'default' tag (for exploration priors) */
|
|
411
|
+
async getKnownTagsForAutoWeights() {
|
|
412
|
+
const tags = await this.redisClient.sMembers(this.allTagsKey);
|
|
413
|
+
return tags.filter((t) => t !== 'default');
|
|
414
|
+
}
|
|
415
|
+
// ============================================================================
|
|
158
416
|
// OpenTelemetry Tracing Hooks
|
|
159
417
|
// ============================================================================
|
|
160
418
|
/**
|
|
@@ -183,13 +441,16 @@ class AssignmentMatcher {
|
|
|
183
441
|
}
|
|
184
442
|
}
|
|
185
443
|
async addUser(user) {
|
|
444
|
+
await this.readyPromise;
|
|
186
445
|
await this.redisClient.hSet(this.usersKey, user.id, JSON.stringify({
|
|
187
446
|
...user,
|
|
188
447
|
tags: [...user.tags, ...(this.enableDefaultMatching ? ['default'] : [])],
|
|
189
448
|
}));
|
|
449
|
+
await this.touchUser(user.id);
|
|
190
450
|
return user;
|
|
191
451
|
}
|
|
192
452
|
async addAssignment(assignment) {
|
|
453
|
+
await this.readyPromise;
|
|
193
454
|
let { id, tags, priority, latitude, longitude } = assignment;
|
|
194
455
|
if (!priority)
|
|
195
456
|
priority = await this.calculatePriority(assignment);
|
|
@@ -206,7 +467,7 @@ class AssignmentMatcher {
|
|
|
206
467
|
score: priority,
|
|
207
468
|
value: id,
|
|
208
469
|
});
|
|
209
|
-
if (latitude && longitude) {
|
|
470
|
+
if ((0, geo_1.isValidLatitude)(latitude) && (0, geo_1.isValidLongitude)(longitude)) {
|
|
210
471
|
multi.geoAdd(assignmentGeoKey, {
|
|
211
472
|
longitude,
|
|
212
473
|
latitude,
|
|
@@ -227,13 +488,14 @@ class AssignmentMatcher {
|
|
|
227
488
|
return assignment;
|
|
228
489
|
}
|
|
229
490
|
async removeAssignment(id) {
|
|
491
|
+
await this.readyPromise;
|
|
230
492
|
const assignmentPriorityKey = this.keys.assignmentPriority(id);
|
|
231
493
|
const assignmentTagsKey = this.keys.assignmentTags(id);
|
|
232
494
|
const assignmentGeoKey = this.keys.assignmentsGeo();
|
|
233
495
|
// Fetch tags and owner in case it's pending
|
|
234
496
|
const [tagsCsv, owner] = await Promise.all([
|
|
235
497
|
this.redisClient.hGet(assignmentTagsKey, 'tags'),
|
|
236
|
-
this.redisClient.hGet(this.assignmentOwnerKey, id)
|
|
498
|
+
this.redisClient.hGet(this.assignmentOwnerKey, id),
|
|
237
499
|
]);
|
|
238
500
|
let tags = [];
|
|
239
501
|
if (tagsCsv && tagsCsv.length > 0) {
|
|
@@ -262,10 +524,12 @@ class AssignmentMatcher {
|
|
|
262
524
|
return id;
|
|
263
525
|
}
|
|
264
526
|
async removeUser(userId) {
|
|
527
|
+
await this.readyPromise;
|
|
265
528
|
const multi = this.redisClient
|
|
266
529
|
.multi()
|
|
267
530
|
.del(this.keys.userAssignments(userId))
|
|
268
531
|
.del(this.keys.userRejected(userId))
|
|
532
|
+
.zRem(this.keys.userActivity(), userId)
|
|
269
533
|
.hDel(this.usersKey, userId);
|
|
270
534
|
await multi.exec();
|
|
271
535
|
return userId;
|
|
@@ -275,18 +539,17 @@ class AssignmentMatcher {
|
|
|
275
539
|
* For large datasets, prefer using getAssignmentsPaginated() instead.
|
|
276
540
|
*/
|
|
277
541
|
async getAllAssignments() {
|
|
542
|
+
await this.readyPromise;
|
|
278
543
|
return (0, pagination_1.getAllAssignmentsFromStores)(this.redisClient, this.assignmentStoreKeys);
|
|
279
544
|
}
|
|
280
545
|
/**
|
|
281
546
|
* Get assignments with pagination support for efficient querying of large datasets.
|
|
282
547
|
* Uses cursor-based pagination across statuses.
|
|
283
548
|
*
|
|
284
|
-
* @param options
|
|
285
|
-
* @param options.limit - Maximum number of assignments to return per page (default: 100)
|
|
286
|
-
* @param options.status - Filter by status: 'queued' | 'pending' | 'accepted' | 'all' (default: 'all')
|
|
287
|
-
* @param options.includeTotal - Whether to include total count (slower for large datasets)
|
|
549
|
+
* @param options - Pagination options.
|
|
288
550
|
*/
|
|
289
551
|
async getAssignmentsPaginated(options) {
|
|
552
|
+
await this.readyPromise;
|
|
290
553
|
return (0, pagination_1.getAssignmentsPaginatedFromStores)(this.redisClient, this.assignmentStoreKeys, options);
|
|
291
554
|
}
|
|
292
555
|
/**
|
|
@@ -294,24 +557,93 @@ class AssignmentMatcher {
|
|
|
294
557
|
* Efficient for dashboards and monitoring.
|
|
295
558
|
*/
|
|
296
559
|
async getAssignmentCounts() {
|
|
560
|
+
await this.readyPromise;
|
|
297
561
|
return (0, pagination_1.getAssignmentCountsFromStores)(this.redisClient, this.assignmentStoreKeys);
|
|
298
562
|
}
|
|
299
563
|
/**
|
|
300
564
|
* Get a single assignment by ID from any status.
|
|
301
565
|
*/
|
|
302
566
|
async getAssignment(id) {
|
|
567
|
+
await this.readyPromise;
|
|
303
568
|
return (0, pagination_1.getAssignmentById)(this.redisClient, this.assignmentStoreKeys, id);
|
|
304
569
|
}
|
|
305
570
|
/**
|
|
306
571
|
* Get multiple assignments by IDs efficiently.
|
|
307
572
|
*/
|
|
308
573
|
async getAssignmentsByIds(ids) {
|
|
574
|
+
await this.readyPromise;
|
|
309
575
|
return (0, pagination_1.getAssignmentsByIdsBatch)(this.redisClient, this.assignmentStoreKeys, ids);
|
|
310
576
|
}
|
|
577
|
+
/**
|
|
578
|
+
* Get all pending assignments with owner and pending duration metadata.
|
|
579
|
+
*/
|
|
580
|
+
async getPendingAssignmentsWithAge() {
|
|
581
|
+
await this.readyPromise;
|
|
582
|
+
const now = Date.now();
|
|
583
|
+
const pendingEntries = await this.redisClient.hGetAll(this.pendingAssignmentsKey);
|
|
584
|
+
const assignmentIds = Object.keys(pendingEntries);
|
|
585
|
+
if (assignmentIds.length === 0) {
|
|
586
|
+
return [];
|
|
587
|
+
}
|
|
588
|
+
const [owners, expiryScores] = await Promise.all([
|
|
589
|
+
this.redisClient.hmGet(this.assignmentOwnerKey, assignmentIds),
|
|
590
|
+
Promise.all(assignmentIds.map((id) => this.redisClient.zScore(this.pendingAssignmentsExpiryKey, id))),
|
|
591
|
+
]);
|
|
592
|
+
const results = [];
|
|
593
|
+
for (let i = 0; i < assignmentIds.length; i++) {
|
|
594
|
+
const id = assignmentIds[i];
|
|
595
|
+
const json = pendingEntries[id];
|
|
596
|
+
if (!json)
|
|
597
|
+
continue;
|
|
598
|
+
let assignment;
|
|
599
|
+
try {
|
|
600
|
+
assignment = JSON.parse(json);
|
|
601
|
+
}
|
|
602
|
+
catch {
|
|
603
|
+
continue;
|
|
604
|
+
}
|
|
605
|
+
const score = expiryScores[i];
|
|
606
|
+
const expiresAt = score === null ? null : Number(score);
|
|
607
|
+
const pendingSince = expiresAt === null ? null : expiresAt - this.matchExpirationMs;
|
|
608
|
+
const pendingForMs = pendingSince === null ? null : Math.max(0, now - pendingSince);
|
|
609
|
+
results.push({
|
|
610
|
+
assignment,
|
|
611
|
+
ownerId: owners[i] ?? null,
|
|
612
|
+
pendingForMs,
|
|
613
|
+
pendingSince,
|
|
614
|
+
expiresAt,
|
|
615
|
+
});
|
|
616
|
+
}
|
|
617
|
+
results.sort((a, b) => (b.pendingForMs ?? -1) - (a.pendingForMs ?? -1));
|
|
618
|
+
return results;
|
|
619
|
+
}
|
|
311
620
|
/** Default match score implementation using extracted scoring module */
|
|
312
621
|
defaultMatchScore(user, assignmentTags, assignmentPriority, _assignmentId, skillThresholds) {
|
|
313
622
|
return Promise.resolve((0, match_score_1.calculateMatchScore)(user, assignmentTags, assignmentPriority, this.enableDefaultMatching, skillThresholds));
|
|
314
623
|
}
|
|
624
|
+
async evaluateGeoMatch(user, assignment) {
|
|
625
|
+
if (this.geoMatchingFunction) {
|
|
626
|
+
return this.geoMatchingFunction({
|
|
627
|
+
user,
|
|
628
|
+
assignment,
|
|
629
|
+
defaultMaxDistanceKm: this.geoDefaultMaxDistanceKm,
|
|
630
|
+
});
|
|
631
|
+
}
|
|
632
|
+
return (0, geo_1.checkGeoMatch)(user, assignment, {
|
|
633
|
+
enabled: this.enableGeoMatching,
|
|
634
|
+
defaultMaxDistanceKm: this.geoDefaultMaxDistanceKm,
|
|
635
|
+
});
|
|
636
|
+
}
|
|
637
|
+
calculateGeoBoost(geoMatch) {
|
|
638
|
+
if (!this.enableGeoMatching || this.geoScoreWeight <= 0)
|
|
639
|
+
return 0;
|
|
640
|
+
if (typeof geoMatch.distanceKm !== 'number' || typeof geoMatch.effectiveMaxDistanceKm !== 'number')
|
|
641
|
+
return 0;
|
|
642
|
+
if (geoMatch.effectiveMaxDistanceKm <= 0)
|
|
643
|
+
return 0;
|
|
644
|
+
const ratio = 1 - geoMatch.distanceKm / geoMatch.effectiveMaxDistanceKm;
|
|
645
|
+
return this.geoScoreWeight * Math.max(0, ratio);
|
|
646
|
+
}
|
|
315
647
|
async calculatePriority(...args) {
|
|
316
648
|
const [assignment] = args;
|
|
317
649
|
return (0, match_score_1.calculateDefaultPriority)(assignment?.createdAt);
|
|
@@ -345,11 +677,11 @@ class AssignmentMatcher {
|
|
|
345
677
|
const assignmentPriorityKey = this.keys.assignmentPriority(id);
|
|
346
678
|
// Fetch tags to update per-tag indices
|
|
347
679
|
const assignmentTagsKey = this.keys.assignmentTags(id);
|
|
348
|
-
const [existsRef, tagsCsv] = await this.redisClient
|
|
680
|
+
const [existsRef, tagsCsv] = (await this.redisClient
|
|
349
681
|
.multi()
|
|
350
682
|
.hExists(this.assignmentsRefKey, id)
|
|
351
683
|
.hGet(assignmentTagsKey, 'tags')
|
|
352
|
-
.exec();
|
|
684
|
+
.exec());
|
|
353
685
|
const tags = (tagsCsv && tagsCsv.length > 0 ? tagsCsv.split(',') : []);
|
|
354
686
|
const multi = this.redisClient.multi();
|
|
355
687
|
multi.hSet(assignmentPriorityKey, 'priority', priority);
|
|
@@ -404,6 +736,10 @@ class AssignmentMatcher {
|
|
|
404
736
|
}
|
|
405
737
|
}
|
|
406
738
|
}
|
|
739
|
+
// Workflow-targeted assignments above are deterministically targeted at this
|
|
740
|
+
// user (not drawn from the shared tag pool below), so the claim-race filtering
|
|
741
|
+
// at the end of this function must never strip them out.
|
|
742
|
+
const workflowTargetedCount = userAssignments.length;
|
|
407
743
|
// Priority 2: Build candidate assignments using per-tag zset union with user weights for scalability.
|
|
408
744
|
const positiveWeights = [];
|
|
409
745
|
const zeroWeightTags = [];
|
|
@@ -450,7 +786,7 @@ class AssignmentMatcher {
|
|
|
450
786
|
const rejectedKey = this.keys.userRejected(user.id);
|
|
451
787
|
const unionKeysWithWeights = expandedPositive.map((pw) => ({
|
|
452
788
|
key: this.keys.tagAssignments(pw.tag),
|
|
453
|
-
weight: pw.weight
|
|
789
|
+
weight: pw.weight,
|
|
454
790
|
}));
|
|
455
791
|
const multi = this.redisClient.multi();
|
|
456
792
|
// Weighted union of positive tag assignment zsets
|
|
@@ -486,7 +822,7 @@ class AssignmentMatcher {
|
|
|
486
822
|
// Also fetch assignment JSON to access allowedCidrs for network matching
|
|
487
823
|
batched.hGet(this.assignmentsRefKey, assignmentId);
|
|
488
824
|
}
|
|
489
|
-
const flat = await batched.exec();
|
|
825
|
+
const flat = (await batched.exec());
|
|
490
826
|
const details = [];
|
|
491
827
|
for (let i = 0; i < top.length; i++) {
|
|
492
828
|
const assignmentId = top[i].value;
|
|
@@ -495,68 +831,141 @@ class AssignmentMatcher {
|
|
|
495
831
|
const assignmentJson = flat[i * 3 + 2];
|
|
496
832
|
let allowedCidrs;
|
|
497
833
|
let skillThresholds;
|
|
834
|
+
let raw;
|
|
498
835
|
if (assignmentJson) {
|
|
499
836
|
try {
|
|
500
837
|
const parsed = JSON.parse(assignmentJson);
|
|
501
838
|
allowedCidrs = parsed.allowedCidrs;
|
|
502
839
|
skillThresholds = parsed.skillThresholds;
|
|
840
|
+
raw = parsed;
|
|
503
841
|
}
|
|
504
842
|
catch {
|
|
505
843
|
// Ignore JSON parse errors
|
|
506
844
|
}
|
|
507
845
|
}
|
|
508
|
-
details.push({ id: assignmentId, basePriority: priority, tags, allowedCidrs, skillThresholds });
|
|
846
|
+
details.push({ id: assignmentId, basePriority: priority, tags, allowedCidrs, skillThresholds, raw });
|
|
509
847
|
}
|
|
510
848
|
// Prefer higher base priority first to satisfy tests and practical expectations
|
|
511
849
|
details.sort((a, b) => b.basePriority - a.basePriority);
|
|
512
850
|
const selected = [];
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
851
|
+
if (this.enableLearning) {
|
|
852
|
+
// Learning path: evaluate all eligible candidates, then re-rank by
|
|
853
|
+
// base priority + predicted reward (hard filters still apply first).
|
|
854
|
+
const modelWeights = await this.learning.getModel();
|
|
855
|
+
const eligible = [];
|
|
856
|
+
for (const d of details) {
|
|
857
|
+
if (!(0, cidr_1.checkCidrMatch)(user.ip, d.allowedCidrs))
|
|
858
|
+
continue;
|
|
859
|
+
const geoMatch = await this.evaluateGeoMatch(user, d.raw ?? { id: d.id, tags: [] });
|
|
860
|
+
if (!geoMatch.eligible)
|
|
861
|
+
continue;
|
|
862
|
+
const [score, combinedPriority] = await this.matchScore(user, d.tags, d.basePriority, d.id, d.skillThresholds);
|
|
863
|
+
if (!score || !combinedPriority)
|
|
864
|
+
continue;
|
|
865
|
+
const geoAdjustedPriority = combinedPriority + this.calculateGeoBoost(geoMatch);
|
|
866
|
+
const context = {
|
|
867
|
+
...(d.raw ?? {}),
|
|
868
|
+
id: d.id,
|
|
869
|
+
tags: d.tags ? d.tags.split(',').filter(Boolean) : [],
|
|
870
|
+
};
|
|
871
|
+
const features = this.learningFeatureExtractor(user, context);
|
|
872
|
+
const predicted = this.learning.predict(features, modelWeights);
|
|
873
|
+
// Shadow mode observes without influencing ranking.
|
|
874
|
+
// Epsilon-greedy exploration adds random jitter to gather data on under-served candidates.
|
|
875
|
+
const exploration = !this.learning.shadowMode && this.learning.shouldExplore()
|
|
876
|
+
? Math.random() * this.learning.boostFactor
|
|
877
|
+
: 0;
|
|
878
|
+
const effectivePriority = this.learning.shadowMode
|
|
879
|
+
? geoAdjustedPriority
|
|
880
|
+
: geoAdjustedPriority + this.learning.boostFactor * predicted + exploration;
|
|
881
|
+
eligible.push({ detail: d, combinedPriority, features, predicted, effectivePriority });
|
|
519
882
|
}
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
883
|
+
eligible.sort((a, b) => b.effectivePriority - a.effectivePriority);
|
|
884
|
+
for (const c of eligible) {
|
|
885
|
+
if (userAssignments.length >= this.maxUserBacklogSize)
|
|
886
|
+
break;
|
|
887
|
+
userAssignments.push({ id: c.detail.id, priority: c.effectivePriority });
|
|
888
|
+
selected.push({ id: c.detail.id, tags: c.detail.tags });
|
|
889
|
+
await this.learning.recordDecision(user.id, c.detail.id, c.features, c.predicted, c.detail.tags ? c.detail.tags.split(',').filter(Boolean) : undefined);
|
|
525
890
|
}
|
|
526
891
|
}
|
|
527
|
-
|
|
892
|
+
else {
|
|
893
|
+
for (const d of details) {
|
|
894
|
+
if (userAssignments.length >= this.maxUserBacklogSize)
|
|
895
|
+
break;
|
|
896
|
+
// Check CIDR restrictions: if assignment has allowedCidrs, user must have matching IP
|
|
897
|
+
if (!(0, cidr_1.checkCidrMatch)(user.ip, d.allowedCidrs)) {
|
|
898
|
+
continue; // Skip this assignment - user IP doesn't match allowed CIDRs
|
|
899
|
+
}
|
|
900
|
+
const geoMatch = await this.evaluateGeoMatch(user, d.raw ?? { id: d.id, tags: [] });
|
|
901
|
+
if (!geoMatch.eligible) {
|
|
902
|
+
continue;
|
|
903
|
+
}
|
|
904
|
+
// Use custom matchScore (supports weights and thresholds) for a final check and tie-break
|
|
905
|
+
const [score, combinedPriority] = await this.matchScore(user, d.tags, d.basePriority, d.id, d.skillThresholds);
|
|
906
|
+
if (score && combinedPriority) {
|
|
907
|
+
userAssignments.push({ id: d.id, priority: combinedPriority + this.calculateGeoBoost(geoMatch) });
|
|
908
|
+
selected.push({ id: d.id, tags: d.tags });
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
// Claim, then clean up. The candidate read above (zDiffStore/zRangeWithScores)
|
|
913
|
+
// is a snapshot taken before this point, and getUserRelatedAssignments runs
|
|
914
|
+
// concurrently across users - matchUsersAssignments() Promise.all's the bulk
|
|
915
|
+
// path, and a per-user matchUsersAssignments(userId) call can race a bulk
|
|
916
|
+
// pass too. Without a single atomic gate, two concurrent callers can both
|
|
917
|
+
// still see the same assignment as available and both hand it to their user.
|
|
918
|
+
// HDEL on assignmentsRefKey is atomic and idempotent (returns 1 only for
|
|
919
|
+
// whichever caller actually deletes the field), so it's used here as that
|
|
920
|
+
// gate: only assignments this call actually wins are kept: anything already
|
|
921
|
+
// claimed by a concurrent caller since the snapshot read is dropped instead
|
|
922
|
+
// of being double-assigned.
|
|
923
|
+
const claimedIds = new Set();
|
|
528
924
|
if (selected.length > 0) {
|
|
529
|
-
// Fetch JSONs first to store in pending
|
|
530
925
|
const jsonPromises = selected.map((s) => this.redisClient.hGet(this.assignmentsRefKey, s.id));
|
|
531
926
|
const jsons = await Promise.all(jsonPromises);
|
|
532
927
|
const now = Date.now();
|
|
533
|
-
const
|
|
928
|
+
const claimMulti = this.redisClient.multi();
|
|
929
|
+
for (const s of selected) {
|
|
930
|
+
claimMulti.hDel(this.assignmentsRefKey, s.id);
|
|
931
|
+
}
|
|
932
|
+
const claimResults = (await claimMulti.exec());
|
|
534
933
|
for (let i = 0; i < selected.length; i++) {
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
rm
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
rm.
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
934
|
+
if (Number(claimResults[i]) > 0)
|
|
935
|
+
claimedIds.add(selected[i].id);
|
|
936
|
+
}
|
|
937
|
+
if (claimedIds.size > 0) {
|
|
938
|
+
const rm = this.redisClient.multi();
|
|
939
|
+
for (let i = 0; i < selected.length; i++) {
|
|
940
|
+
const s = selected[i];
|
|
941
|
+
if (!claimedIds.has(s.id))
|
|
942
|
+
continue; // lost the race - already claimed elsewhere
|
|
943
|
+
const json = jsons[i];
|
|
944
|
+
rm.del(this.keys.assignmentPriority(s.id));
|
|
945
|
+
rm.del(this.keys.assignmentTags(s.id));
|
|
946
|
+
// Remove from global zset
|
|
947
|
+
rm.zRem(this.assignmentsKey, s.id);
|
|
948
|
+
// Remove from per-tag zsets
|
|
949
|
+
const tags = (s.tags ? s.tags.split(',').filter(Boolean) : []);
|
|
950
|
+
for (const tag of tags) {
|
|
951
|
+
rm.zRem(this.keys.tagAssignments(tag), s.id);
|
|
952
|
+
}
|
|
953
|
+
// Add to pending structures
|
|
954
|
+
if (json) {
|
|
955
|
+
rm.hSet(this.pendingAssignmentsKey, s.id, json);
|
|
956
|
+
rm.zAdd(this.pendingAssignmentsExpiryKey, { score: now + this.matchExpirationMs, value: s.id });
|
|
957
|
+
rm.hSet(this.assignmentOwnerKey, s.id, user.id);
|
|
958
|
+
}
|
|
553
959
|
}
|
|
960
|
+
await rm.exec();
|
|
554
961
|
}
|
|
555
|
-
await rm.exec();
|
|
556
962
|
}
|
|
557
|
-
|
|
963
|
+
const workflowTargeted = userAssignments.slice(0, workflowTargetedCount);
|
|
964
|
+
const tagScored = userAssignments.slice(workflowTargetedCount).filter((ua) => claimedIds.has(ua.id));
|
|
965
|
+
return [...workflowTargeted, ...tagScored];
|
|
558
966
|
}
|
|
559
967
|
async matchUsersAssignments(userId) {
|
|
968
|
+
await this.readyPromise;
|
|
560
969
|
// If a specific userId is provided, process only that user for precise per-user matching.
|
|
561
970
|
if (userId) {
|
|
562
971
|
const userJson = await this.redisClient.hGet(this.usersKey, userId);
|
|
@@ -600,10 +1009,12 @@ class AssignmentMatcher {
|
|
|
600
1009
|
}));
|
|
601
1010
|
}
|
|
602
1011
|
async getCurrentAssignmentsForUser(userId) {
|
|
1012
|
+
await this.readyPromise;
|
|
603
1013
|
const userAssignments = await this.redisClient.sMembers(this.keys.userAssignments(userId));
|
|
604
1014
|
return userAssignments.map((el) => el.split(':')[1]);
|
|
605
1015
|
}
|
|
606
1016
|
async acceptAssignment(userId, assignmentId) {
|
|
1017
|
+
await this.readyPromise;
|
|
607
1018
|
const isAssigned = await this.redisClient.sIsMember(this.keys.userAssignments(userId), `assignment:${assignmentId}`);
|
|
608
1019
|
if (!isAssigned)
|
|
609
1020
|
throw new Error('Assignment not found for user');
|
|
@@ -619,9 +1030,14 @@ class AssignmentMatcher {
|
|
|
619
1030
|
multi.hSet(this.acceptedAssignmentsKey, assignmentId, json);
|
|
620
1031
|
}
|
|
621
1032
|
await multi.exec();
|
|
1033
|
+
if (this.enableLearning) {
|
|
1034
|
+
await this.learning.applyOutcome(assignmentId, 'accept');
|
|
1035
|
+
}
|
|
1036
|
+
await this.touchUser(userId);
|
|
622
1037
|
return true;
|
|
623
1038
|
}
|
|
624
1039
|
async rejectAssignment(userId, assignmentId) {
|
|
1040
|
+
await this.readyPromise;
|
|
625
1041
|
const isAssigned = await this.redisClient.sIsMember(this.keys.userAssignments(userId), `assignment:${assignmentId}`);
|
|
626
1042
|
if (!isAssigned)
|
|
627
1043
|
throw new Error('Assignment not found for user');
|
|
@@ -634,6 +1050,10 @@ class AssignmentMatcher {
|
|
|
634
1050
|
// Add to rejected list to prevent immediate re-assignment
|
|
635
1051
|
multi.sAdd(this.keys.userRejected(userId), assignmentId);
|
|
636
1052
|
await multi.exec();
|
|
1053
|
+
if (this.enableLearning) {
|
|
1054
|
+
await this.learning.applyOutcome(assignmentId, 'reject');
|
|
1055
|
+
}
|
|
1056
|
+
await this.touchUser(userId);
|
|
637
1057
|
if (json) {
|
|
638
1058
|
await this.addAssignment(JSON.parse(json));
|
|
639
1059
|
}
|
|
@@ -649,6 +1069,7 @@ class AssignmentMatcher {
|
|
|
649
1069
|
* @param result - Optional result payload for routing decisions
|
|
650
1070
|
*/
|
|
651
1071
|
async completeAssignment(userId, assignmentId, result) {
|
|
1072
|
+
await this.readyPromise;
|
|
652
1073
|
// Verify assignment is in accepted state
|
|
653
1074
|
const json = await this.redisClient.hGet(this.acceptedAssignmentsKey, assignmentId);
|
|
654
1075
|
if (!json) {
|
|
@@ -668,6 +1089,9 @@ class AssignmentMatcher {
|
|
|
668
1089
|
};
|
|
669
1090
|
multi.hSet(this.completedAssignmentsKey, assignmentId, JSON.stringify(completedData));
|
|
670
1091
|
await multi.exec();
|
|
1092
|
+
if (this.enableLearning) {
|
|
1093
|
+
await this.learning.applyOutcome(assignmentId, 'complete');
|
|
1094
|
+
}
|
|
671
1095
|
// Publish workflow event if workflows are enabled
|
|
672
1096
|
if (this.enableWorkflows) {
|
|
673
1097
|
await this.publishWorkflowEvent({
|
|
@@ -689,6 +1113,7 @@ class AssignmentMatcher {
|
|
|
689
1113
|
* @param reason - Optional reason for failure
|
|
690
1114
|
*/
|
|
691
1115
|
async failAssignment(userId, assignmentId, reason) {
|
|
1116
|
+
await this.readyPromise;
|
|
692
1117
|
const json = await this.redisClient.hGet(this.acceptedAssignmentsKey, assignmentId);
|
|
693
1118
|
if (!json) {
|
|
694
1119
|
throw new Error('Assignment not found in accepted state');
|
|
@@ -706,6 +1131,9 @@ class AssignmentMatcher {
|
|
|
706
1131
|
};
|
|
707
1132
|
multi.hSet(this.completedAssignmentsKey, assignmentId, JSON.stringify(failedData));
|
|
708
1133
|
await multi.exec();
|
|
1134
|
+
if (this.enableLearning) {
|
|
1135
|
+
await this.learning.applyOutcome(assignmentId, 'fail');
|
|
1136
|
+
}
|
|
709
1137
|
// Publish workflow event if workflows are enabled
|
|
710
1138
|
if (this.enableWorkflows) {
|
|
711
1139
|
await this.publishWorkflowEvent({
|
|
@@ -731,48 +1159,67 @@ class AssignmentMatcher {
|
|
|
731
1159
|
* Register a new workflow definition.
|
|
732
1160
|
*/
|
|
733
1161
|
async registerWorkflow(definition) {
|
|
1162
|
+
await this.readyPromise;
|
|
734
1163
|
return this.workflow.registerWorkflow(definition);
|
|
735
1164
|
}
|
|
736
1165
|
/**
|
|
737
1166
|
* Get a workflow definition by ID.
|
|
738
1167
|
*/
|
|
739
1168
|
async getWorkflowDefinition(id) {
|
|
1169
|
+
await this.readyPromise;
|
|
740
1170
|
return this.workflow.getWorkflowDefinition(id);
|
|
741
1171
|
}
|
|
742
1172
|
/**
|
|
743
1173
|
* List all registered workflow definitions.
|
|
744
1174
|
*/
|
|
745
1175
|
async listWorkflowDefinitions() {
|
|
1176
|
+
await this.readyPromise;
|
|
746
1177
|
return this.workflow.listWorkflowDefinitions();
|
|
747
1178
|
}
|
|
1179
|
+
/**
|
|
1180
|
+
* Register and start a workflow in one call, or start an already-registered workflow by ID.
|
|
1181
|
+
*/
|
|
1182
|
+
async executeWorkflow(workflowOrId, userId, initialContext) {
|
|
1183
|
+
await this.readyPromise;
|
|
1184
|
+
if (typeof workflowOrId === 'string') {
|
|
1185
|
+
return this.workflow.startWorkflow(workflowOrId, userId, initialContext);
|
|
1186
|
+
}
|
|
1187
|
+
const definition = await this.workflow.registerWorkflow(workflowOrId);
|
|
1188
|
+
return this.workflow.startWorkflow(definition.id, userId, initialContext);
|
|
1189
|
+
}
|
|
748
1190
|
/**
|
|
749
1191
|
* Start a new workflow instance for a user.
|
|
750
1192
|
*/
|
|
751
1193
|
async startWorkflow(workflowDefinitionId, userId, initialContext) {
|
|
1194
|
+
await this.readyPromise;
|
|
752
1195
|
return this.workflow.startWorkflow(workflowDefinitionId, userId, initialContext);
|
|
753
1196
|
}
|
|
754
1197
|
/**
|
|
755
1198
|
* Get a workflow instance by ID.
|
|
756
1199
|
*/
|
|
757
1200
|
async getWorkflowInstance(instanceId) {
|
|
1201
|
+
await this.readyPromise;
|
|
758
1202
|
return this.workflow.getWorkflowInstance(instanceId);
|
|
759
1203
|
}
|
|
760
1204
|
/**
|
|
761
1205
|
* Get a workflow instance with its snapshot definition.
|
|
762
1206
|
*/
|
|
763
1207
|
async getWorkflowInstanceWithSnapshot(instanceId) {
|
|
1208
|
+
await this.readyPromise;
|
|
764
1209
|
return this.workflow.getWorkflowInstanceWithSnapshot(instanceId);
|
|
765
1210
|
}
|
|
766
1211
|
/**
|
|
767
1212
|
* Get all active workflow instances for a user.
|
|
768
1213
|
*/
|
|
769
1214
|
async getActiveWorkflowsForUser(userId) {
|
|
1215
|
+
await this.readyPromise;
|
|
770
1216
|
return this.workflow.getActiveWorkflowsForUser(userId);
|
|
771
1217
|
}
|
|
772
1218
|
/**
|
|
773
1219
|
* Cancel a workflow instance.
|
|
774
1220
|
*/
|
|
775
1221
|
async cancelWorkflow(instanceId) {
|
|
1222
|
+
await this.readyPromise;
|
|
776
1223
|
return this.workflow.cancelWorkflow(instanceId);
|
|
777
1224
|
}
|
|
778
1225
|
/**
|
|
@@ -780,12 +1227,14 @@ class AssignmentMatcher {
|
|
|
780
1227
|
* Should be called periodically.
|
|
781
1228
|
*/
|
|
782
1229
|
async processExpiredWorkflowSteps() {
|
|
1230
|
+
await this.readyPromise;
|
|
783
1231
|
return this.workflow.processExpiredWorkflowSteps();
|
|
784
1232
|
}
|
|
785
1233
|
/**
|
|
786
1234
|
* Publish a workflow event to the Redis Stream.
|
|
787
1235
|
*/
|
|
788
1236
|
async publishWorkflowEvent(event) {
|
|
1237
|
+
await this.readyPromise;
|
|
789
1238
|
return this.workflow.publishWorkflowEvent(event);
|
|
790
1239
|
}
|
|
791
1240
|
/**
|
|
@@ -793,15 +1242,58 @@ class AssignmentMatcher {
|
|
|
793
1242
|
* This listens to the event stream and processes workflow transitions.
|
|
794
1243
|
*/
|
|
795
1244
|
async startOrchestrator() {
|
|
1245
|
+
await this.readyPromise;
|
|
796
1246
|
return this.workflow.startOrchestrator();
|
|
797
1247
|
}
|
|
798
1248
|
/**
|
|
799
1249
|
* Stop the workflow orchestrator.
|
|
800
1250
|
*/
|
|
801
1251
|
async stopOrchestrator() {
|
|
1252
|
+
await this.readyPromise;
|
|
802
1253
|
return this.workflow.stopOrchestrator();
|
|
803
1254
|
}
|
|
1255
|
+
/**
|
|
1256
|
+
* Register a machine task handler by name. Machine steps with a matching
|
|
1257
|
+
* machineTask.handler run through this handler; unmatched handlers fall
|
|
1258
|
+
* back to the executeMachineTask host hook.
|
|
1259
|
+
*/
|
|
1260
|
+
registerMachineHandler(name, handler) {
|
|
1261
|
+
this.workflow.registerMachineHandler(name, handler);
|
|
1262
|
+
}
|
|
1263
|
+
/**
|
|
1264
|
+
* Process due delayed event retries. Called automatically by the
|
|
1265
|
+
* orchestrator; exposed for deployments that run their own schedulers.
|
|
1266
|
+
*/
|
|
1267
|
+
async drainScheduledRetries() {
|
|
1268
|
+
await this.readyPromise;
|
|
1269
|
+
return this.workflow.drainScheduledRetries();
|
|
1270
|
+
}
|
|
1271
|
+
/**
|
|
1272
|
+
* Backfill workflow indexes (active-instance index) from records created
|
|
1273
|
+
* before these indexes existed. Safe to run multiple times.
|
|
1274
|
+
*/
|
|
1275
|
+
async backfillWorkflowIndexes() {
|
|
1276
|
+
await this.readyPromise;
|
|
1277
|
+
return this.workflow.backfillWorkflowIndexes();
|
|
1278
|
+
}
|
|
1279
|
+
/**
|
|
1280
|
+
* Remove terminal workflow instances last updated more than olderThanMs
|
|
1281
|
+
* ago, including registry, per-user, and index entries.
|
|
1282
|
+
*/
|
|
1283
|
+
async pruneWorkflowInstances(olderThanMs) {
|
|
1284
|
+
await this.readyPromise;
|
|
1285
|
+
return this.workflow.pruneWorkflowInstances(olderThanMs);
|
|
1286
|
+
}
|
|
1287
|
+
/**
|
|
1288
|
+
* Operational metrics for the workflow engine: active instances, retry
|
|
1289
|
+
* queue depth, DLQ size, and event stream statistics.
|
|
1290
|
+
*/
|
|
1291
|
+
async getWorkflowMetrics() {
|
|
1292
|
+
await this.readyPromise;
|
|
1293
|
+
return this.workflow.getWorkflowMetrics();
|
|
1294
|
+
}
|
|
804
1295
|
async processExpiredMatches() {
|
|
1296
|
+
await this.readyPromise;
|
|
805
1297
|
const now = Date.now();
|
|
806
1298
|
const expiredIds = await this.redisClient.zRangeByScore(this.pendingAssignmentsExpiryKey, '-inf', now);
|
|
807
1299
|
for (const id of expiredIds) {
|
|
@@ -815,6 +1307,9 @@ class AssignmentMatcher {
|
|
|
815
1307
|
multi.zRem(this.pendingAssignmentsExpiryKey, id);
|
|
816
1308
|
multi.hDel(this.assignmentOwnerKey, id);
|
|
817
1309
|
await multi.exec();
|
|
1310
|
+
if (this.enableLearning) {
|
|
1311
|
+
await this.learning.applyOutcome(id, 'expire');
|
|
1312
|
+
}
|
|
818
1313
|
// Publish workflow expired event if workflows are enabled
|
|
819
1314
|
if (this.enableWorkflows && owner) {
|
|
820
1315
|
await this.workflow.publishWorkflowEvent({
|
|
@@ -844,6 +1339,97 @@ class AssignmentMatcher {
|
|
|
844
1339
|
this.autoReleaseInterval = null;
|
|
845
1340
|
}
|
|
846
1341
|
}
|
|
1342
|
+
// ============================================================================
|
|
1343
|
+
// Idle User Auto-Rejection (opt-in via idleUserTimeoutMs)
|
|
1344
|
+
// ============================================================================
|
|
1345
|
+
/**
|
|
1346
|
+
* Record activity for a user (heartbeat). Resets the idle clock used by
|
|
1347
|
+
* processIdleUsers(). Called automatically on addUser, acceptAssignment,
|
|
1348
|
+
* and rejectAssignment; consumers can also call it directly as a heartbeat.
|
|
1349
|
+
*/
|
|
1350
|
+
async touchUser(userId) {
|
|
1351
|
+
await this.readyPromise;
|
|
1352
|
+
await this.redisClient.zAdd(this.keys.userActivity(), { score: Date.now(), value: userId });
|
|
1353
|
+
}
|
|
1354
|
+
/**
|
|
1355
|
+
* Detect users that have been idle longer than idleUserTimeoutMs while
|
|
1356
|
+
* holding pending (unactioned) assignments. Idle users are removed from
|
|
1357
|
+
* the matching pool and their pending assignments are requeued for
|
|
1358
|
+
* distribution to other users.
|
|
1359
|
+
*
|
|
1360
|
+
* No-op (returns []) when idleUserTimeoutMs is not configured.
|
|
1361
|
+
*
|
|
1362
|
+
* @returns IDs of users that were removed
|
|
1363
|
+
*/
|
|
1364
|
+
async processIdleUsers() {
|
|
1365
|
+
await this.readyPromise;
|
|
1366
|
+
if (this.idleUserTimeoutMs === null)
|
|
1367
|
+
return [];
|
|
1368
|
+
const cutoff = Date.now() - this.idleUserTimeoutMs;
|
|
1369
|
+
const idleCandidates = await this.redisClient.zRangeByScore(this.keys.userActivity(), '-inf', cutoff);
|
|
1370
|
+
const removed = [];
|
|
1371
|
+
for (const userId of idleCandidates) {
|
|
1372
|
+
// Skip users no longer in the pool (clean up stale activity entry)
|
|
1373
|
+
const exists = await this.redisClient.hExists(this.usersKey, userId);
|
|
1374
|
+
if (!exists) {
|
|
1375
|
+
await this.redisClient.zRem(this.keys.userActivity(), userId);
|
|
1376
|
+
continue;
|
|
1377
|
+
}
|
|
1378
|
+
// Only consider a user idle if they are sitting on unactioned assignments
|
|
1379
|
+
const pendingCount = await this.redisClient.sCard(this.keys.userAssignments(userId));
|
|
1380
|
+
if (pendingCount === 0)
|
|
1381
|
+
continue;
|
|
1382
|
+
await this.releaseUserPendingAssignments(userId);
|
|
1383
|
+
await this.removeUser(userId);
|
|
1384
|
+
removed.push(userId);
|
|
1385
|
+
}
|
|
1386
|
+
return removed;
|
|
1387
|
+
}
|
|
1388
|
+
/**
|
|
1389
|
+
* Requeue all pending assignments currently held by a user.
|
|
1390
|
+
*/
|
|
1391
|
+
async releaseUserPendingAssignments(userId) {
|
|
1392
|
+
const members = await this.redisClient.sMembers(this.keys.userAssignments(userId));
|
|
1393
|
+
const now = Date.now();
|
|
1394
|
+
for (const member of members) {
|
|
1395
|
+
const id = member.split(':')[1];
|
|
1396
|
+
const json = await this.redisClient.hGet(this.pendingAssignmentsKey, id);
|
|
1397
|
+
const multi = this.redisClient.multi();
|
|
1398
|
+
multi.sRem(this.keys.userAssignments(userId), member);
|
|
1399
|
+
multi.hDel(this.pendingAssignmentsKey, id);
|
|
1400
|
+
multi.zRem(this.pendingAssignmentsExpiryKey, id);
|
|
1401
|
+
multi.hDel(this.assignmentOwnerKey, id);
|
|
1402
|
+
await multi.exec();
|
|
1403
|
+
if (this.enableLearning) {
|
|
1404
|
+
await this.learning.applyOutcome(id, 'expire');
|
|
1405
|
+
}
|
|
1406
|
+
if (this.enableWorkflows) {
|
|
1407
|
+
await this.workflow.publishWorkflowEvent({
|
|
1408
|
+
eventId: (0, crypto_1.randomUUID)(),
|
|
1409
|
+
type: 'EXPIRED',
|
|
1410
|
+
userId,
|
|
1411
|
+
assignmentId: id,
|
|
1412
|
+
timestamp: now,
|
|
1413
|
+
});
|
|
1414
|
+
}
|
|
1415
|
+
if (json) {
|
|
1416
|
+
await this.addAssignment(JSON.parse(json));
|
|
1417
|
+
}
|
|
1418
|
+
}
|
|
1419
|
+
}
|
|
1420
|
+
startIdleUserInterval(intervalMs = 10000) {
|
|
1421
|
+
if (this.idleUserInterval)
|
|
1422
|
+
return;
|
|
1423
|
+
this.idleUserInterval = setInterval(() => {
|
|
1424
|
+
this.processIdleUsers().catch(console.error);
|
|
1425
|
+
}, intervalMs);
|
|
1426
|
+
}
|
|
1427
|
+
stopIdleUserInterval() {
|
|
1428
|
+
if (this.idleUserInterval) {
|
|
1429
|
+
clearInterval(this.idleUserInterval);
|
|
1430
|
+
this.idleUserInterval = null;
|
|
1431
|
+
}
|
|
1432
|
+
}
|
|
847
1433
|
/**
|
|
848
1434
|
* Get assignments specifically targeted at a user through active workflows.
|
|
849
1435
|
* These take priority over general pool assignments for deterministic matching.
|