assignment-user-matcher 1.6.0 → 1.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +177 -11
- package/dist/escalation/policy.d.ts +65 -0
- package/dist/escalation/policy.d.ts.map +1 -0
- package/dist/escalation/policy.js +120 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/learning/auto-weights.d.ts +18 -8
- package/dist/learning/auto-weights.d.ts.map +1 -1
- package/dist/learning/auto-weights.js +120 -18
- package/dist/learning/features.d.ts +2 -2
- package/dist/learning/features.d.ts.map +1 -1
- package/dist/learning/features.js +10 -2
- package/dist/managers/LearningManager.d.ts +7 -0
- package/dist/managers/LearningManager.d.ts.map +1 -1
- package/dist/managers/LearningManager.js +85 -11
- package/dist/managers/WorkflowManager.d.ts +10 -0
- package/dist/managers/WorkflowManager.d.ts.map +1 -1
- package/dist/managers/WorkflowManager.js +57 -2
- package/dist/matcher.class.d.ts +141 -4
- package/dist/matcher.class.d.ts.map +1 -1
- package/dist/matcher.class.js +801 -27
- package/dist/queries/pagination.d.ts +5 -0
- package/dist/queries/pagination.d.ts.map +1 -1
- package/dist/queries/pagination.js +13 -1
- package/dist/scoring/match-score.d.ts +6 -0
- package/dist/scoring/match-score.d.ts.map +1 -1
- package/dist/scoring/match-score.js +17 -2
- package/dist/sla/policy.d.ts +49 -0
- package/dist/sla/policy.d.ts.map +1 -0
- package/dist/sla/policy.js +96 -0
- package/dist/tracing/decision-trace.d.ts.map +1 -1
- package/dist/tracing/decision-trace.js +4 -2
- package/dist/types/matcher.d.ts +395 -2
- package/dist/types/matcher.d.ts.map +1 -1
- package/dist/utils/keys.d.ts +8 -0
- package/dist/utils/keys.d.ts.map +1 -1
- package/dist/utils/keys.js +16 -0
- package/dist/workflow-builder.d.ts +22 -0
- package/dist/workflow-builder.d.ts.map +1 -1
- package/dist/workflow-builder.js +29 -0
- package/dist/workflow-validation.d.ts.map +1 -1
- package/dist/workflow-validation.js +32 -0
- package/package.json +2 -1
package/dist/matcher.class.js
CHANGED
|
@@ -9,6 +9,8 @@ const keys_1 = require("./utils/keys");
|
|
|
9
9
|
const pagination_1 = require("./queries/pagination");
|
|
10
10
|
const match_score_1 = require("./scoring/match-score");
|
|
11
11
|
const fair_arbitration_1 = require("./scoring/fair-arbitration");
|
|
12
|
+
const policy_1 = require("./escalation/policy");
|
|
13
|
+
const policy_2 = require("./sla/policy");
|
|
12
14
|
const decision_trace_1 = require("./tracing/decision-trace");
|
|
13
15
|
const features_1 = require("./learning/features");
|
|
14
16
|
const DecisionTraceManager_1 = require("./managers/DecisionTraceManager");
|
|
@@ -37,6 +39,13 @@ class AssignmentMatcher {
|
|
|
37
39
|
constructor(redisClient, options) {
|
|
38
40
|
this.redisClient = redisClient;
|
|
39
41
|
this.luaScriptSha = null;
|
|
42
|
+
this.autoRoutingWeightsSyncInterval = null;
|
|
43
|
+
// ============================================================================
|
|
44
|
+
// Maintenance — the periodic sweeps that make deadlines actually fire
|
|
45
|
+
// ============================================================================
|
|
46
|
+
this.maintenanceInterval = null;
|
|
47
|
+
this.maintenanceOptions = null;
|
|
48
|
+
this.maintenanceRunning = false;
|
|
40
49
|
this.autoReleaseInterval = null;
|
|
41
50
|
this.idleUserInterval = null;
|
|
42
51
|
this.relevantBatchSize = options?.relevantBatchSize ?? 50;
|
|
@@ -55,6 +64,8 @@ class AssignmentMatcher {
|
|
|
55
64
|
this.assignmentOwnerKey = this.keys.assignmentOwner();
|
|
56
65
|
this.allTagsKey = this.keys.allTags();
|
|
57
66
|
this.acceptedAssignmentsKey = this.keys.acceptedAssignments();
|
|
67
|
+
this.acceptedAssignmentsExpiryKey = this.keys.acceptedAssignmentsExpiry();
|
|
68
|
+
this.assignmentsSlaExpiryKey = this.keys.assignmentsSlaExpiry();
|
|
58
69
|
this.completedAssignmentsKey = this.keys.completedAssignments();
|
|
59
70
|
this.calculatePriority = options?.prioritizationFunction ?? this.calculatePriority;
|
|
60
71
|
this.usingDefaultMatchScore = !options?.matchingFunction;
|
|
@@ -93,7 +104,12 @@ class AssignmentMatcher {
|
|
|
93
104
|
// Learning layer (opt-in contextual bandit re-ranking)
|
|
94
105
|
this.enableLearning = options?.enableLearning ?? false;
|
|
95
106
|
this.enableAutoRoutingWeights = options?.enableAutoRoutingWeights ?? false;
|
|
96
|
-
this.
|
|
107
|
+
this.learningSlaTightnessReferenceMs = options?.learningSlaTightnessReferenceMs ?? 3600000;
|
|
108
|
+
// The default extractor closes over the configured SLA tightness
|
|
109
|
+
// reference; custom extractors keep their exact signature.
|
|
110
|
+
this.learningFeatureExtractor =
|
|
111
|
+
options?.learningFeatureExtractor ??
|
|
112
|
+
((user, assignment) => (0, features_1.extractMatchFeatures)(user, assignment, this.learningSlaTightnessReferenceMs));
|
|
97
113
|
this.learning = new LearningManager_1.LearningManager(this.redisClient, this.keys, {
|
|
98
114
|
learningRate: options?.learningRate,
|
|
99
115
|
explorationRate: options?.learningExplorationRate,
|
|
@@ -127,7 +143,16 @@ class AssignmentMatcher {
|
|
|
127
143
|
onWorkflowEvent: options?.onWorkflowEvent,
|
|
128
144
|
});
|
|
129
145
|
this.onAssignmentLifecycle = options?.onAssignmentLifecycle;
|
|
130
|
-
this.
|
|
146
|
+
this.autoRoutingWeightsSyncIntervalMs = options?.autoRoutingWeightsSyncIntervalMs;
|
|
147
|
+
if (this.enableAutoRoutingWeights && this.autoRoutingWeightsSyncIntervalMs) {
|
|
148
|
+
this.readyPromise = this.initRedis().then((self) => {
|
|
149
|
+
this.startAutoRoutingWeightsSync(this.autoRoutingWeightsSyncIntervalMs);
|
|
150
|
+
return self;
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
else {
|
|
154
|
+
this.readyPromise = this.initRedis();
|
|
155
|
+
}
|
|
131
156
|
}
|
|
132
157
|
/**
|
|
133
158
|
* Fire the optional assignment lifecycle hook. Errors are swallowed so a
|
|
@@ -143,13 +168,99 @@ class AssignmentMatcher {
|
|
|
143
168
|
// Best-effort hook: do not propagate.
|
|
144
169
|
}
|
|
145
170
|
}
|
|
146
|
-
|
|
171
|
+
// ============================================================================
|
|
172
|
+
// SLO stats — minimal aggregate counters (global + per-tag hashes)
|
|
173
|
+
// ============================================================================
|
|
174
|
+
/** Increment SLO counters globally and per assignment tag. Best-effort. */
|
|
175
|
+
async bumpSlaStats(tags, deltas) {
|
|
176
|
+
try {
|
|
177
|
+
const multi = this.redisClient.multi();
|
|
178
|
+
const apply = (key) => {
|
|
179
|
+
for (const [field, delta] of Object.entries(deltas)) {
|
|
180
|
+
multi.hIncrByFloat(key, field, delta);
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
apply(this.keys.slaStats());
|
|
184
|
+
for (const tag of tags ?? []) {
|
|
185
|
+
if (tag)
|
|
186
|
+
apply(this.keys.slaTagStats(tag));
|
|
187
|
+
}
|
|
188
|
+
await multi.exec();
|
|
189
|
+
}
|
|
190
|
+
catch {
|
|
191
|
+
// Best-effort: stats never break the lifecycle.
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Accept-path stats: offers were counted at claim time; here we record
|
|
196
|
+
* the accept, its latency (acceptedAt - matchedAt), and whether it beat
|
|
197
|
+
* the response deadline that was in effect.
|
|
198
|
+
*/
|
|
199
|
+
async recordSlaAccept(pendingJson, acceptedAt) {
|
|
200
|
+
try {
|
|
201
|
+
const parsed = JSON.parse(pendingJson);
|
|
202
|
+
const matchedAt = Number(parsed[policy_2.SLA_MATCHED_AT_FIELD]);
|
|
203
|
+
if (!Number.isFinite(matchedAt) || matchedAt <= 0)
|
|
204
|
+
return;
|
|
205
|
+
const latency = Math.max(0, acceptedAt - matchedAt);
|
|
206
|
+
const respondWithin = (0, policy_1.responseDeadlineMs)(parsed, this.matchExpirationMs);
|
|
207
|
+
const deltas = {
|
|
208
|
+
accepts: 1,
|
|
209
|
+
acceptLatencyMsSum: latency,
|
|
210
|
+
};
|
|
211
|
+
if (matchedAt + respondWithin >= acceptedAt)
|
|
212
|
+
deltas.acceptedInTime = 1;
|
|
213
|
+
await this.bumpSlaStats(parsed.tags, deltas);
|
|
214
|
+
}
|
|
215
|
+
catch {
|
|
216
|
+
// best-effort: stats never break the lifecycle
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
/** Completion-path stats: completion latency (completedAt - acceptedAt). */
|
|
220
|
+
async recordSlaComplete(acceptedJson, completedAt) {
|
|
221
|
+
try {
|
|
222
|
+
const parsed = JSON.parse(acceptedJson);
|
|
223
|
+
const acceptedAt = Number(parsed[policy_2.SLA_ACCEPTED_AT_FIELD]);
|
|
224
|
+
if (!Number.isFinite(acceptedAt) || acceptedAt <= 0)
|
|
225
|
+
return;
|
|
226
|
+
await this.bumpSlaStats(parsed.tags, {
|
|
227
|
+
completes: 1,
|
|
228
|
+
completeLatencyMsSum: Math.max(0, completedAt - acceptedAt),
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
catch {
|
|
232
|
+
// best-effort
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* Aggregate SLO attainment counters, globally or for a single tag.
|
|
237
|
+
* Means are computed from sum/count pairs; 0 when no data.
|
|
238
|
+
*/
|
|
239
|
+
async getSlaStats(tag) {
|
|
240
|
+
await this.readyPromise;
|
|
241
|
+
const raw = await this.redisClient.hGetAll(tag ? this.keys.slaTagStats(tag) : this.keys.slaStats());
|
|
242
|
+
const num = (field) => Number(raw[field]) || 0;
|
|
243
|
+
const accepts = num('accepts');
|
|
244
|
+
const completes = num('completes');
|
|
245
|
+
return {
|
|
246
|
+
offers: num('offers'),
|
|
247
|
+
acceptedInTime: num('acceptedInTime'),
|
|
248
|
+
acceptanceBreaches: num('acceptanceBreaches'),
|
|
249
|
+
completionBreaches: num('completionBreaches'),
|
|
250
|
+
ttlExpiries: num('ttlExpiries'),
|
|
251
|
+
rejectionParked: num('rejectionParked'),
|
|
252
|
+
meanAcceptLatencyMs: accepts > 0 ? num('acceptLatencyMsSum') / accepts : 0,
|
|
253
|
+
meanCompleteLatencyMs: completes > 0 ? num('completeLatencyMsSum') / completes : 0,
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
/** Keys for the assignment stores (used by pagination queries) */
|
|
147
257
|
get assignmentStoreKeys() {
|
|
148
258
|
return {
|
|
149
259
|
queued: this.assignmentsRefKey,
|
|
150
260
|
pending: this.pendingAssignmentsKey,
|
|
151
261
|
accepted: this.acceptedAssignmentsKey,
|
|
152
262
|
completed: this.completedAssignmentsKey,
|
|
263
|
+
parked: this.keys.parkedAssignments(),
|
|
153
264
|
};
|
|
154
265
|
}
|
|
155
266
|
async initRedis() {
|
|
@@ -658,9 +769,7 @@ class AssignmentMatcher {
|
|
|
658
769
|
let userList;
|
|
659
770
|
if (opts?.userIds && opts.userIds.length > 0) {
|
|
660
771
|
const jsons = await this.redisClient.hmGet(this.usersKey, opts.userIds);
|
|
661
|
-
userList = jsons
|
|
662
|
-
.filter((json) => Boolean(json))
|
|
663
|
-
.map((json) => JSON.parse(json));
|
|
772
|
+
userList = jsons.filter((json) => Boolean(json)).map((json) => JSON.parse(json));
|
|
664
773
|
}
|
|
665
774
|
else {
|
|
666
775
|
const all = await this.redisClient.hGetAll(this.usersKey);
|
|
@@ -810,6 +919,11 @@ class AssignmentMatcher {
|
|
|
810
919
|
* The applied learned map is stored on the user as `learnedRoutingWeights`
|
|
811
920
|
* for observability.
|
|
812
921
|
*
|
|
922
|
+
* Guardrails: evidence floor (`minTotalSamples`), strict veto gate for
|
|
923
|
+
* manual tags (`minSamplesForVeto`), and per-sync step clamp
|
|
924
|
+
* (`maxDeltaPerSync`) are applied automatically. Set `dryRun: true` to
|
|
925
|
+
* compute the would-be map without writing anything.
|
|
926
|
+
*
|
|
813
927
|
* Returns the applied weights per user id.
|
|
814
928
|
*/
|
|
815
929
|
async syncLearnedRoutingWeights(userId, opts) {
|
|
@@ -817,6 +931,8 @@ class AssignmentMatcher {
|
|
|
817
931
|
const targets = userId ? [userId] : await this.learning.listTrackedUsers();
|
|
818
932
|
const knownTags = opts?.includeUnexploredTags ? await this.getKnownTagsForAutoWeights() : undefined;
|
|
819
933
|
const applied = {};
|
|
934
|
+
const maxDelta = this.learning.autoWeights.maxDeltaPerSync;
|
|
935
|
+
const maxWeight = this.learning.autoWeights.maxWeight ?? 100;
|
|
820
936
|
for (const id of targets) {
|
|
821
937
|
const userJson = await this.redisClient.hGet(this.usersKey, id);
|
|
822
938
|
if (!userJson)
|
|
@@ -832,23 +948,130 @@ class AssignmentMatcher {
|
|
|
832
948
|
const learned = await this.learning.getLearnedRoutingWeights(id, knownTags, existingForSynthesis);
|
|
833
949
|
if (Object.keys(learned).length === 0)
|
|
834
950
|
continue;
|
|
951
|
+
// Apply per-sync step clamp. Vetoes (weight 0) that passed the
|
|
952
|
+
// strict veto gate are allowed to jump despite the clamp.
|
|
953
|
+
const clampedLearned = {};
|
|
954
|
+
for (const [tag, weight] of Object.entries(learned)) {
|
|
955
|
+
if (weight === 0 || maxDelta === undefined) {
|
|
956
|
+
clampedLearned[tag] = weight;
|
|
957
|
+
continue;
|
|
958
|
+
}
|
|
959
|
+
const previous = previousLearned[tag] ?? user.routingWeights?.[tag];
|
|
960
|
+
if (previous === undefined) {
|
|
961
|
+
clampedLearned[tag] = Math.min(weight, maxWeight);
|
|
962
|
+
continue;
|
|
963
|
+
}
|
|
964
|
+
const lower = previous - maxDelta;
|
|
965
|
+
const upper = previous + maxDelta;
|
|
966
|
+
clampedLearned[tag] = Math.min(Math.max(weight, lower, 1), upper, maxWeight);
|
|
967
|
+
}
|
|
835
968
|
let routingWeights;
|
|
836
969
|
if (opts?.overrideManual) {
|
|
837
|
-
routingWeights =
|
|
970
|
+
routingWeights = { ...clampedLearned };
|
|
838
971
|
}
|
|
839
972
|
else {
|
|
840
973
|
const manualEntries = {};
|
|
841
974
|
for (const [tag, weight] of Object.entries(user.routingWeights ?? {})) {
|
|
842
|
-
if (!(tag in previousLearned) && !(tag in
|
|
975
|
+
if (!(tag in previousLearned) && !(tag in clampedLearned))
|
|
843
976
|
manualEntries[tag] = weight;
|
|
844
977
|
}
|
|
845
|
-
routingWeights = { ...manualEntries, ...
|
|
978
|
+
routingWeights = { ...manualEntries, ...clampedLearned };
|
|
846
979
|
}
|
|
847
|
-
await this.redisClient.hSet(this.usersKey, id, JSON.stringify({ ...user, routingWeights, learnedRoutingWeights: learned }));
|
|
848
980
|
applied[id] = routingWeights;
|
|
981
|
+
if (opts?.dryRun)
|
|
982
|
+
continue;
|
|
983
|
+
await this.redisClient.hSet(this.usersKey, id, JSON.stringify({
|
|
984
|
+
...user,
|
|
985
|
+
routingWeights,
|
|
986
|
+
routingWeightsSnapshot: user.routingWeights,
|
|
987
|
+
learnedRoutingWeights: clampedLearned,
|
|
988
|
+
learnedRoutingWeightsSyncedAt: Date.now(),
|
|
989
|
+
}));
|
|
849
990
|
}
|
|
850
991
|
return applied;
|
|
851
992
|
}
|
|
993
|
+
/**
|
|
994
|
+
* Revert learned routing weights for one user (or all users with a
|
|
995
|
+
* snapshot) to the map saved before the last sync. No-op when no snapshot
|
|
996
|
+
* exists.
|
|
997
|
+
*
|
|
998
|
+
* Returns reverted user ids.
|
|
999
|
+
*/
|
|
1000
|
+
async revertLearnedRoutingWeights(userId) {
|
|
1001
|
+
await this.readyPromise;
|
|
1002
|
+
const targets = [];
|
|
1003
|
+
if (userId) {
|
|
1004
|
+
targets.push(userId);
|
|
1005
|
+
}
|
|
1006
|
+
else {
|
|
1007
|
+
const all = await this.redisClient.hGetAll(this.usersKey);
|
|
1008
|
+
for (const [id, json] of Object.entries(all)) {
|
|
1009
|
+
try {
|
|
1010
|
+
const u = JSON.parse(json);
|
|
1011
|
+
if (u.routingWeightsSnapshot)
|
|
1012
|
+
targets.push(id);
|
|
1013
|
+
}
|
|
1014
|
+
catch {
|
|
1015
|
+
// ignore malformed user entries
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
}
|
|
1019
|
+
const reverted = [];
|
|
1020
|
+
for (const id of targets) {
|
|
1021
|
+
const userJson = await this.redisClient.hGet(this.usersKey, id);
|
|
1022
|
+
if (!userJson)
|
|
1023
|
+
continue;
|
|
1024
|
+
const user = JSON.parse(userJson);
|
|
1025
|
+
if (!user.routingWeightsSnapshot)
|
|
1026
|
+
continue;
|
|
1027
|
+
await this.redisClient.hSet(this.usersKey, id, JSON.stringify({
|
|
1028
|
+
...user,
|
|
1029
|
+
routingWeights: user.routingWeightsSnapshot,
|
|
1030
|
+
routingWeightsSnapshot: undefined,
|
|
1031
|
+
learnedRoutingWeights: undefined,
|
|
1032
|
+
learnedRoutingWeightsSyncedAt: undefined,
|
|
1033
|
+
}));
|
|
1034
|
+
reverted.push(id);
|
|
1035
|
+
}
|
|
1036
|
+
return reverted;
|
|
1037
|
+
}
|
|
1038
|
+
/** Start the automatic learned-weights sync tick. Idempotent. */
|
|
1039
|
+
startAutoRoutingWeightsSync(intervalMs) {
|
|
1040
|
+
this.stopAutoRoutingWeightsSync();
|
|
1041
|
+
if (intervalMs)
|
|
1042
|
+
this.autoRoutingWeightsSyncIntervalMs = intervalMs;
|
|
1043
|
+
const ms = this.autoRoutingWeightsSyncIntervalMs;
|
|
1044
|
+
if (!ms || !this.enableAutoRoutingWeights)
|
|
1045
|
+
return;
|
|
1046
|
+
this.autoRoutingWeightsSyncInterval = setInterval(() => {
|
|
1047
|
+
this.runAutoRoutingWeightsSyncTick().catch((err) => console.error('Auto routing-weights sync tick failed:', err));
|
|
1048
|
+
}, ms);
|
|
1049
|
+
this.autoRoutingWeightsSyncInterval.unref?.();
|
|
1050
|
+
}
|
|
1051
|
+
/** Stop the automatic learned-weights sync tick. Safe when not started. */
|
|
1052
|
+
stopAutoRoutingWeightsSync() {
|
|
1053
|
+
if (this.autoRoutingWeightsSyncInterval) {
|
|
1054
|
+
clearInterval(this.autoRoutingWeightsSyncInterval);
|
|
1055
|
+
this.autoRoutingWeightsSyncInterval = null;
|
|
1056
|
+
}
|
|
1057
|
+
}
|
|
1058
|
+
/** Whether the automatic learned-weights sync tick is running. */
|
|
1059
|
+
isAutoRoutingWeightsSyncRunning() {
|
|
1060
|
+
return this.autoRoutingWeightsSyncInterval !== null;
|
|
1061
|
+
}
|
|
1062
|
+
async runAutoRoutingWeightsSyncTick() {
|
|
1063
|
+
const ms = this.autoRoutingWeightsSyncIntervalMs;
|
|
1064
|
+
if (!ms)
|
|
1065
|
+
return;
|
|
1066
|
+
const lockTtl = Math.max(1000, ms - 1000);
|
|
1067
|
+
const acquired = await this.redisClient.set(this.keys.autoWeightsSyncLock(), this.streamConsumerName, {
|
|
1068
|
+
NX: true,
|
|
1069
|
+
PX: lockTtl,
|
|
1070
|
+
});
|
|
1071
|
+
if (!acquired)
|
|
1072
|
+
return;
|
|
1073
|
+
await this.syncLearnedRoutingWeights();
|
|
1074
|
+
}
|
|
852
1075
|
/** All known tags except the internal 'default' tag (for exploration priors) */
|
|
853
1076
|
async getKnownTagsForAutoWeights() {
|
|
854
1077
|
const tags = await this.redisClient.sMembers(this.allTagsKey);
|
|
@@ -896,6 +1119,20 @@ class AssignmentMatcher {
|
|
|
896
1119
|
let { id, tags, priority, latitude, longitude } = assignment;
|
|
897
1120
|
if (!priority)
|
|
898
1121
|
priority = await this.calculatePriority(assignment);
|
|
1122
|
+
// First-enqueue clock for the freshness TTL: NX semantics via the
|
|
1123
|
+
// object itself — a requeue re-adds the same JSON (with the original
|
|
1124
|
+
// _enqueuedAt), so the TTL is never extended by rejection ping-pong.
|
|
1125
|
+
// Only stamped when the assignment actually declares a TTL, so
|
|
1126
|
+
// non-SLA assignments keep byte-identical stored JSON.
|
|
1127
|
+
const slaPolicy = (0, policy_2.normalizeSlaPolicy)(assignment.sla);
|
|
1128
|
+
let slaExpiry = null;
|
|
1129
|
+
if (slaPolicy?.expireAfterMs !== undefined) {
|
|
1130
|
+
const record = assignment;
|
|
1131
|
+
if (record[policy_2.SLA_ENQUEUED_AT_FIELD] === undefined) {
|
|
1132
|
+
record[policy_2.SLA_ENQUEUED_AT_FIELD] = Date.now();
|
|
1133
|
+
}
|
|
1134
|
+
slaExpiry = (0, policy_2.slaExpiryScore)(record[policy_2.SLA_ENQUEUED_AT_FIELD], slaPolicy);
|
|
1135
|
+
}
|
|
899
1136
|
const assignmentPriorityKey = this.keys.assignmentPriority(id);
|
|
900
1137
|
const assignmentTagsKey = this.keys.assignmentTags(id);
|
|
901
1138
|
const assignmentGeoKey = this.keys.assignmentsGeo();
|
|
@@ -912,6 +1149,9 @@ class AssignmentMatcher {
|
|
|
912
1149
|
score: priority,
|
|
913
1150
|
value: id,
|
|
914
1151
|
});
|
|
1152
|
+
if (slaExpiry !== null) {
|
|
1153
|
+
multi.zAdd(this.assignmentsSlaExpiryKey, { score: slaExpiry, value: id });
|
|
1154
|
+
}
|
|
915
1155
|
if ((0, geo_1.isValidLatitude)(latitude) && (0, geo_1.isValidLongitude)(longitude)) {
|
|
916
1156
|
multi.geoAdd(assignmentGeoKey, {
|
|
917
1157
|
longitude,
|
|
@@ -979,6 +1219,9 @@ class AssignmentMatcher {
|
|
|
979
1219
|
}
|
|
980
1220
|
// 3. Remove from Accepted state
|
|
981
1221
|
multi.hDel(this.acceptedAssignmentsKey, id);
|
|
1222
|
+
// 4. Clear SLA indexes (no-ops for non-SLA assignments)
|
|
1223
|
+
multi.zRem(this.acceptedAssignmentsExpiryKey, id);
|
|
1224
|
+
multi.zRem(this.assignmentsSlaExpiryKey, id);
|
|
982
1225
|
await multi.exec();
|
|
983
1226
|
return id;
|
|
984
1227
|
}
|
|
@@ -1666,15 +1909,41 @@ class AssignmentMatcher {
|
|
|
1666
1909
|
for (const tag of tags) {
|
|
1667
1910
|
rm.zRem(this.keys.tagAssignments(tag), s.id);
|
|
1668
1911
|
}
|
|
1669
|
-
// Add to pending structures
|
|
1912
|
+
// Add to pending structures. An assignment carrying an
|
|
1913
|
+
// EscalationPolicy sets its own response deadline; everything
|
|
1914
|
+
// else uses the matcher-wide one and never pays for a parse.
|
|
1670
1915
|
if (json) {
|
|
1671
|
-
|
|
1672
|
-
|
|
1916
|
+
// SLA-bearing assignments get a match timestamp for
|
|
1917
|
+
// accept-latency SLO stats; everyone else's JSON stays
|
|
1918
|
+
// byte-identical (guarded by the same cheap indexOf).
|
|
1919
|
+
let pendingJson = json;
|
|
1920
|
+
if (json.indexOf('"sla"') !== -1) {
|
|
1921
|
+
try {
|
|
1922
|
+
const parsed = JSON.parse(json);
|
|
1923
|
+
parsed[policy_2.SLA_MATCHED_AT_FIELD] = now;
|
|
1924
|
+
pendingJson = JSON.stringify(parsed);
|
|
1925
|
+
// Count the offer (global + per-tag) in the same batch.
|
|
1926
|
+
rm.hIncrByFloat(this.keys.slaStats(), 'offers', 1);
|
|
1927
|
+
for (const tag of (parsed.tags ?? [])) {
|
|
1928
|
+
if (tag)
|
|
1929
|
+
rm.hIncrByFloat(this.keys.slaTagStats(tag), 'offers', 1);
|
|
1930
|
+
}
|
|
1931
|
+
}
|
|
1932
|
+
catch {
|
|
1933
|
+
// keep original JSON on parse failure
|
|
1934
|
+
}
|
|
1935
|
+
}
|
|
1936
|
+
rm.hSet(this.pendingAssignmentsKey, s.id, pendingJson);
|
|
1937
|
+
rm.zAdd(this.pendingAssignmentsExpiryKey, {
|
|
1938
|
+
score: now + (0, policy_1.responseDeadlineFromJson)(json, this.matchExpirationMs),
|
|
1939
|
+
value: s.id,
|
|
1940
|
+
});
|
|
1673
1941
|
rm.hSet(this.assignmentOwnerKey, s.id, user.id);
|
|
1674
1942
|
}
|
|
1675
1943
|
}
|
|
1676
1944
|
await rm.exec();
|
|
1677
|
-
for (
|
|
1945
|
+
for (let i = 0; i < selected.length; i++) {
|
|
1946
|
+
const s = selected[i];
|
|
1678
1947
|
if (!claimedIds.has(s.id))
|
|
1679
1948
|
continue;
|
|
1680
1949
|
this.emitAssignmentLifecycle({
|
|
@@ -1682,7 +1951,7 @@ class AssignmentMatcher {
|
|
|
1682
1951
|
taskId: s.id,
|
|
1683
1952
|
workerId: user.id,
|
|
1684
1953
|
matchedAt: now,
|
|
1685
|
-
expiresAt: now + this.matchExpirationMs,
|
|
1954
|
+
expiresAt: now + (0, policy_1.responseDeadlineFromJson)(jsons[i], this.matchExpirationMs),
|
|
1686
1955
|
});
|
|
1687
1956
|
}
|
|
1688
1957
|
}
|
|
@@ -2045,24 +2314,40 @@ class AssignmentMatcher {
|
|
|
2045
2314
|
}
|
|
2046
2315
|
else {
|
|
2047
2316
|
// Pending under another user: transfer ownership and restart the
|
|
2048
|
-
// expiry clock for the new owner
|
|
2317
|
+
// expiry clock for the new owner (honouring the assignment's own
|
|
2318
|
+
// response deadline when it declares one).
|
|
2319
|
+
const pendingJson = await this.redisClient.hGet(this.pendingAssignmentsKey, assignmentId);
|
|
2320
|
+
const deadlineMs = (0, policy_1.responseDeadlineFromJson)(pendingJson, this.matchExpirationMs);
|
|
2321
|
+
const now = Date.now();
|
|
2049
2322
|
const transfer = this.redisClient
|
|
2050
2323
|
.multi()
|
|
2051
2324
|
.sRem(this.keys.userAssignments(previousOwnerId), `assignment:${assignmentId}`)
|
|
2052
2325
|
.sAdd(this.keys.userAssignments(userId), `assignment:${assignmentId}`)
|
|
2053
2326
|
.hSet(this.assignmentOwnerKey, assignmentId, userId)
|
|
2054
2327
|
.zAdd(this.pendingAssignmentsExpiryKey, {
|
|
2055
|
-
score:
|
|
2328
|
+
score: now + deadlineMs,
|
|
2056
2329
|
value: assignmentId,
|
|
2057
2330
|
});
|
|
2331
|
+
// Refresh the SLA match timestamp for the new owner so accept
|
|
2332
|
+
// latency is measured against the transfer, not the original claim.
|
|
2333
|
+
if (pendingJson && pendingJson.indexOf('"sla"') !== -1) {
|
|
2334
|
+
try {
|
|
2335
|
+
const parsed = JSON.parse(pendingJson);
|
|
2336
|
+
parsed[policy_2.SLA_MATCHED_AT_FIELD] = now;
|
|
2337
|
+
transfer.hSet(this.pendingAssignmentsKey, assignmentId, JSON.stringify(parsed));
|
|
2338
|
+
}
|
|
2339
|
+
catch {
|
|
2340
|
+
// keep original JSON on parse failure
|
|
2341
|
+
}
|
|
2342
|
+
}
|
|
2058
2343
|
await transfer.exec();
|
|
2059
|
-
const reassignedAt =
|
|
2344
|
+
const reassignedAt = now;
|
|
2060
2345
|
this.emitAssignmentLifecycle({
|
|
2061
2346
|
kind: 'pending',
|
|
2062
2347
|
taskId: assignmentId,
|
|
2063
2348
|
workerId: userId,
|
|
2064
2349
|
matchedAt: reassignedAt,
|
|
2065
|
-
expiresAt: reassignedAt +
|
|
2350
|
+
expiresAt: reassignedAt + deadlineMs,
|
|
2066
2351
|
});
|
|
2067
2352
|
}
|
|
2068
2353
|
await this.touchUser(userId);
|
|
@@ -2105,6 +2390,7 @@ class AssignmentMatcher {
|
|
|
2105
2390
|
throw new Error('Assignment not found for user');
|
|
2106
2391
|
// Get the assignment JSON before removing from pending
|
|
2107
2392
|
const json = await this.redisClient.hGet(this.pendingAssignmentsKey, assignmentId);
|
|
2393
|
+
const now = Date.now();
|
|
2108
2394
|
const multi = this.redisClient.multi();
|
|
2109
2395
|
multi.sRem(this.keys.userAssignments(userId), `assignment:${assignmentId}`);
|
|
2110
2396
|
multi.hDel(this.pendingAssignmentsKey, assignmentId);
|
|
@@ -2112,11 +2398,35 @@ class AssignmentMatcher {
|
|
|
2112
2398
|
multi.hDel(this.assignmentOwnerKey, assignmentId);
|
|
2113
2399
|
// The wait clock stops when a user takes the work
|
|
2114
2400
|
multi.zRem(this.keys.assignmentsQueuedAt(), assignmentId);
|
|
2115
|
-
// Store in accepted assignments
|
|
2401
|
+
// Store in accepted assignments. SLA-bearing assignments are stamped
|
|
2402
|
+
// with the accept timestamp/owner and registered on the completion-
|
|
2403
|
+
// deadline index when they declare completeWithinMs.
|
|
2116
2404
|
if (json) {
|
|
2117
|
-
|
|
2405
|
+
const slaPolicy = (0, policy_2.slaFromJson)(json);
|
|
2406
|
+
let acceptedJson = json;
|
|
2407
|
+
if (slaPolicy) {
|
|
2408
|
+
try {
|
|
2409
|
+
const parsed = JSON.parse(json);
|
|
2410
|
+
parsed[policy_2.SLA_ACCEPTED_AT_FIELD] = now;
|
|
2411
|
+
parsed[policy_2.SLA_ACCEPTED_BY_FIELD] = userId;
|
|
2412
|
+
acceptedJson = JSON.stringify(parsed);
|
|
2413
|
+
const deadline = (0, policy_2.completionDeadlineScore)(now, slaPolicy);
|
|
2414
|
+
if (deadline !== null) {
|
|
2415
|
+
multi.zAdd(this.acceptedAssignmentsExpiryKey, { score: deadline, value: assignmentId });
|
|
2416
|
+
}
|
|
2417
|
+
}
|
|
2418
|
+
catch {
|
|
2419
|
+
// keep original JSON on parse failure
|
|
2420
|
+
}
|
|
2421
|
+
}
|
|
2422
|
+
multi.hSet(this.acceptedAssignmentsKey, assignmentId, acceptedJson);
|
|
2118
2423
|
}
|
|
2119
2424
|
await multi.exec();
|
|
2425
|
+
// SLO accept stats piggyback the accept path (internally guarded:
|
|
2426
|
+
// stats errors never break the lifecycle).
|
|
2427
|
+
if (json && json.indexOf('"sla"') !== -1) {
|
|
2428
|
+
await this.recordSlaAccept(json, now);
|
|
2429
|
+
}
|
|
2120
2430
|
if (this.enableLearning) {
|
|
2121
2431
|
await this.learning.applyOutcome(assignmentId, 'accept');
|
|
2122
2432
|
}
|
|
@@ -2124,7 +2434,7 @@ class AssignmentMatcher {
|
|
|
2124
2434
|
kind: 'accepted',
|
|
2125
2435
|
taskId: assignmentId,
|
|
2126
2436
|
workerId: userId,
|
|
2127
|
-
acceptedAt:
|
|
2437
|
+
acceptedAt: now,
|
|
2128
2438
|
});
|
|
2129
2439
|
await this.touchUser(userId);
|
|
2130
2440
|
return true;
|
|
@@ -2154,10 +2464,69 @@ class AssignmentMatcher {
|
|
|
2154
2464
|
});
|
|
2155
2465
|
await this.touchUser(userId);
|
|
2156
2466
|
if (json) {
|
|
2157
|
-
await this.
|
|
2467
|
+
await this.requeueAfterRefusal(JSON.parse(json), 'reject');
|
|
2158
2468
|
}
|
|
2159
2469
|
return true;
|
|
2160
2470
|
}
|
|
2471
|
+
/**
|
|
2472
|
+
* Shared requeue path for refusals (explicit rejects and blocking
|
|
2473
|
+
* no-response expiries): increments the SLA rejection counter and, when
|
|
2474
|
+
* the budget is exhausted, applies `onMaxRejections` instead of
|
|
2475
|
+
* requeueing. Non-SLA assignments take the untouched legacy path.
|
|
2476
|
+
*/
|
|
2477
|
+
async requeueAfterRefusal(assignment, cause) {
|
|
2478
|
+
const policy = (0, policy_2.normalizeSlaPolicy)(assignment.sla);
|
|
2479
|
+
if (!policy) {
|
|
2480
|
+
await this.addAssignment(assignment);
|
|
2481
|
+
return;
|
|
2482
|
+
}
|
|
2483
|
+
const record = assignment;
|
|
2484
|
+
const rejections = (0, policy_2.rejectionCountOf)(assignment) + 1;
|
|
2485
|
+
record[policy_2.SLA_REJECTION_COUNT_FIELD] = rejections;
|
|
2486
|
+
// 'keep' makes the budget measurement-only: the counter keeps
|
|
2487
|
+
// accumulating so stats stay honest, but the assignment is requeued.
|
|
2488
|
+
if (!(0, policy_2.rejectionBudgetExhausted)(assignment, policy) || policy.onMaxRejections === 'keep') {
|
|
2489
|
+
await this.addAssignment(assignment);
|
|
2490
|
+
return;
|
|
2491
|
+
}
|
|
2492
|
+
await this.applyRejectionExhaustion(assignment, policy, rejections, cause);
|
|
2493
|
+
}
|
|
2494
|
+
/**
|
|
2495
|
+
* Terminal step for an assignment whose rejection budget is exhausted:
|
|
2496
|
+
* parked or failed per `onMaxRejections`. The caller must already have
|
|
2497
|
+
* removed it from the pending structures.
|
|
2498
|
+
*/
|
|
2499
|
+
async applyRejectionExhaustion(assignment, policy, rejections, cause) {
|
|
2500
|
+
const action = policy.onMaxRejections === 'fail' ? 'fail' : 'park';
|
|
2501
|
+
const now = Date.now();
|
|
2502
|
+
// The assignment leaves the queued/pending universe: stop both clocks.
|
|
2503
|
+
const multi = this.redisClient
|
|
2504
|
+
.multi()
|
|
2505
|
+
.zRem(this.keys.assignmentsQueuedAt(), assignment.id)
|
|
2506
|
+
.zRem(this.assignmentsSlaExpiryKey, assignment.id);
|
|
2507
|
+
if (action === 'park') {
|
|
2508
|
+
multi.hSet(this.keys.parkedAssignments(), assignment.id, JSON.stringify(assignment));
|
|
2509
|
+
}
|
|
2510
|
+
else {
|
|
2511
|
+
multi.hSet(this.completedAssignmentsKey, assignment.id, JSON.stringify({
|
|
2512
|
+
...assignment,
|
|
2513
|
+
_failedAt: now,
|
|
2514
|
+
_failureReason: `rejection-budget-exhausted:${cause}`,
|
|
2515
|
+
}));
|
|
2516
|
+
}
|
|
2517
|
+
await multi.exec();
|
|
2518
|
+
this.emitAssignmentLifecycle({
|
|
2519
|
+
kind: 'rejectionBudgetExhausted',
|
|
2520
|
+
taskId: assignment.id,
|
|
2521
|
+
rejections,
|
|
2522
|
+
action,
|
|
2523
|
+
assignment,
|
|
2524
|
+
at: now,
|
|
2525
|
+
});
|
|
2526
|
+
if (action === 'park') {
|
|
2527
|
+
await this.bumpSlaStats(assignment.tags, { rejectionParked: 1 });
|
|
2528
|
+
}
|
|
2529
|
+
}
|
|
2161
2530
|
/**
|
|
2162
2531
|
* Complete an assignment with a result payload.
|
|
2163
2532
|
* Moves the assignment from 'accepted' to 'completed' state and publishes an event
|
|
@@ -2179,6 +2548,9 @@ class AssignmentMatcher {
|
|
|
2179
2548
|
// Move from accepted to completed
|
|
2180
2549
|
const multi = this.redisClient.multi();
|
|
2181
2550
|
multi.hDel(this.acceptedAssignmentsKey, assignmentId);
|
|
2551
|
+
// Clear SLA indexes (no-ops for non-SLA assignments)
|
|
2552
|
+
multi.zRem(this.acceptedAssignmentsExpiryKey, assignmentId);
|
|
2553
|
+
multi.zRem(this.assignmentsSlaExpiryKey, assignmentId);
|
|
2182
2554
|
// Store in completed with result metadata
|
|
2183
2555
|
const completedData = {
|
|
2184
2556
|
...assignment,
|
|
@@ -2188,6 +2560,9 @@ class AssignmentMatcher {
|
|
|
2188
2560
|
};
|
|
2189
2561
|
multi.hSet(this.completedAssignmentsKey, assignmentId, JSON.stringify(completedData));
|
|
2190
2562
|
await multi.exec();
|
|
2563
|
+
if (json.indexOf('"sla"') !== -1) {
|
|
2564
|
+
await this.recordSlaComplete(json, now);
|
|
2565
|
+
}
|
|
2191
2566
|
if (this.enableLearning) {
|
|
2192
2567
|
await this.learning.applyOutcome(assignmentId, 'complete');
|
|
2193
2568
|
}
|
|
@@ -2228,6 +2603,9 @@ class AssignmentMatcher {
|
|
|
2228
2603
|
// Move from accepted to completed (with failed status)
|
|
2229
2604
|
const multi = this.redisClient.multi();
|
|
2230
2605
|
multi.hDel(this.acceptedAssignmentsKey, assignmentId);
|
|
2606
|
+
// Clear SLA indexes (no-ops for non-SLA assignments)
|
|
2607
|
+
multi.zRem(this.acceptedAssignmentsExpiryKey, assignmentId);
|
|
2608
|
+
multi.zRem(this.assignmentsSlaExpiryKey, assignmentId);
|
|
2231
2609
|
const failedData = {
|
|
2232
2610
|
...assignment,
|
|
2233
2611
|
_failedBy: userId,
|
|
@@ -2433,16 +2811,50 @@ class AssignmentMatcher {
|
|
|
2433
2811
|
await this.readyPromise;
|
|
2434
2812
|
return this.workflow.getWorkflowMetrics();
|
|
2435
2813
|
}
|
|
2436
|
-
|
|
2814
|
+
/**
|
|
2815
|
+
* Requeue pending assignments whose response deadline elapsed, applying
|
|
2816
|
+
* each assignment's `EscalationPolicy` when it has one.
|
|
2817
|
+
*
|
|
2818
|
+
* Assignments without a policy take exactly the path they always did: the
|
|
2819
|
+
* owner loses the assignment, it returns to the open pool, and they may
|
|
2820
|
+
* win it again. With a policy the non-responder can be blocked, the
|
|
2821
|
+
* priority can climb, the tier tags can advance, and an exhausted ladder
|
|
2822
|
+
* can park the assignment instead of recirculating it forever.
|
|
2823
|
+
*
|
|
2824
|
+
* The wait clock (`assignmentsQueuedAt`) always survives: the requeue goes
|
|
2825
|
+
* through `addAssignment()`, whose `NX` keeps the original first-enqueue
|
|
2826
|
+
* time, so `oldestWaitingMs` measures the work item and not the tier.
|
|
2827
|
+
*/
|
|
2828
|
+
async processResponseDeadlines() {
|
|
2437
2829
|
await this.readyPromise;
|
|
2438
2830
|
const now = Date.now();
|
|
2439
2831
|
const expiredIds = await this.redisClient.zRangeByScore(this.pendingAssignmentsExpiryKey, '-inf', now);
|
|
2832
|
+
let escalations = 0;
|
|
2833
|
+
let parked = 0;
|
|
2440
2834
|
for (const id of expiredIds) {
|
|
2441
2835
|
const owner = await this.redisClient.hGet(this.assignmentOwnerKey, id);
|
|
2442
2836
|
const json = await this.redisClient.hGet(this.pendingAssignmentsKey, id);
|
|
2837
|
+
const assignment = json ? JSON.parse(json) : null;
|
|
2838
|
+
const policy = assignment ? (0, policy_1.normalizeEscalationPolicy)(assignment.escalation) : null;
|
|
2839
|
+
const slaPolicy = assignment ? (0, policy_2.normalizeSlaPolicy)(assignment.sla) : null;
|
|
2840
|
+
// A blocking no-response expiry counts as a refusal against the
|
|
2841
|
+
// SLA rejection budget (same as an explicit reject). Increment
|
|
2842
|
+
// before escalateAssignment() spreads the object so the decision
|
|
2843
|
+
// carries the bumped count.
|
|
2844
|
+
const countsAsRefusal = Boolean(policy && policy.onNoResponse === 'block' && owner);
|
|
2845
|
+
if (assignment && slaPolicy && countsAsRefusal) {
|
|
2846
|
+
assignment[policy_2.SLA_REJECTION_COUNT_FIELD] = (0, policy_2.rejectionCountOf)(assignment) + 1;
|
|
2847
|
+
}
|
|
2848
|
+
const decision = assignment && policy ? (0, policy_1.escalateAssignment)(assignment, policy) : null;
|
|
2443
2849
|
const multi = this.redisClient.multi();
|
|
2444
2850
|
if (owner) {
|
|
2445
2851
|
multi.sRem(this.keys.userAssignments(owner), `assignment:${id}`);
|
|
2852
|
+
// A blocking policy treats "never answered" as a soft rejection,
|
|
2853
|
+
// reusing the same rejected set an explicit reject writes to —
|
|
2854
|
+
// so the requeue cannot land back on the non-responder, and
|
|
2855
|
+
// decision traces already explain it as `rejectedPreviously`.
|
|
2856
|
+
if (decision?.blockPreviousOwner)
|
|
2857
|
+
multi.sAdd(this.keys.userRejected(owner), id);
|
|
2446
2858
|
}
|
|
2447
2859
|
multi.hDel(this.pendingAssignmentsKey, id);
|
|
2448
2860
|
multi.zRem(this.pendingAssignmentsExpiryKey, id);
|
|
@@ -2454,6 +2866,9 @@ class AssignmentMatcher {
|
|
|
2454
2866
|
workerId: owner ?? null,
|
|
2455
2867
|
expiredAt: now,
|
|
2456
2868
|
});
|
|
2869
|
+
if (assignment && slaPolicy) {
|
|
2870
|
+
await this.bumpSlaStats(assignment.tags, { acceptanceBreaches: 1 });
|
|
2871
|
+
}
|
|
2457
2872
|
if (this.enableLearning) {
|
|
2458
2873
|
await this.learning.applyOutcome(id, 'expire');
|
|
2459
2874
|
}
|
|
@@ -2467,12 +2882,371 @@ class AssignmentMatcher {
|
|
|
2467
2882
|
timestamp: now,
|
|
2468
2883
|
});
|
|
2469
2884
|
}
|
|
2470
|
-
if (
|
|
2471
|
-
|
|
2885
|
+
if (!assignment)
|
|
2886
|
+
continue;
|
|
2887
|
+
// The SLA rejection budget outranks the escalation ladder: once
|
|
2888
|
+
// nobody will take the work, tier hops are moot.
|
|
2889
|
+
if (slaPolicy &&
|
|
2890
|
+
countsAsRefusal &&
|
|
2891
|
+
(0, policy_2.rejectionBudgetExhausted)(assignment, slaPolicy) &&
|
|
2892
|
+
slaPolicy.onMaxRejections !== 'keep') {
|
|
2893
|
+
await this.applyRejectionExhaustion(assignment, slaPolicy, (0, policy_2.rejectionCountOf)(assignment), 'blocking-expiry');
|
|
2894
|
+
continue;
|
|
2895
|
+
}
|
|
2896
|
+
if (decision && decision.exhausted) {
|
|
2897
|
+
this.emitAssignmentLifecycle({
|
|
2898
|
+
kind: 'escalationExhausted',
|
|
2899
|
+
taskId: id,
|
|
2900
|
+
level: decision.level,
|
|
2901
|
+
parked: decision.onExhausted === 'park',
|
|
2902
|
+
at: now,
|
|
2903
|
+
});
|
|
2904
|
+
if (decision.onExhausted === 'park') {
|
|
2905
|
+
// Held out of matching entirely: no requeue, and the wait
|
|
2906
|
+
// clock is cleared so a parked item stops inflating
|
|
2907
|
+
// oldestWaitingMs for work that is still winnable.
|
|
2908
|
+
await this.redisClient
|
|
2909
|
+
.multi()
|
|
2910
|
+
.hSet(this.keys.parkedAssignments(), id, JSON.stringify(assignment))
|
|
2911
|
+
.zRem(this.keys.assignmentsQueuedAt(), id)
|
|
2912
|
+
.exec();
|
|
2913
|
+
parked++;
|
|
2914
|
+
continue;
|
|
2915
|
+
}
|
|
2916
|
+
await this.addAssignment(assignment);
|
|
2917
|
+
continue;
|
|
2918
|
+
}
|
|
2919
|
+
if (decision) {
|
|
2920
|
+
await this.addAssignment(decision.assignment);
|
|
2921
|
+
escalations++;
|
|
2922
|
+
this.emitAssignmentLifecycle({
|
|
2923
|
+
kind: 'escalated',
|
|
2924
|
+
taskId: id,
|
|
2925
|
+
fromWorkerId: owner ?? null,
|
|
2926
|
+
level: decision.level,
|
|
2927
|
+
blockedPreviousOwner: decision.blockPreviousOwner && Boolean(owner),
|
|
2928
|
+
reason: 'no-response',
|
|
2929
|
+
escalatedAt: now,
|
|
2930
|
+
});
|
|
2931
|
+
continue;
|
|
2932
|
+
}
|
|
2933
|
+
await this.addAssignment(assignment);
|
|
2934
|
+
}
|
|
2935
|
+
return { expired: expiredIds.length, escalations, parked };
|
|
2936
|
+
}
|
|
2937
|
+
/**
|
|
2938
|
+
* Backwards-compatible alias of `processResponseDeadlines()` returning
|
|
2939
|
+
* only the number of expired assignments.
|
|
2940
|
+
*/
|
|
2941
|
+
async processExpiredMatches() {
|
|
2942
|
+
const { expired } = await this.processResponseDeadlines();
|
|
2943
|
+
return expired;
|
|
2944
|
+
}
|
|
2945
|
+
/**
|
|
2946
|
+
* Sweep accepted assignments whose completion deadline
|
|
2947
|
+
* (`sla.completeWithinMs`, measured from accept) has elapsed.
|
|
2948
|
+
*
|
|
2949
|
+
* Each breached entry is removed from the deadline index before the
|
|
2950
|
+
* action runs, so a breach fires exactly once: a `'notify'` breach does
|
|
2951
|
+
* not re-fire every tick, and a `'requeue'`d assignment only gets a
|
|
2952
|
+
* fresh completion clock on its next accept.
|
|
2953
|
+
*/
|
|
2954
|
+
async processCompletionDeadlines() {
|
|
2955
|
+
await this.readyPromise;
|
|
2956
|
+
const now = Date.now();
|
|
2957
|
+
const breachedIds = await this.redisClient.zRangeByScore(this.acceptedAssignmentsExpiryKey, '-inf', now);
|
|
2958
|
+
let breached = 0;
|
|
2959
|
+
for (const id of breachedIds) {
|
|
2960
|
+
const json = await this.redisClient.hGet(this.acceptedAssignmentsKey, id);
|
|
2961
|
+
// Fire-once: drop the index entry first. If the assignment is
|
|
2962
|
+
// gone (completed/failed/removed between the zRange and now)
|
|
2963
|
+
// there is nothing to do.
|
|
2964
|
+
await this.redisClient.zRem(this.acceptedAssignmentsExpiryKey, id);
|
|
2965
|
+
if (!json)
|
|
2966
|
+
continue;
|
|
2967
|
+
const assignment = JSON.parse(json);
|
|
2968
|
+
const policy = (0, policy_2.normalizeSlaPolicy)(assignment.sla);
|
|
2969
|
+
if (!policy)
|
|
2970
|
+
continue;
|
|
2971
|
+
breached++;
|
|
2972
|
+
const record = assignment;
|
|
2973
|
+
const workerId = record[policy_2.SLA_ACCEPTED_BY_FIELD] ?? null;
|
|
2974
|
+
const action = policy.onCompletionBreach;
|
|
2975
|
+
this.emitAssignmentLifecycle({
|
|
2976
|
+
kind: 'completionBreached',
|
|
2977
|
+
taskId: id,
|
|
2978
|
+
workerId,
|
|
2979
|
+
action,
|
|
2980
|
+
assignment,
|
|
2981
|
+
at: now,
|
|
2982
|
+
});
|
|
2983
|
+
await this.bumpSlaStats(assignment.tags, { completionBreaches: 1 });
|
|
2984
|
+
if (this.enableLearning) {
|
|
2985
|
+
await this.learning.applyOutcome(id, action === 'fail' ? 'fail' : 'expire');
|
|
2986
|
+
}
|
|
2987
|
+
if (action === 'notify') {
|
|
2988
|
+
// Worker keeps the assignment; the event + learning outcome
|
|
2989
|
+
// above are the whole breach response.
|
|
2990
|
+
continue;
|
|
2472
2991
|
}
|
|
2992
|
+
if (action === 'requeue') {
|
|
2993
|
+
const multi = this.redisClient.multi().hDel(this.acceptedAssignmentsKey, id);
|
|
2994
|
+
if (workerId)
|
|
2995
|
+
multi.sAdd(this.keys.userRejected(workerId), id);
|
|
2996
|
+
await multi.exec();
|
|
2997
|
+
// The JSON still carries _enqueuedAt, so the freshness TTL
|
|
2998
|
+
// keeps ticking across the requeue. A requeue after a
|
|
2999
|
+
// completion breach is not a refusal: _rejectionCount is
|
|
3000
|
+
// untouched.
|
|
3001
|
+
await this.addAssignment(assignment);
|
|
3002
|
+
continue;
|
|
3003
|
+
}
|
|
3004
|
+
if (action === 'fail') {
|
|
3005
|
+
await this.redisClient
|
|
3006
|
+
.multi()
|
|
3007
|
+
.hDel(this.acceptedAssignmentsKey, id)
|
|
3008
|
+
.hSet(this.completedAssignmentsKey, id, JSON.stringify({
|
|
3009
|
+
...assignment,
|
|
3010
|
+
_failedBy: workerId,
|
|
3011
|
+
_failedAt: now,
|
|
3012
|
+
_failureReason: 'completion-sla-breach',
|
|
3013
|
+
}))
|
|
3014
|
+
// Terminal: the freshness TTL no longer applies.
|
|
3015
|
+
.zRem(this.assignmentsSlaExpiryKey, id)
|
|
3016
|
+
.exec();
|
|
3017
|
+
continue;
|
|
3018
|
+
}
|
|
3019
|
+
// 'park'
|
|
3020
|
+
await this.redisClient
|
|
3021
|
+
.multi()
|
|
3022
|
+
.hDel(this.acceptedAssignmentsKey, id)
|
|
3023
|
+
.hSet(this.keys.parkedAssignments(), id, JSON.stringify(assignment))
|
|
3024
|
+
.zRem(this.assignmentsSlaExpiryKey, id)
|
|
3025
|
+
.exec();
|
|
2473
3026
|
}
|
|
2474
|
-
return
|
|
3027
|
+
return { breached };
|
|
3028
|
+
}
|
|
3029
|
+
/**
|
|
3030
|
+
* Sweep assignments whose freshness TTL (`sla.expireAfterMs`, measured
|
|
3031
|
+
* from first enqueue) has elapsed. Applies in every state — queued,
|
|
3032
|
+
* pending, accepted — because stale work is stale regardless of who
|
|
3033
|
+
* holds it.
|
|
3034
|
+
*/
|
|
3035
|
+
async processSlaExpiries() {
|
|
3036
|
+
await this.readyPromise;
|
|
3037
|
+
const now = Date.now();
|
|
3038
|
+
const expiredIds = await this.redisClient.zRangeByScore(this.assignmentsSlaExpiryKey, '-inf', now);
|
|
3039
|
+
let expired = 0;
|
|
3040
|
+
for (const id of expiredIds) {
|
|
3041
|
+
// Locate the current store: pending (with owner), accepted, or queued.
|
|
3042
|
+
const [pendingJson, acceptedJson, queuedJson] = await Promise.all([
|
|
3043
|
+
this.redisClient.hGet(this.pendingAssignmentsKey, id),
|
|
3044
|
+
this.redisClient.hGet(this.acceptedAssignmentsKey, id),
|
|
3045
|
+
this.redisClient.hGet(this.assignmentsRefKey, id),
|
|
3046
|
+
]);
|
|
3047
|
+
const json = pendingJson ?? acceptedJson ?? queuedJson;
|
|
3048
|
+
// Stale index entry (already completed/failed/removed): just clean it.
|
|
3049
|
+
if (!json) {
|
|
3050
|
+
await this.redisClient.zRem(this.assignmentsSlaExpiryKey, id);
|
|
3051
|
+
continue;
|
|
3052
|
+
}
|
|
3053
|
+
const assignment = JSON.parse(json);
|
|
3054
|
+
const policy = (0, policy_2.normalizeSlaPolicy)(assignment.sla);
|
|
3055
|
+
if (!policy || policy.expireAfterMs === undefined) {
|
|
3056
|
+
await this.redisClient.zRem(this.assignmentsSlaExpiryKey, id);
|
|
3057
|
+
continue;
|
|
3058
|
+
}
|
|
3059
|
+
const ownerId = pendingJson
|
|
3060
|
+
? await this.redisClient.hGet(this.assignmentOwnerKey, id)
|
|
3061
|
+
: (assignment[policy_2.SLA_ACCEPTED_BY_FIELD] ?? null);
|
|
3062
|
+
const action = policy.onExpire;
|
|
3063
|
+
expired++;
|
|
3064
|
+
if (action === 'park') {
|
|
3065
|
+
await this.redisClient.hSet(this.keys.parkedAssignments(), id, JSON.stringify(assignment));
|
|
3066
|
+
}
|
|
3067
|
+
// Remove from whichever store it occupies, with full index cleanup.
|
|
3068
|
+
if (pendingJson) {
|
|
3069
|
+
const multi = this.redisClient.multi();
|
|
3070
|
+
if (ownerId)
|
|
3071
|
+
multi.sRem(this.keys.userAssignments(ownerId), `assignment:${id}`);
|
|
3072
|
+
multi.hDel(this.pendingAssignmentsKey, id);
|
|
3073
|
+
multi.zRem(this.pendingAssignmentsExpiryKey, id);
|
|
3074
|
+
multi.hDel(this.assignmentOwnerKey, id);
|
|
3075
|
+
multi.zRem(this.assignmentsSlaExpiryKey, id);
|
|
3076
|
+
// Leaving the queued/pending universe: the wait clock stops.
|
|
3077
|
+
multi.zRem(this.keys.assignmentsQueuedAt(), id);
|
|
3078
|
+
await multi.exec();
|
|
3079
|
+
}
|
|
3080
|
+
else if (acceptedJson) {
|
|
3081
|
+
await this.redisClient
|
|
3082
|
+
.multi()
|
|
3083
|
+
.hDel(this.acceptedAssignmentsKey, id)
|
|
3084
|
+
.zRem(this.acceptedAssignmentsExpiryKey, id)
|
|
3085
|
+
.zRem(this.assignmentsSlaExpiryKey, id)
|
|
3086
|
+
.exec();
|
|
3087
|
+
}
|
|
3088
|
+
else {
|
|
3089
|
+
// Queued: full index cleanup via removeAssignment (also zRems
|
|
3090
|
+
// the SLA expiry index).
|
|
3091
|
+
await this.removeAssignment(id);
|
|
3092
|
+
}
|
|
3093
|
+
this.emitAssignmentLifecycle({
|
|
3094
|
+
kind: 'slaExpired',
|
|
3095
|
+
taskId: id,
|
|
3096
|
+
ownerId,
|
|
3097
|
+
action,
|
|
3098
|
+
// Emitted after the removal above, so this snapshot is the only
|
|
3099
|
+
// remaining copy on the 'drop' path.
|
|
3100
|
+
assignment,
|
|
3101
|
+
at: now,
|
|
3102
|
+
});
|
|
3103
|
+
await this.bumpSlaStats(assignment.tags, { ttlExpiries: 1 });
|
|
3104
|
+
if (this.enableLearning) {
|
|
3105
|
+
await this.learning.applyOutcome(id, 'expire');
|
|
3106
|
+
}
|
|
3107
|
+
}
|
|
3108
|
+
return { expired };
|
|
3109
|
+
}
|
|
3110
|
+
/**
|
|
3111
|
+
* Assignments held out of matching because their escalation ladder was
|
|
3112
|
+
* exhausted under `onExhausted: 'park'` — nobody answered, all the way up.
|
|
3113
|
+
*/
|
|
3114
|
+
async getParkedAssignments() {
|
|
3115
|
+
await this.readyPromise;
|
|
3116
|
+
const all = await this.redisClient.hGetAll(this.keys.parkedAssignments());
|
|
3117
|
+
return Object.values(all).map((json) => JSON.parse(json));
|
|
3118
|
+
}
|
|
3119
|
+
/**
|
|
3120
|
+
* Return a parked assignment to the queue, optionally resetting its
|
|
3121
|
+
* escalation level so the ladder can run again from the top.
|
|
3122
|
+
*
|
|
3123
|
+
* `resetSla` clears the first-enqueue clock and rejection counter.
|
|
3124
|
+
* Without it an unparked assignment whose freshness TTL already elapsed
|
|
3125
|
+
* will simply expire again on the next TTL sweep.
|
|
3126
|
+
*
|
|
3127
|
+
* @returns false when the id was not parked
|
|
3128
|
+
*/
|
|
3129
|
+
async unparkAssignment(id, opts) {
|
|
3130
|
+
await this.readyPromise;
|
|
3131
|
+
const json = await this.redisClient.hGet(this.keys.parkedAssignments(), id);
|
|
3132
|
+
if (!json)
|
|
3133
|
+
return false;
|
|
3134
|
+
const assignment = JSON.parse(json);
|
|
3135
|
+
const record = assignment;
|
|
3136
|
+
if (opts?.resetEscalation)
|
|
3137
|
+
delete record._escalationLevel;
|
|
3138
|
+
if (opts?.resetSla) {
|
|
3139
|
+
delete record[policy_2.SLA_ENQUEUED_AT_FIELD];
|
|
3140
|
+
delete record[policy_2.SLA_REJECTION_COUNT_FIELD];
|
|
3141
|
+
delete record[policy_2.SLA_MATCHED_AT_FIELD];
|
|
3142
|
+
delete record[policy_2.SLA_ACCEPTED_AT_FIELD];
|
|
3143
|
+
delete record[policy_2.SLA_ACCEPTED_BY_FIELD];
|
|
3144
|
+
}
|
|
3145
|
+
await this.redisClient.hDel(this.keys.parkedAssignments(), id);
|
|
3146
|
+
await this.addAssignment(assignment);
|
|
3147
|
+
return true;
|
|
3148
|
+
}
|
|
3149
|
+
/** Current escalation level of an assignment (0 = never escalated). */
|
|
3150
|
+
async getEscalationLevel(id) {
|
|
3151
|
+
await this.readyPromise;
|
|
3152
|
+
const assignment = await this.getAssignment(id);
|
|
3153
|
+
return assignment ? (0, policy_1.escalationLevelOf)(assignment) : 0;
|
|
3154
|
+
}
|
|
3155
|
+
/**
|
|
3156
|
+
* Run every enabled maintenance sweep once: response deadlines and
|
|
3157
|
+
* escalations, workflow step timeouts, and idle-user release.
|
|
3158
|
+
*
|
|
3159
|
+
* Deadlines are not self-firing — something has to sweep them. Hosts that
|
|
3160
|
+
* already own a tick (a multi-tenant worker, a serverless schedule) should
|
|
3161
|
+
* call this instead of holding a timer per matcher; everyone else should
|
|
3162
|
+
* call `startMaintenance()` once and forget about it.
|
|
3163
|
+
*/
|
|
3164
|
+
async runMaintenanceOnce(options) {
|
|
3165
|
+
await this.readyPromise;
|
|
3166
|
+
const startedAt = Date.now();
|
|
3167
|
+
const opts = this.resolveMaintenanceOptions(options);
|
|
3168
|
+
let expiredMatches = 0;
|
|
3169
|
+
let escalations = 0;
|
|
3170
|
+
let parked = 0;
|
|
3171
|
+
let expiredSteps = 0;
|
|
3172
|
+
let releasedIdleUsers = 0;
|
|
3173
|
+
let completionBreaches = 0;
|
|
3174
|
+
let slaExpiries = 0;
|
|
3175
|
+
if (opts.responseDeadlines) {
|
|
3176
|
+
const result = await this.processResponseDeadlines();
|
|
3177
|
+
expiredMatches = result.expired;
|
|
3178
|
+
escalations = result.escalations;
|
|
3179
|
+
parked = result.parked;
|
|
3180
|
+
}
|
|
3181
|
+
if (opts.completionDeadlines) {
|
|
3182
|
+
completionBreaches = (await this.processCompletionDeadlines()).breached;
|
|
3183
|
+
}
|
|
3184
|
+
if (opts.slaExpiries) {
|
|
3185
|
+
slaExpiries = (await this.processSlaExpiries()).expired;
|
|
3186
|
+
}
|
|
3187
|
+
if (opts.workflowStepTimeouts && this.enableWorkflows) {
|
|
3188
|
+
expiredSteps = await this.processExpiredWorkflowSteps();
|
|
3189
|
+
}
|
|
3190
|
+
if (opts.idleUsers && this.idleUserTimeoutMs !== null) {
|
|
3191
|
+
releasedIdleUsers = (await this.processIdleUsers()).length;
|
|
3192
|
+
}
|
|
3193
|
+
return {
|
|
3194
|
+
expiredMatches,
|
|
3195
|
+
escalations,
|
|
3196
|
+
parked,
|
|
3197
|
+
expiredSteps,
|
|
3198
|
+
releasedIdleUsers,
|
|
3199
|
+
completionBreaches,
|
|
3200
|
+
slaExpiries,
|
|
3201
|
+
tookMs: Date.now() - startedAt,
|
|
3202
|
+
};
|
|
3203
|
+
}
|
|
3204
|
+
/**
|
|
3205
|
+
* Start the periodic maintenance tick. Idempotent; a second call with
|
|
3206
|
+
* different options replaces the first.
|
|
3207
|
+
*
|
|
3208
|
+
* @param options.intervalMs how often to sweep (default 5000)
|
|
3209
|
+
*/
|
|
3210
|
+
startMaintenance(options) {
|
|
3211
|
+
this.stopMaintenance();
|
|
3212
|
+
this.maintenanceOptions = this.resolveMaintenanceOptions(options);
|
|
3213
|
+
const intervalMs = options?.intervalMs ?? 5000;
|
|
3214
|
+
this.maintenanceInterval = setInterval(() => {
|
|
3215
|
+
// Skip a tick rather than pile up overlapping sweeps when a pass
|
|
3216
|
+
// takes longer than the interval.
|
|
3217
|
+
if (this.maintenanceRunning)
|
|
3218
|
+
return;
|
|
3219
|
+
this.maintenanceRunning = true;
|
|
3220
|
+
this.runMaintenanceOnce(this.maintenanceOptions ?? undefined)
|
|
3221
|
+
.catch((err) => console.error('Maintenance tick failed:', err))
|
|
3222
|
+
.finally(() => {
|
|
3223
|
+
this.maintenanceRunning = false;
|
|
3224
|
+
});
|
|
3225
|
+
}, intervalMs);
|
|
3226
|
+
this.maintenanceInterval.unref?.();
|
|
3227
|
+
}
|
|
3228
|
+
/** Stop the periodic maintenance tick. Safe to call when not started. */
|
|
3229
|
+
stopMaintenance() {
|
|
3230
|
+
if (this.maintenanceInterval) {
|
|
3231
|
+
clearInterval(this.maintenanceInterval);
|
|
3232
|
+
this.maintenanceInterval = null;
|
|
3233
|
+
}
|
|
3234
|
+
this.maintenanceOptions = null;
|
|
3235
|
+
}
|
|
3236
|
+
/** Whether the maintenance tick is currently running. */
|
|
3237
|
+
isMaintenanceRunning() {
|
|
3238
|
+
return this.maintenanceInterval !== null;
|
|
3239
|
+
}
|
|
3240
|
+
resolveMaintenanceOptions(options) {
|
|
3241
|
+
return {
|
|
3242
|
+
responseDeadlines: options?.responseDeadlines ?? true,
|
|
3243
|
+
completionDeadlines: options?.completionDeadlines ?? true,
|
|
3244
|
+
slaExpiries: options?.slaExpiries ?? true,
|
|
3245
|
+
workflowStepTimeouts: options?.workflowStepTimeouts ?? this.enableWorkflows,
|
|
3246
|
+
idleUsers: options?.idleUsers ?? this.idleUserTimeoutMs !== null,
|
|
3247
|
+
};
|
|
2475
3248
|
}
|
|
3249
|
+
/** @deprecated Use `startMaintenance()`, which also sweeps workflow step timeouts. */
|
|
2476
3250
|
startAutoReleaseInterval(intervalMs = 10000) {
|
|
2477
3251
|
if (this.autoReleaseInterval)
|
|
2478
3252
|
return;
|