assignment-user-matcher 1.10.0 → 1.12.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 +106 -13
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/learning/auto-weights.d.ts +7 -4
- package/dist/learning/auto-weights.d.ts.map +1 -1
- package/dist/learning/auto-weights.js +7 -6
- package/dist/lua/workflow-transition.lua +8 -2
- package/dist/managers/LearningManager.d.ts.map +1 -1
- package/dist/managers/LearningManager.js +47 -0
- package/dist/managers/WorkflowManager.d.ts +7 -1
- package/dist/managers/WorkflowManager.d.ts.map +1 -1
- package/dist/managers/WorkflowManager.js +85 -12
- package/dist/matcher.class.d.ts +84 -3
- package/dist/matcher.class.d.ts.map +1 -1
- package/dist/matcher.class.js +498 -76
- package/dist/queries/users.d.ts +34 -0
- package/dist/queries/users.d.ts.map +1 -0
- package/dist/queries/users.js +227 -0
- package/dist/schedule/recurrence.d.ts +82 -0
- package/dist/schedule/recurrence.d.ts.map +1 -0
- package/dist/schedule/recurrence.js +145 -0
- package/dist/scheduling/constraints/availability.d.ts +0 -1
- package/dist/scheduling/constraints/availability.d.ts.map +1 -1
- package/dist/scheduling/constraints/availability.js +27 -4
- package/dist/scheduling/constraints/contract.d.ts.map +1 -1
- package/dist/scheduling/constraints/contract.js +17 -3
- package/dist/scheduling/constraints/daily-rest.d.ts.map +1 -1
- package/dist/scheduling/constraints/daily-rest.js +7 -2
- package/dist/scheduling/constraints/hour-budget.d.ts.map +1 -1
- package/dist/scheduling/constraints/hour-budget.js +7 -1
- package/dist/scheduling/constraints/in-shift-breaks.d.ts.map +1 -1
- package/dist/scheduling/constraints/in-shift-breaks.js +4 -2
- package/dist/scheduling/constraints/min-rest.d.ts.map +1 -1
- package/dist/scheduling/constraints/min-rest.js +8 -19
- package/dist/scheduling/constraints/night-work.js +17 -1
- package/dist/scheduling/constraints/no-overlap.d.ts +5 -1
- package/dist/scheduling/constraints/no-overlap.d.ts.map +1 -1
- package/dist/scheduling/constraints/no-overlap.js +11 -12
- package/dist/scheduling/constraints/weekly-rest.js +12 -1
- package/dist/scheduling/engine/construction.d.ts.map +1 -1
- package/dist/scheduling/engine/construction.js +7 -0
- package/dist/scheduling/model.d.ts.map +1 -1
- package/dist/scheduling/model.js +1 -0
- package/dist/scheduling/time.d.ts +6 -0
- package/dist/scheduling/time.d.ts.map +1 -1
- package/dist/scheduling/time.js +20 -9
- package/dist/scheduling/types.d.ts +6 -0
- package/dist/scheduling/types.d.ts.map +1 -1
- package/dist/types/matcher.d.ts +197 -5
- package/dist/types/matcher.d.ts.map +1 -1
- package/dist/utils/keys.d.ts +3 -0
- package/dist/utils/keys.d.ts.map +1 -1
- package/dist/utils/keys.js +17 -0
- package/package.json +1 -1
package/dist/matcher.class.js
CHANGED
|
@@ -7,11 +7,13 @@ const cidr_1 = require("./utils/cidr");
|
|
|
7
7
|
const geo_1 = require("./utils/geo");
|
|
8
8
|
const keys_1 = require("./utils/keys");
|
|
9
9
|
const pagination_1 = require("./queries/pagination");
|
|
10
|
+
const users_1 = require("./queries/users");
|
|
10
11
|
const match_score_1 = require("./scoring/match-score");
|
|
11
12
|
const fair_arbitration_1 = require("./scoring/fair-arbitration");
|
|
12
13
|
const policy_1 = require("./escalation/policy");
|
|
13
14
|
const policy_2 = require("./sla/policy");
|
|
14
15
|
const policy_3 = require("./schedule/policy");
|
|
16
|
+
const recurrence_1 = require("./schedule/recurrence");
|
|
15
17
|
const assignment_lint_1 = require("./validation/assignment-lint");
|
|
16
18
|
const decision_trace_1 = require("./tracing/decision-trace");
|
|
17
19
|
const features_1 = require("./learning/features");
|
|
@@ -71,6 +73,8 @@ class AssignmentMatcher {
|
|
|
71
73
|
this.scheduledAssignmentsKey = this.keys.scheduledAssignments();
|
|
72
74
|
this.scheduledActivateAtKey = this.keys.scheduledActivateAt();
|
|
73
75
|
this.scheduleNotAfterKey = this.keys.scheduleNotAfter();
|
|
76
|
+
this.recurringAssignmentsKey = this.keys.recurringAssignments();
|
|
77
|
+
this.recurringDueAtKey = this.keys.recurringDueAt();
|
|
74
78
|
this.completedAssignmentsKey = this.keys.completedAssignments();
|
|
75
79
|
this.calculatePriority = options?.prioritizationFunction ?? this.calculatePriority;
|
|
76
80
|
this.usingDefaultMatchScore = !options?.matchingFunction;
|
|
@@ -297,7 +301,9 @@ class AssignmentMatcher {
|
|
|
297
301
|
async loadLuaScripts() {
|
|
298
302
|
try {
|
|
299
303
|
this.luaScriptSha = await this.redisClient.scriptLoad(WORKFLOW_TRANSITION_LUA);
|
|
300
|
-
|
|
304
|
+
// The source rides along so a NOSCRIPT after a Redis restart can
|
|
305
|
+
// be answered with a re-load instead of bricking every transition.
|
|
306
|
+
this.workflow.setLuaScriptSha(this.luaScriptSha, WORKFLOW_TRANSITION_LUA);
|
|
301
307
|
}
|
|
302
308
|
catch (err) {
|
|
303
309
|
console.error('Failed to load Lua scripts:', err);
|
|
@@ -1126,7 +1132,13 @@ class AssignmentMatcher {
|
|
|
1126
1132
|
const existingForSynthesis = user.routingWeights
|
|
1127
1133
|
? Object.fromEntries(Object.entries(user.routingWeights).filter(([tag]) => !(tag in previousLearned)))
|
|
1128
1134
|
: undefined;
|
|
1129
|
-
|
|
1135
|
+
// The user's own declared tags are always known: once the sync
|
|
1136
|
+
// installs a routingWeights map, only positive entries match, so a
|
|
1137
|
+
// declared tag the learner has no data for would silently stop
|
|
1138
|
+
// matching forever. Including it here gives it the exploration
|
|
1139
|
+
// prior instead.
|
|
1140
|
+
const userKnownTags = [...new Set([...(knownTags ?? []), ...(user.tags ?? [])])];
|
|
1141
|
+
const learned = await this.learning.getLearnedRoutingWeights(id, userKnownTags.length > 0 ? userKnownTags : undefined, existingForSynthesis);
|
|
1130
1142
|
if (Object.keys(learned).length === 0)
|
|
1131
1143
|
continue;
|
|
1132
1144
|
// Apply per-sync step clamp. Vetoes (weight 0) that passed the
|
|
@@ -1164,7 +1176,11 @@ class AssignmentMatcher {
|
|
|
1164
1176
|
await this.redisClient.hSet(this.usersKey, id, JSON.stringify({
|
|
1165
1177
|
...user,
|
|
1166
1178
|
routingWeights,
|
|
1167
|
-
|
|
1179
|
+
// `null` (not undefined) for a previously weightless user:
|
|
1180
|
+
// undefined is dropped by JSON, which made the sync
|
|
1181
|
+
// irreversible for exactly the tag-based users it affects
|
|
1182
|
+
// the most. Revert restores tag-based matching from null.
|
|
1183
|
+
routingWeightsSnapshot: user.routingWeights ?? null,
|
|
1168
1184
|
learnedRoutingWeights: clampedLearned,
|
|
1169
1185
|
learnedRoutingWeightsSyncedAt: Date.now(),
|
|
1170
1186
|
}));
|
|
@@ -1189,7 +1205,7 @@ class AssignmentMatcher {
|
|
|
1189
1205
|
for (const [id, json] of Object.entries(all)) {
|
|
1190
1206
|
try {
|
|
1191
1207
|
const u = JSON.parse(json);
|
|
1192
|
-
if (u.routingWeightsSnapshot)
|
|
1208
|
+
if (u.routingWeightsSnapshot !== undefined)
|
|
1193
1209
|
targets.push(id);
|
|
1194
1210
|
}
|
|
1195
1211
|
catch {
|
|
@@ -1203,11 +1219,13 @@ class AssignmentMatcher {
|
|
|
1203
1219
|
if (!userJson)
|
|
1204
1220
|
continue;
|
|
1205
1221
|
const user = JSON.parse(userJson);
|
|
1206
|
-
|
|
1222
|
+
// A `null` snapshot means "had no routingWeights before the sync"
|
|
1223
|
+
// — reverting restores tag-based matching by dropping the map.
|
|
1224
|
+
if (user.routingWeightsSnapshot === undefined)
|
|
1207
1225
|
continue;
|
|
1208
1226
|
await this.redisClient.hSet(this.usersKey, id, JSON.stringify({
|
|
1209
1227
|
...user,
|
|
1210
|
-
routingWeights: user.routingWeightsSnapshot,
|
|
1228
|
+
routingWeights: user.routingWeightsSnapshot ?? undefined,
|
|
1211
1229
|
routingWeightsSnapshot: undefined,
|
|
1212
1230
|
learnedRoutingWeights: undefined,
|
|
1213
1231
|
learnedRoutingWeightsSyncedAt: undefined,
|
|
@@ -1255,7 +1273,10 @@ class AssignmentMatcher {
|
|
|
1255
1273
|
}
|
|
1256
1274
|
/** All known tags except the internal 'default' tag (for exploration priors) */
|
|
1257
1275
|
async getKnownTagsForAutoWeights() {
|
|
1258
|
-
|
|
1276
|
+
// allTags is a ZSET (zAdd in enqueueAssignment, zRangeByLex in wildcard
|
|
1277
|
+
// expansion) — an SMEMBERS read threw WRONGTYPE on any deployment that
|
|
1278
|
+
// had ever enqueued an assignment.
|
|
1279
|
+
const tags = await this.redisClient.zRange(this.allTagsKey, 0, -1);
|
|
1259
1280
|
return tags.filter((t) => t !== 'default');
|
|
1260
1281
|
}
|
|
1261
1282
|
// ============================================================================
|
|
@@ -1398,12 +1419,26 @@ class AssignmentMatcher {
|
|
|
1398
1419
|
const assignmentPriorityKey = this.keys.assignmentPriority(id);
|
|
1399
1420
|
const assignmentTagsKey = this.keys.assignmentTags(id);
|
|
1400
1421
|
const assignmentGeoKey = this.keys.assignmentsGeo();
|
|
1401
|
-
// Fetch tags, owner (in case it's pending),
|
|
1402
|
-
|
|
1422
|
+
// Fetch tags, owner (in case it's pending), accepted JSON (for the
|
|
1423
|
+
// per-user accepted index), and vetoed users for index cleanup
|
|
1424
|
+
const [tagsCsv, owner, acceptedJson, vetoedUsers] = await Promise.all([
|
|
1403
1425
|
this.redisClient.hGet(assignmentTagsKey, 'tags'),
|
|
1404
1426
|
this.redisClient.hGet(this.assignmentOwnerKey, id),
|
|
1427
|
+
this.redisClient.hGet(this.acceptedAssignmentsKey, id),
|
|
1405
1428
|
this.redisClient.sMembers(this.keys.assignmentVetoed(id)),
|
|
1406
1429
|
]);
|
|
1430
|
+
// Best-effort owner of the accepted record: only SLA-bearing items
|
|
1431
|
+
// carry _acceptedBy, so a non-SLA accepted assignment leaves a stale
|
|
1432
|
+
// per-user index member here — reads filter it out and self-heal.
|
|
1433
|
+
let acceptedBy = null;
|
|
1434
|
+
if (acceptedJson && acceptedJson.indexOf('"sla"') !== -1) {
|
|
1435
|
+
try {
|
|
1436
|
+
acceptedBy = JSON.parse(acceptedJson)[policy_2.SLA_ACCEPTED_BY_FIELD] ?? null;
|
|
1437
|
+
}
|
|
1438
|
+
catch {
|
|
1439
|
+
// keep null on parse failure
|
|
1440
|
+
}
|
|
1441
|
+
}
|
|
1407
1442
|
let tags = [];
|
|
1408
1443
|
if (tagsCsv && tagsCsv.length > 0) {
|
|
1409
1444
|
tags = tagsCsv.split(',');
|
|
@@ -1432,6 +1467,9 @@ class AssignmentMatcher {
|
|
|
1432
1467
|
}
|
|
1433
1468
|
// 3. Remove from Accepted state
|
|
1434
1469
|
multi.hDel(this.acceptedAssignmentsKey, id);
|
|
1470
|
+
if (acceptedBy) {
|
|
1471
|
+
multi.zRem(this.keys.userAcceptedAssignments(acceptedBy), id);
|
|
1472
|
+
}
|
|
1435
1473
|
// 4. Clear SLA indexes (no-ops for non-SLA assignments)
|
|
1436
1474
|
multi.zRem(this.acceptedAssignmentsExpiryKey, id);
|
|
1437
1475
|
multi.zRem(this.assignmentsSlaExpiryKey, id);
|
|
@@ -1449,6 +1487,7 @@ class AssignmentMatcher {
|
|
|
1449
1487
|
.del(this.keys.userAssignments(userId))
|
|
1450
1488
|
.del(this.keys.userRejected(userId))
|
|
1451
1489
|
.del(this.keys.userVetoed(userId))
|
|
1490
|
+
.del(this.keys.userAcceptedAssignments(userId))
|
|
1452
1491
|
.zRem(this.keys.userActivity(), userId)
|
|
1453
1492
|
.sRem(this.keys.pausedUsers(), userId)
|
|
1454
1493
|
.hDel(this.usersKey, userId);
|
|
@@ -1480,11 +1519,58 @@ class AssignmentMatcher {
|
|
|
1480
1519
|
let cursor = '0';
|
|
1481
1520
|
do {
|
|
1482
1521
|
const { cursor: nextCursor, entries } = await this.redisClient.hScan(this.usersKey, cursor, { COUNT: 500 });
|
|
1483
|
-
|
|
1522
|
+
for (const entry of entries) {
|
|
1523
|
+
try {
|
|
1524
|
+
users.push(JSON.parse(entry.value));
|
|
1525
|
+
}
|
|
1526
|
+
catch {
|
|
1527
|
+
// Skip corrupt entries (same precedent as getAllAssignmentsFromStores)
|
|
1528
|
+
}
|
|
1529
|
+
}
|
|
1484
1530
|
cursor = nextCursor;
|
|
1485
1531
|
} while (cursor !== '0');
|
|
1486
1532
|
return users;
|
|
1487
1533
|
}
|
|
1534
|
+
/**
|
|
1535
|
+
* Paginated user query with composable status/workload filters
|
|
1536
|
+
* (`status`, `idleForMs`, `hasBacklog`, `atCapacity`). All reads are
|
|
1537
|
+
* bounded: the users hash is paged with HSCAN and per-page metadata is
|
|
1538
|
+
* batched into one multi(). A scan page is never split, so a page may
|
|
1539
|
+
* exceed `limit` by less than one scan page, and filtered scans may
|
|
1540
|
+
* return short pages with `hasMore: true` — keep consuming until
|
|
1541
|
+
* `hasMore` is false. `status: 'idle'` without an explicit `idleForMs`
|
|
1542
|
+
* falls back to the matcher's `idleUserTimeoutMs` (matches nobody when
|
|
1543
|
+
* that is not configured either).
|
|
1544
|
+
*/
|
|
1545
|
+
async getUsersPaginated(options) {
|
|
1546
|
+
await this.readyPromise;
|
|
1547
|
+
const resolved = options ? { ...options } : undefined;
|
|
1548
|
+
if (resolved && resolved.idleForMs === undefined && resolved.status === 'idle' && this.idleUserTimeoutMs !== null) {
|
|
1549
|
+
resolved.idleForMs = this.idleUserTimeoutMs;
|
|
1550
|
+
}
|
|
1551
|
+
return (0, users_1.getUsersPaginatedFromStore)(this.redisClient, this.keys, resolved, (user) => this.backlogLimitFor(user));
|
|
1552
|
+
}
|
|
1553
|
+
/**
|
|
1554
|
+
* Order-preserving workload summaries for a known set of user ids
|
|
1555
|
+
* (chunked pipelined reads). Missing or corrupt user records are omitted.
|
|
1556
|
+
*/
|
|
1557
|
+
async getUserSummaries(userIds) {
|
|
1558
|
+
await this.readyPromise;
|
|
1559
|
+
return (0, users_1.getUserSummariesBatch)(this.redisClient, this.keys, userIds, (user) => this.backlogLimitFor(user));
|
|
1560
|
+
}
|
|
1561
|
+
/**
|
|
1562
|
+
* A user's accepted (in-progress) assignments, newest first, backed by
|
|
1563
|
+
* the per-user accepted index. Verified against the accepted store, so
|
|
1564
|
+
* stale index members (e.g. left by a `removeAssignment` on a non-SLA
|
|
1565
|
+
* assignment, or by an older library version) are dropped and self-healed.
|
|
1566
|
+
*
|
|
1567
|
+
* Note: the index is maintained from the version that introduced it —
|
|
1568
|
+
* accepted work that predates it appears only after it cycles.
|
|
1569
|
+
*/
|
|
1570
|
+
async getActiveAssignmentsForUser(userId) {
|
|
1571
|
+
await this.readyPromise;
|
|
1572
|
+
return (0, users_1.getActiveAssignmentsFromStore)(this.redisClient, this.keys, userId);
|
|
1573
|
+
}
|
|
1488
1574
|
// ============================================================================
|
|
1489
1575
|
// Worker Availability (pause/resume)
|
|
1490
1576
|
// ============================================================================
|
|
@@ -1601,15 +1687,35 @@ class AssignmentMatcher {
|
|
|
1601
1687
|
let cursor = '0';
|
|
1602
1688
|
do {
|
|
1603
1689
|
const { cursor: nextCursor, entries } = await this.redisClient.hScan(this.usersKey, cursor, { COUNT: 500 });
|
|
1604
|
-
|
|
1690
|
+
for (const entry of entries) {
|
|
1691
|
+
try {
|
|
1692
|
+
users.push(JSON.parse(entry.value));
|
|
1693
|
+
}
|
|
1694
|
+
catch {
|
|
1695
|
+
// Skip corrupt entries (same precedent as getAllAssignmentsFromStores)
|
|
1696
|
+
}
|
|
1697
|
+
}
|
|
1605
1698
|
cursor = nextCursor;
|
|
1606
1699
|
} while (cursor !== '0');
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
|
|
1612
|
-
|
|
1700
|
+
// Chunked pipelined backlog reads — one multi() per 500 users keeps
|
|
1701
|
+
// pipelines bounded when the pool grows.
|
|
1702
|
+
const perUser = [];
|
|
1703
|
+
for (let start = 0; start < users.length; start += 500) {
|
|
1704
|
+
const chunk = users.slice(start, start + 500);
|
|
1705
|
+
const multi = this.redisClient.multi();
|
|
1706
|
+
for (const user of chunk) {
|
|
1707
|
+
multi.sCard(this.keys.userAssignments(user.id));
|
|
1708
|
+
}
|
|
1709
|
+
const backlogs = (await multi.exec());
|
|
1710
|
+
for (let i = 0; i < chunk.length; i++) {
|
|
1711
|
+
perUser.push({
|
|
1712
|
+
userId: chunk[i].id,
|
|
1713
|
+
backlog: Number(backlogs[i] ?? 0),
|
|
1714
|
+
maxBacklogSize: this.backlogLimitFor(chunk[i]),
|
|
1715
|
+
paused: paused.has(chunk[i].id),
|
|
1716
|
+
});
|
|
1717
|
+
}
|
|
1718
|
+
}
|
|
1613
1719
|
perUser.sort((a, b) => a.userId.localeCompare(b.userId));
|
|
1614
1720
|
return {
|
|
1615
1721
|
queued: counts.queued,
|
|
@@ -1621,43 +1727,79 @@ class AssignmentMatcher {
|
|
|
1621
1727
|
}
|
|
1622
1728
|
/**
|
|
1623
1729
|
* Get all pending assignments with owner and pending duration metadata.
|
|
1730
|
+
* Reads are bounded: the pending hash is paged with HSCAN and each page's
|
|
1731
|
+
* owner/expiry lookups are batched. Pass `{ limit }` (clamped to 1000) to
|
|
1732
|
+
* hydrate only the top-N longest-pending assignments instead of every one.
|
|
1624
1733
|
*/
|
|
1625
|
-
async getPendingAssignmentsWithAge() {
|
|
1734
|
+
async getPendingAssignmentsWithAge(options) {
|
|
1626
1735
|
await this.readyPromise;
|
|
1627
1736
|
const now = Date.now();
|
|
1628
|
-
const
|
|
1629
|
-
|
|
1630
|
-
|
|
1737
|
+
const metas = [];
|
|
1738
|
+
// HSCAN may repeat a field across pages under a concurrent rehash;
|
|
1739
|
+
// the listing must not repeat an assignment.
|
|
1740
|
+
const seen = new Set();
|
|
1741
|
+
let cursor = '0';
|
|
1742
|
+
do {
|
|
1743
|
+
const { cursor: nextCursor, entries: rawEntries } = await this.redisClient.hScan(this.pendingAssignmentsKey, cursor, { COUNT: 500 });
|
|
1744
|
+
cursor = nextCursor;
|
|
1745
|
+
const entries = rawEntries.filter((entry) => !seen.has(entry.field));
|
|
1746
|
+
if (entries.length === 0)
|
|
1747
|
+
continue;
|
|
1748
|
+
for (const entry of entries)
|
|
1749
|
+
seen.add(entry.field);
|
|
1750
|
+
const pageIds = entries.map((entry) => entry.field);
|
|
1751
|
+
const owners = await this.redisClient.hmGet(this.assignmentOwnerKey, pageIds);
|
|
1752
|
+
const multi = this.redisClient.multi();
|
|
1753
|
+
for (const id of pageIds) {
|
|
1754
|
+
multi.zScore(this.pendingAssignmentsExpiryKey, id);
|
|
1755
|
+
}
|
|
1756
|
+
const expiryScores = (await multi.exec());
|
|
1757
|
+
for (let i = 0; i < entries.length; i++) {
|
|
1758
|
+
const json = entries[i].value;
|
|
1759
|
+
if (!json)
|
|
1760
|
+
continue;
|
|
1761
|
+
const score = expiryScores[i];
|
|
1762
|
+
const expiresAt = score === null || score === undefined ? null : Number(score);
|
|
1763
|
+
const pendingSince = expiresAt === null ? null : expiresAt - this.matchExpirationMs;
|
|
1764
|
+
const pendingForMs = pendingSince === null ? null : Math.max(0, now - pendingSince);
|
|
1765
|
+
metas.push({ json, ownerId: owners[i] ?? null, pendingForMs, pendingSince, expiresAt });
|
|
1766
|
+
}
|
|
1767
|
+
} while (cursor !== '0');
|
|
1768
|
+
if (metas.length === 0) {
|
|
1631
1769
|
return [];
|
|
1632
1770
|
}
|
|
1633
|
-
const
|
|
1634
|
-
this.redisClient.hmGet(this.assignmentOwnerKey, assignmentIds),
|
|
1635
|
-
Promise.all(assignmentIds.map((id) => this.redisClient.zScore(this.pendingAssignmentsExpiryKey, id))),
|
|
1636
|
-
]);
|
|
1637
|
-
const results = [];
|
|
1638
|
-
for (let i = 0; i < assignmentIds.length; i++) {
|
|
1639
|
-
const id = assignmentIds[i];
|
|
1640
|
-
const json = pendingEntries[id];
|
|
1641
|
-
if (!json)
|
|
1642
|
-
continue;
|
|
1643
|
-
let assignment;
|
|
1771
|
+
const hydrate = (meta) => {
|
|
1644
1772
|
try {
|
|
1645
|
-
|
|
1773
|
+
return {
|
|
1774
|
+
assignment: JSON.parse(meta.json),
|
|
1775
|
+
ownerId: meta.ownerId,
|
|
1776
|
+
pendingForMs: meta.pendingForMs,
|
|
1777
|
+
pendingSince: meta.pendingSince,
|
|
1778
|
+
expiresAt: meta.expiresAt,
|
|
1779
|
+
};
|
|
1646
1780
|
}
|
|
1647
1781
|
catch {
|
|
1648
|
-
|
|
1782
|
+
return null;
|
|
1649
1783
|
}
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1784
|
+
};
|
|
1785
|
+
const limit = options?.limit;
|
|
1786
|
+
if (typeof limit === 'number' && Number.isFinite(limit)) {
|
|
1787
|
+
// Sort the (small) metadata first, then hydrate only the top N.
|
|
1788
|
+
const clamped = Math.max(1, Math.min(Math.floor(limit), 1000));
|
|
1789
|
+
const top = [...metas].sort((a, b) => (b.pendingForMs ?? -1) - (a.pendingForMs ?? -1)).slice(0, clamped);
|
|
1790
|
+
const results = [];
|
|
1791
|
+
for (const meta of top) {
|
|
1792
|
+
const hydrated = hydrate(meta);
|
|
1793
|
+
if (hydrated)
|
|
1794
|
+
results.push(hydrated);
|
|
1795
|
+
}
|
|
1796
|
+
return results;
|
|
1797
|
+
}
|
|
1798
|
+
const results = [];
|
|
1799
|
+
for (const meta of metas) {
|
|
1800
|
+
const hydrated = hydrate(meta);
|
|
1801
|
+
if (hydrated)
|
|
1802
|
+
results.push(hydrated);
|
|
1661
1803
|
}
|
|
1662
1804
|
results.sort((a, b) => (b.pendingForMs ?? -1) - (a.pendingForMs ?? -1));
|
|
1663
1805
|
return results;
|
|
@@ -1756,12 +1898,23 @@ class AssignmentMatcher {
|
|
|
1756
1898
|
return { id, priority };
|
|
1757
1899
|
}
|
|
1758
1900
|
async setAssignmentPriorityByTags(tags, priority) {
|
|
1759
|
-
// Update priorities for
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1901
|
+
// Update priorities for QUEUED assignments that include any of the
|
|
1902
|
+
// specified tags. Pending/accepted assignments left the matching
|
|
1903
|
+
// indexes at claim time — re-zAdding them here would resurrect
|
|
1904
|
+
// permanent ghost candidates that crowd real work out of the batch.
|
|
1905
|
+
const queued = await this.redisClient.hGetAll(this.assignmentsRefKey);
|
|
1906
|
+
const relevantAssignments = [];
|
|
1907
|
+
for (const json of Object.values(queued)) {
|
|
1908
|
+
try {
|
|
1909
|
+
const assignment = JSON.parse(json);
|
|
1910
|
+
const assignmentTagSet = new Set(assignment.tags);
|
|
1911
|
+
if (tags.some((tag) => assignmentTagSet.has(tag)))
|
|
1912
|
+
relevantAssignments.push(assignment);
|
|
1913
|
+
}
|
|
1914
|
+
catch {
|
|
1915
|
+
// Skip corrupt entries (same precedent as getAllAssignmentsFromStores)
|
|
1916
|
+
}
|
|
1917
|
+
}
|
|
1765
1918
|
if (relevantAssignments.length > 0) {
|
|
1766
1919
|
const multi = this.redisClient.multi();
|
|
1767
1920
|
for (const assignment of relevantAssignments) {
|
|
@@ -1778,6 +1931,23 @@ class AssignmentMatcher {
|
|
|
1778
1931
|
}
|
|
1779
1932
|
}
|
|
1780
1933
|
await multi.exec();
|
|
1934
|
+
// The snapshot read above races the atomic claim gate (same
|
|
1935
|
+
// pattern as setAssignmentPriority): undo any ghost the writes
|
|
1936
|
+
// resurrected for assignments claimed since the read.
|
|
1937
|
+
const ids = relevantAssignments.map((a) => a.id);
|
|
1938
|
+
const owners = await this.redisClient.hmGet(this.assignmentOwnerKey, ids);
|
|
1939
|
+
const ghosts = relevantAssignments.filter((_, i) => owners[i]);
|
|
1940
|
+
if (ghosts.length > 0) {
|
|
1941
|
+
const cleanup = this.redisClient.multi();
|
|
1942
|
+
for (const assignment of ghosts) {
|
|
1943
|
+
cleanup.zRem(this.assignmentsKey, assignment.id);
|
|
1944
|
+
const idxTags = [...assignment.tags, ...(this.enableDefaultMatching ? ['default'] : [])];
|
|
1945
|
+
for (const tag of idxTags) {
|
|
1946
|
+
cleanup.zRem(this.keys.tagAssignments(tag), assignment.id);
|
|
1947
|
+
}
|
|
1948
|
+
}
|
|
1949
|
+
await cleanup.exec();
|
|
1950
|
+
}
|
|
1781
1951
|
}
|
|
1782
1952
|
return relevantAssignments.map((assignment) => ({ id: assignment.id, priority }));
|
|
1783
1953
|
}
|
|
@@ -1807,17 +1977,25 @@ class AssignmentMatcher {
|
|
|
1807
1977
|
const own = user.maxBacklogSize;
|
|
1808
1978
|
return typeof own === 'number' && Number.isFinite(own) && own >= 0 ? own : this.maxUserBacklogSize;
|
|
1809
1979
|
}
|
|
1810
|
-
async computeCandidatesForUser(user, capToBacklog = true, collector) {
|
|
1980
|
+
async computeCandidatesForUser(user, capToBacklog = true, collector, grantBudget) {
|
|
1811
1981
|
const userAssignments = [];
|
|
1812
1982
|
const routingWeights = user.routingWeights;
|
|
1813
1983
|
const hasRoutingWeights = Boolean(routingWeights && Object.keys(routingWeights).length > 0);
|
|
1984
|
+
// The cap bounds TOTAL backlog, not new grants per pass: callers that
|
|
1985
|
+
// know the user's current backlog pass the remaining headroom as
|
|
1986
|
+
// `grantBudget` (without it, a user holding work could be topped up to
|
|
1987
|
+
// 2×limit−1). capToBacklog=false (the fair path) keeps the full
|
|
1988
|
+
// candidate set for global arbitration.
|
|
1989
|
+
const effectiveCap = capToBacklog
|
|
1990
|
+
? Math.max(0, grantBudget ?? this.backlogLimitFor(user))
|
|
1991
|
+
: this.backlogLimitFor(user);
|
|
1814
1992
|
// Priority 1: Check for workflow-targeted assignments (deterministic matching)
|
|
1815
1993
|
if (this.enableWorkflows) {
|
|
1816
1994
|
const workflowAssignments = await this.getWorkflowTargetedAssignments(user.id);
|
|
1817
1995
|
if (workflowAssignments.length > 0) {
|
|
1818
1996
|
// Workflow assignments take precedence - add them first with highest priority
|
|
1819
1997
|
userAssignments.push(...workflowAssignments);
|
|
1820
|
-
if (userAssignments.length >=
|
|
1998
|
+
if (userAssignments.length >= effectiveCap) {
|
|
1821
1999
|
return { userAssignments, selected: [], workflowTargetedCount: userAssignments.length };
|
|
1822
2000
|
}
|
|
1823
2001
|
}
|
|
@@ -2012,7 +2190,7 @@ class AssignmentMatcher {
|
|
|
2012
2190
|
}
|
|
2013
2191
|
eligible.sort((a, b) => b.effectivePriority - a.effectivePriority);
|
|
2014
2192
|
for (const c of eligible) {
|
|
2015
|
-
if (capToBacklog && userAssignments.length >=
|
|
2193
|
+
if (capToBacklog && userAssignments.length >= effectiveCap)
|
|
2016
2194
|
break;
|
|
2017
2195
|
userAssignments.push({ id: c.detail.id, priority: c.effectivePriority });
|
|
2018
2196
|
selected.push({ id: c.detail.id, tags: c.detail.tags });
|
|
@@ -2021,7 +2199,7 @@ class AssignmentMatcher {
|
|
|
2021
2199
|
}
|
|
2022
2200
|
else {
|
|
2023
2201
|
for (const d of details) {
|
|
2024
|
-
if (capToBacklog && userAssignments.length >=
|
|
2202
|
+
if (capToBacklog && userAssignments.length >= effectiveCap)
|
|
2025
2203
|
break;
|
|
2026
2204
|
// Check CIDR restrictions: if assignment has allowedCidrs, user must have matching IP
|
|
2027
2205
|
if (!(0, cidr_1.checkCidrMatch)(user.ip, d.allowedCidrs)) {
|
|
@@ -2127,6 +2305,10 @@ class AssignmentMatcher {
|
|
|
2127
2305
|
for (const tag of tags) {
|
|
2128
2306
|
rm.zRem(this.keys.tagAssignments(tag), s.id);
|
|
2129
2307
|
}
|
|
2308
|
+
// Leaving the queued universe takes the geo index entry along
|
|
2309
|
+
// (a requeue re-adds it via enqueue's geoAdd); without this the
|
|
2310
|
+
// index grows monotonically with completed work.
|
|
2311
|
+
rm.zRem(this.keys.assignmentsGeo(), s.id);
|
|
2130
2312
|
// Add to pending structures. An assignment carrying an
|
|
2131
2313
|
// EscalationPolicy sets its own response deadline; everything
|
|
2132
2314
|
// else uses the matcher-wide one and never pays for a parse.
|
|
@@ -2175,11 +2357,26 @@ class AssignmentMatcher {
|
|
|
2175
2357
|
}
|
|
2176
2358
|
return claimedIds;
|
|
2177
2359
|
}
|
|
2178
|
-
async getUserRelatedAssignments(user, collector) {
|
|
2179
|
-
const { userAssignments, selected, workflowTargetedCount } = await this.computeCandidatesForUser(user, true, collector);
|
|
2180
|
-
const claimedIds = await this.claimSelected(user, selected);
|
|
2360
|
+
async getUserRelatedAssignments(user, collector, grantBudget) {
|
|
2361
|
+
const { userAssignments, selected, workflowTargetedCount } = await this.computeCandidatesForUser(user, true, collector, grantBudget);
|
|
2181
2362
|
const workflowTargeted = userAssignments.slice(0, workflowTargetedCount);
|
|
2182
|
-
|
|
2363
|
+
// Targeted grants go through the SAME queued→pending claim gate as
|
|
2364
|
+
// organic matching — a grant that only lands in the backlog set while
|
|
2365
|
+
// the assignment stays queued would "accept" into nothing and be
|
|
2366
|
+
// re-granted forever. A targeted id the tag path also selected is
|
|
2367
|
+
// claimed once, under its targeted entry.
|
|
2368
|
+
const targetedIds = new Set(workflowTargeted.map((t) => t.id));
|
|
2369
|
+
const claimList = [
|
|
2370
|
+
...workflowTargeted.map((t) => ({ id: t.id, tags: t.tags ?? '' })),
|
|
2371
|
+
...selected.filter((s) => !targetedIds.has(s.id)),
|
|
2372
|
+
];
|
|
2373
|
+
const claimedIds = await this.claimSelected(user, claimList);
|
|
2374
|
+
const tagScored = userAssignments
|
|
2375
|
+
.slice(workflowTargetedCount)
|
|
2376
|
+
.filter((ua) => claimedIds.has(ua.id) && !targetedIds.has(ua.id));
|
|
2377
|
+
// A targeted assignment that lost the claim was already moved to
|
|
2378
|
+
// pending for this same user on an earlier pass — its backlog
|
|
2379
|
+
// membership below is an idempotent re-add, so it is never stripped.
|
|
2183
2380
|
return { assignments: [...workflowTargeted, ...tagScored], claimedIds, workflowTargeted };
|
|
2184
2381
|
}
|
|
2185
2382
|
/**
|
|
@@ -2279,7 +2476,8 @@ class AssignmentMatcher {
|
|
|
2279
2476
|
}));
|
|
2280
2477
|
// Workflow-targeted assignments are deterministically targeted at one
|
|
2281
2478
|
// user each - not contested across users - so claim them immediately,
|
|
2282
|
-
// exactly like the non-fair path does
|
|
2479
|
+
// exactly like the non-fair path does: through the claimSelected gate
|
|
2480
|
+
// (queued→pending with an owner), then the backlog membership.
|
|
2283
2481
|
await Promise.all(perUser.map(async ({ user, candidates }) => {
|
|
2284
2482
|
const workflowOnly = candidates.userAssignments.slice(0, candidates.workflowTargetedCount);
|
|
2285
2483
|
if (workflowOnly.length === 0)
|
|
@@ -2288,6 +2486,7 @@ class AssignmentMatcher {
|
|
|
2288
2486
|
// Membership must be read before the sAdd below
|
|
2289
2487
|
workflowGrants.push(...(await this.filterNewWorkflowGrants(user, workflowOnly)));
|
|
2290
2488
|
}
|
|
2489
|
+
await this.claimSelected(user, workflowOnly.map((a) => ({ id: a.id, tags: a.tags ?? '' })));
|
|
2291
2490
|
await this.redisClient.sAdd(this.keys.userAssignments(user.id), workflowOnly.map((a) => `assignment:${a.id}`));
|
|
2292
2491
|
}));
|
|
2293
2492
|
// Flatten every user's tag-scored candidates into one global list of
|
|
@@ -2406,7 +2605,7 @@ class AssignmentMatcher {
|
|
|
2406
2605
|
if (userMatchesCount >= this.backlogLimitFor(user))
|
|
2407
2606
|
return;
|
|
2408
2607
|
const collector = this.tracingActive ? new decision_trace_1.TraceCollector() : undefined;
|
|
2409
|
-
const { assignments, claimedIds, workflowTargeted } = await this.getUserRelatedAssignments(user, collector);
|
|
2608
|
+
const { assignments, claimedIds, workflowTargeted } = await this.getUserRelatedAssignments(user, collector, this.backlogLimitFor(user) - userMatchesCount);
|
|
2410
2609
|
// Membership must be read before the sAdd below
|
|
2411
2610
|
const newWorkflowGrants = collector ? await this.filterNewWorkflowGrants(user, workflowTargeted) : [];
|
|
2412
2611
|
const relevantAssignmentKeys = assignments
|
|
@@ -2447,7 +2646,7 @@ class AssignmentMatcher {
|
|
|
2447
2646
|
if (userMatchesCount >= this.backlogLimitFor(user)) {
|
|
2448
2647
|
return;
|
|
2449
2648
|
}
|
|
2450
|
-
const { assignments, claimedIds, workflowTargeted } = await this.getUserRelatedAssignments(user, collector);
|
|
2649
|
+
const { assignments, claimedIds, workflowTargeted } = await this.getUserRelatedAssignments(user, collector, this.backlogLimitFor(user) - userMatchesCount);
|
|
2451
2650
|
if (collector) {
|
|
2452
2651
|
for (const id of claimedIds)
|
|
2453
2652
|
winners.set(id, user.id);
|
|
@@ -2667,6 +2866,10 @@ class AssignmentMatcher {
|
|
|
2667
2866
|
}
|
|
2668
2867
|
}
|
|
2669
2868
|
multi.hSet(this.acceptedAssignmentsKey, assignmentId, acceptedJson);
|
|
2869
|
+
// Per-user accepted-work index (raw id, score = accept time).
|
|
2870
|
+
// Inside the guard: an accept whose pending JSON is missing stores
|
|
2871
|
+
// nothing, so it must index nothing.
|
|
2872
|
+
multi.zAdd(this.keys.userAcceptedAssignments(userId), { score: now, value: assignmentId });
|
|
2670
2873
|
}
|
|
2671
2874
|
await multi.exec();
|
|
2672
2875
|
// SLO accept stats piggyback the accept path (internally guarded:
|
|
@@ -2796,6 +2999,7 @@ class AssignmentMatcher {
|
|
|
2796
2999
|
// Move from accepted to completed
|
|
2797
3000
|
const multi = this.redisClient.multi();
|
|
2798
3001
|
multi.hDel(this.acceptedAssignmentsKey, assignmentId);
|
|
3002
|
+
multi.zRem(this.keys.userAcceptedAssignments(userId), assignmentId);
|
|
2799
3003
|
// Clear SLA indexes (no-ops for non-SLA assignments)
|
|
2800
3004
|
multi.zRem(this.acceptedAssignmentsExpiryKey, assignmentId);
|
|
2801
3005
|
multi.zRem(this.assignmentsSlaExpiryKey, assignmentId);
|
|
@@ -2851,6 +3055,7 @@ class AssignmentMatcher {
|
|
|
2851
3055
|
// Move from accepted to completed (with failed status)
|
|
2852
3056
|
const multi = this.redisClient.multi();
|
|
2853
3057
|
multi.hDel(this.acceptedAssignmentsKey, assignmentId);
|
|
3058
|
+
multi.zRem(this.keys.userAcceptedAssignments(userId), assignmentId);
|
|
2854
3059
|
// Clear SLA indexes (no-ops for non-SLA assignments)
|
|
2855
3060
|
multi.zRem(this.acceptedAssignmentsExpiryKey, assignmentId);
|
|
2856
3061
|
multi.zRem(this.assignmentsSlaExpiryKey, assignmentId);
|
|
@@ -3251,8 +3456,10 @@ class AssignmentMatcher {
|
|
|
3251
3456
|
}
|
|
3252
3457
|
if (action === 'requeue') {
|
|
3253
3458
|
const multi = this.redisClient.multi().hDel(this.acceptedAssignmentsKey, id);
|
|
3254
|
-
if (workerId)
|
|
3459
|
+
if (workerId) {
|
|
3255
3460
|
multi.sAdd(this.keys.userRejected(workerId), id);
|
|
3461
|
+
multi.zRem(this.keys.userAcceptedAssignments(workerId), id);
|
|
3462
|
+
}
|
|
3256
3463
|
await multi.exec();
|
|
3257
3464
|
// The JSON still carries _enqueuedAt, so the freshness TTL
|
|
3258
3465
|
// keeps ticking across the requeue. A requeue after a
|
|
@@ -3262,7 +3469,7 @@ class AssignmentMatcher {
|
|
|
3262
3469
|
continue;
|
|
3263
3470
|
}
|
|
3264
3471
|
if (action === 'fail') {
|
|
3265
|
-
|
|
3472
|
+
const multi = this.redisClient
|
|
3266
3473
|
.multi()
|
|
3267
3474
|
.hDel(this.acceptedAssignmentsKey, id)
|
|
3268
3475
|
.hSet(this.completedAssignmentsKey, id, JSON.stringify({
|
|
@@ -3272,17 +3479,21 @@ class AssignmentMatcher {
|
|
|
3272
3479
|
_failureReason: 'completion-sla-breach',
|
|
3273
3480
|
}))
|
|
3274
3481
|
// Terminal: the freshness TTL no longer applies.
|
|
3275
|
-
.zRem(this.assignmentsSlaExpiryKey, id)
|
|
3276
|
-
|
|
3482
|
+
.zRem(this.assignmentsSlaExpiryKey, id);
|
|
3483
|
+
if (workerId)
|
|
3484
|
+
multi.zRem(this.keys.userAcceptedAssignments(workerId), id);
|
|
3485
|
+
await multi.exec();
|
|
3277
3486
|
continue;
|
|
3278
3487
|
}
|
|
3279
3488
|
// 'park'
|
|
3280
|
-
|
|
3489
|
+
const parkMulti = this.redisClient
|
|
3281
3490
|
.multi()
|
|
3282
3491
|
.hDel(this.acceptedAssignmentsKey, id)
|
|
3283
3492
|
.hSet(this.keys.parkedAssignments(), id, JSON.stringify(assignment))
|
|
3284
|
-
.zRem(this.assignmentsSlaExpiryKey, id)
|
|
3285
|
-
|
|
3493
|
+
.zRem(this.assignmentsSlaExpiryKey, id);
|
|
3494
|
+
if (workerId)
|
|
3495
|
+
parkMulti.zRem(this.keys.userAcceptedAssignments(workerId), id);
|
|
3496
|
+
await parkMulti.exec();
|
|
3286
3497
|
}
|
|
3287
3498
|
return { breached };
|
|
3288
3499
|
}
|
|
@@ -3339,12 +3550,14 @@ class AssignmentMatcher {
|
|
|
3339
3550
|
await multi.exec();
|
|
3340
3551
|
}
|
|
3341
3552
|
else if (acceptedJson) {
|
|
3342
|
-
|
|
3553
|
+
const multi = this.redisClient
|
|
3343
3554
|
.multi()
|
|
3344
3555
|
.hDel(this.acceptedAssignmentsKey, id)
|
|
3345
3556
|
.zRem(this.acceptedAssignmentsExpiryKey, id)
|
|
3346
|
-
.zRem(this.assignmentsSlaExpiryKey, id)
|
|
3347
|
-
|
|
3557
|
+
.zRem(this.assignmentsSlaExpiryKey, id);
|
|
3558
|
+
if (ownerId)
|
|
3559
|
+
multi.zRem(this.keys.userAcceptedAssignments(ownerId), id);
|
|
3560
|
+
await multi.exec();
|
|
3348
3561
|
}
|
|
3349
3562
|
else {
|
|
3350
3563
|
// Queued: full index cleanup via removeAssignment (also zRems
|
|
@@ -3463,7 +3676,16 @@ class AssignmentMatcher {
|
|
|
3463
3676
|
// A due notBefore falls straight through addAssignment's hold
|
|
3464
3677
|
// guard into the normal enqueue, which also clears the scheduled
|
|
3465
3678
|
// hash atomically with the queued write.
|
|
3466
|
-
|
|
3679
|
+
try {
|
|
3680
|
+
await this.addAssignment(JSON.parse(json));
|
|
3681
|
+
}
|
|
3682
|
+
catch (err) {
|
|
3683
|
+
// The zRem claim already consumed the only trigger; without
|
|
3684
|
+
// restoring it, a failed enqueue strands the assignment in the
|
|
3685
|
+
// scheduled store forever (nothing re-examines it).
|
|
3686
|
+
await this.redisClient.zAdd(this.scheduledActivateAtKey, { score: now, value: id });
|
|
3687
|
+
throw err;
|
|
3688
|
+
}
|
|
3467
3689
|
activated++;
|
|
3468
3690
|
this.emitAssignmentLifecycle({ kind: 'scheduleActivated', taskId: id, at: now });
|
|
3469
3691
|
}
|
|
@@ -3487,6 +3709,181 @@ class AssignmentMatcher {
|
|
|
3487
3709
|
const all = await this.redisClient.hGetAll(this.scheduledAssignmentsKey);
|
|
3488
3710
|
return Object.values(all).map((json) => JSON.parse(json));
|
|
3489
3711
|
}
|
|
3712
|
+
// ============================================================================
|
|
3713
|
+
// Recurring assignments — standing templates the sweep cuts occurrences from
|
|
3714
|
+
// ============================================================================
|
|
3715
|
+
/**
|
|
3716
|
+
* Register (or update) a recurring assignment: a standing template whose
|
|
3717
|
+
* recurrence sweep materializes each occurrence as an ordinary scheduled
|
|
3718
|
+
* assignment (id `<templateId>@<openEpochMs>`, offer window derived from
|
|
3719
|
+
* the policy). The template itself is never matchable.
|
|
3720
|
+
*
|
|
3721
|
+
* Re-adding an existing id replaces the template but keeps its clock —
|
|
3722
|
+
* occurrences already materialized and the next slot are facts about the
|
|
3723
|
+
* past, not properties of the template. Remove and re-add to restart.
|
|
3724
|
+
*
|
|
3725
|
+
* Occurrences fire with sweep granularity: `startMaintenance()` /
|
|
3726
|
+
* `runMaintenanceOnce()` / `processRecurringAssignments()`.
|
|
3727
|
+
*
|
|
3728
|
+
* @throws when `recurrence` is unusable (`everyMs` missing or < 1000,
|
|
3729
|
+
* or `until` before `startAt`)
|
|
3730
|
+
*/
|
|
3731
|
+
async addRecurringAssignment(template) {
|
|
3732
|
+
await this.readyPromise;
|
|
3733
|
+
const policy = (0, recurrence_1.normalizeRecurrencePolicy)(template.recurrence);
|
|
3734
|
+
if (!policy) {
|
|
3735
|
+
throw new Error(`addRecurringAssignment: recurrence needs everyMs >= ${recurrence_1.MIN_EVERY_MS} and a satisfiable until/startAt`);
|
|
3736
|
+
}
|
|
3737
|
+
const existingJson = await this.redisClient.hGet(this.recurringAssignmentsKey, template.id);
|
|
3738
|
+
const existing = existingJson ? JSON.parse(existingJson) : null;
|
|
3739
|
+
const record = {
|
|
3740
|
+
template,
|
|
3741
|
+
nextAt: existing?.nextAt ?? policy.startAt ?? Date.now(),
|
|
3742
|
+
occurrences: existing?.occurrences ?? 0,
|
|
3743
|
+
};
|
|
3744
|
+
await this.redisClient
|
|
3745
|
+
.multi()
|
|
3746
|
+
.hSet(this.recurringAssignmentsKey, template.id, JSON.stringify(record))
|
|
3747
|
+
.zAdd(this.recurringDueAtKey, { score: (0, recurrence_1.sweepDueAt)(record, policy), value: template.id })
|
|
3748
|
+
.exec();
|
|
3749
|
+
return template;
|
|
3750
|
+
}
|
|
3751
|
+
/**
|
|
3752
|
+
* Remove a recurring template: no further occurrences materialize.
|
|
3753
|
+
* Occurrences already cut from it are ordinary assignments and live on —
|
|
3754
|
+
* `dropScheduled: true` additionally removes the ones still sitting
|
|
3755
|
+
* un-activated in the scheduled store (never queued/pending/accepted
|
|
3756
|
+
* work).
|
|
3757
|
+
*
|
|
3758
|
+
* @returns false when the id was not a recurring template
|
|
3759
|
+
*/
|
|
3760
|
+
async removeRecurringAssignment(id, opts) {
|
|
3761
|
+
await this.readyPromise;
|
|
3762
|
+
const [removed] = (await this.redisClient
|
|
3763
|
+
.multi()
|
|
3764
|
+
.hDel(this.recurringAssignmentsKey, id)
|
|
3765
|
+
.zRem(this.recurringDueAtKey, id)
|
|
3766
|
+
.exec());
|
|
3767
|
+
if (opts?.dropScheduled) {
|
|
3768
|
+
const prefix = `${id}@`;
|
|
3769
|
+
const scheduledIds = await this.redisClient.hKeys(this.scheduledAssignmentsKey);
|
|
3770
|
+
for (const occId of scheduledIds) {
|
|
3771
|
+
if (!occId.startsWith(prefix))
|
|
3772
|
+
continue;
|
|
3773
|
+
await this.redisClient
|
|
3774
|
+
.multi()
|
|
3775
|
+
.hDel(this.scheduledAssignmentsKey, occId)
|
|
3776
|
+
.zRem(this.scheduledActivateAtKey, occId)
|
|
3777
|
+
.zRem(this.scheduleNotAfterKey, occId)
|
|
3778
|
+
.exec();
|
|
3779
|
+
}
|
|
3780
|
+
}
|
|
3781
|
+
return Number(removed) === 1;
|
|
3782
|
+
}
|
|
3783
|
+
/** One recurring template with its clock, or null. */
|
|
3784
|
+
async getRecurringAssignment(id) {
|
|
3785
|
+
await this.readyPromise;
|
|
3786
|
+
const json = await this.redisClient.hGet(this.recurringAssignmentsKey, id);
|
|
3787
|
+
return json ? JSON.parse(json) : null;
|
|
3788
|
+
}
|
|
3789
|
+
/** Every recurring template with its clock, soonest next occurrence first. */
|
|
3790
|
+
async listRecurringAssignments() {
|
|
3791
|
+
await this.readyPromise;
|
|
3792
|
+
const all = await this.redisClient.hGetAll(this.recurringAssignmentsKey);
|
|
3793
|
+
return Object.values(all)
|
|
3794
|
+
.map((json) => JSON.parse(json))
|
|
3795
|
+
.sort((a, b) => a.nextAt - b.nextAt);
|
|
3796
|
+
}
|
|
3797
|
+
/**
|
|
3798
|
+
* Sweep the recurring templates: materialize every due slot (one interval
|
|
3799
|
+
* ahead of its open time, so the next occurrence is visible in the
|
|
3800
|
+
* scheduled store before its window opens) and retire templates whose
|
|
3801
|
+
* bound (`until` / `maxOccurrences`) is reached.
|
|
3802
|
+
*
|
|
3803
|
+
* Claims are one-shot zRems like the scheduled sweep, so concurrent
|
|
3804
|
+
* replicas skip templates another sweep already took. A crashed pass is
|
|
3805
|
+
* healed two ways: the due index is re-derived from the template hash at
|
|
3806
|
+
* the top of every sweep (missing entries re-indexed as due now, NX so a
|
|
3807
|
+
* live score is never clobbered), and occurrence ids are deterministic,
|
|
3808
|
+
* so re-materializing a slot that already landed is an idempotent re-add.
|
|
3809
|
+
*/
|
|
3810
|
+
async processRecurringAssignments() {
|
|
3811
|
+
await this.readyPromise;
|
|
3812
|
+
const now = Date.now();
|
|
3813
|
+
let materialized = 0;
|
|
3814
|
+
let retired = 0;
|
|
3815
|
+
// Self-heal: a template whose sweep crashed between the claim and the
|
|
3816
|
+
// state write has no due-index entry and nothing else re-examines it.
|
|
3817
|
+
const [templateIds, indexedIds] = await Promise.all([
|
|
3818
|
+
this.redisClient.hKeys(this.recurringAssignmentsKey),
|
|
3819
|
+
this.redisClient.zRange(this.recurringDueAtKey, 0, -1),
|
|
3820
|
+
]);
|
|
3821
|
+
const indexed = new Set(indexedIds);
|
|
3822
|
+
const orphaned = templateIds.filter((id) => !indexed.has(id));
|
|
3823
|
+
if (orphaned.length > 0) {
|
|
3824
|
+
await this.redisClient.zAdd(this.recurringDueAtKey, orphaned.map((id) => ({ score: now, value: id })), { NX: true });
|
|
3825
|
+
}
|
|
3826
|
+
const dueIds = await this.redisClient.zRangeByScore(this.recurringDueAtKey, '-inf', now);
|
|
3827
|
+
for (const id of dueIds) {
|
|
3828
|
+
const claimed = await this.redisClient.zRem(this.recurringDueAtKey, id);
|
|
3829
|
+
if (!claimed)
|
|
3830
|
+
continue;
|
|
3831
|
+
const json = await this.redisClient.hGet(this.recurringAssignmentsKey, id);
|
|
3832
|
+
// Removed since the range read: the claim was the whole cleanup.
|
|
3833
|
+
if (!json)
|
|
3834
|
+
continue;
|
|
3835
|
+
const record = JSON.parse(json);
|
|
3836
|
+
const policy = (0, recurrence_1.normalizeRecurrencePolicy)(record.template.recurrence);
|
|
3837
|
+
if (!policy) {
|
|
3838
|
+
// A stored record that no longer normalizes (hand-edited, or a
|
|
3839
|
+
// future field contract change): leave the hash entry readable
|
|
3840
|
+
// but inert rather than deleting data or looping on it.
|
|
3841
|
+
continue;
|
|
3842
|
+
}
|
|
3843
|
+
const { slots, next, retiredReason } = (0, recurrence_1.dueSlots)(policy, record, now);
|
|
3844
|
+
try {
|
|
3845
|
+
for (const [index, openAt] of slots.entries()) {
|
|
3846
|
+
await this.addAssignment((0, recurrence_1.materializeOccurrence)(record.template, policy, openAt));
|
|
3847
|
+
materialized++;
|
|
3848
|
+
this.emitAssignmentLifecycle({
|
|
3849
|
+
kind: 'recurrenceMaterialized',
|
|
3850
|
+
taskId: (0, recurrence_1.occurrenceId)(record.template.id, openAt),
|
|
3851
|
+
recurringId: id,
|
|
3852
|
+
occurrence: record.occurrences + index + 1,
|
|
3853
|
+
opensAt: openAt,
|
|
3854
|
+
at: now,
|
|
3855
|
+
});
|
|
3856
|
+
}
|
|
3857
|
+
}
|
|
3858
|
+
catch (err) {
|
|
3859
|
+
// The claim already consumed the only trigger and the state is
|
|
3860
|
+
// deliberately not advanced yet; restore the claim so the next
|
|
3861
|
+
// sweep retries. Slots that did land re-add idempotently.
|
|
3862
|
+
await this.redisClient.zAdd(this.recurringDueAtKey, { score: now, value: id });
|
|
3863
|
+
throw err;
|
|
3864
|
+
}
|
|
3865
|
+
if (retiredReason) {
|
|
3866
|
+
await this.redisClient.hDel(this.recurringAssignmentsKey, id);
|
|
3867
|
+
retired++;
|
|
3868
|
+
this.emitAssignmentLifecycle({
|
|
3869
|
+
kind: 'recurrenceRetired',
|
|
3870
|
+
recurringId: id,
|
|
3871
|
+
reason: retiredReason,
|
|
3872
|
+
occurrences: next.occurrences,
|
|
3873
|
+
at: now,
|
|
3874
|
+
});
|
|
3875
|
+
}
|
|
3876
|
+
else {
|
|
3877
|
+
const updated = { ...record, ...next };
|
|
3878
|
+
await this.redisClient
|
|
3879
|
+
.multi()
|
|
3880
|
+
.hSet(this.recurringAssignmentsKey, id, JSON.stringify(updated))
|
|
3881
|
+
.zAdd(this.recurringDueAtKey, { score: (0, recurrence_1.sweepDueAt)(updated, policy), value: id })
|
|
3882
|
+
.exec();
|
|
3883
|
+
}
|
|
3884
|
+
}
|
|
3885
|
+
return { materialized, retired };
|
|
3886
|
+
}
|
|
3490
3887
|
/**
|
|
3491
3888
|
* Return a parked assignment to the queue, optionally resetting its
|
|
3492
3889
|
* escalation level so the ladder can run again from the top.
|
|
@@ -3519,8 +3916,12 @@ class AssignmentMatcher {
|
|
|
3519
3916
|
delete record[policy_2.SLA_ACCEPTED_AT_FIELD];
|
|
3520
3917
|
delete record[policy_2.SLA_ACCEPTED_BY_FIELD];
|
|
3521
3918
|
}
|
|
3522
|
-
|
|
3919
|
+
// Re-enqueue BEFORE dropping the parked copy: the parked hash holds
|
|
3920
|
+
// the only copy of the JSON, so the reverse order loses the assignment
|
|
3921
|
+
// outright if the enqueue fails mid-flight. A crash between these two
|
|
3922
|
+
// leaves a duplicate (queued + parked), which a repeat unpark heals.
|
|
3523
3923
|
await this.addAssignment(assignment);
|
|
3924
|
+
await this.redisClient.hDel(this.keys.parkedAssignments(), id);
|
|
3524
3925
|
return true;
|
|
3525
3926
|
}
|
|
3526
3927
|
/** Current escalation level of an assignment (0 = never escalated). */
|
|
@@ -3551,6 +3952,15 @@ class AssignmentMatcher {
|
|
|
3551
3952
|
let slaExpiries = 0;
|
|
3552
3953
|
let scheduleActivations = 0;
|
|
3553
3954
|
let scheduleMisses = 0;
|
|
3955
|
+
let recurrenceMaterializations = 0;
|
|
3956
|
+
let recurrenceRetirements = 0;
|
|
3957
|
+
// Recurrence before schedule: an occurrence materialized due-now is
|
|
3958
|
+
// then activated by the schedule sweep in this same tick.
|
|
3959
|
+
if (opts.recurrence) {
|
|
3960
|
+
const result = await this.processRecurringAssignments();
|
|
3961
|
+
recurrenceMaterializations = result.materialized;
|
|
3962
|
+
recurrenceRetirements = result.retired;
|
|
3963
|
+
}
|
|
3554
3964
|
// Schedule first: a just-activated assignment's response/SLA clocks
|
|
3555
3965
|
// then start from this same tick's state.
|
|
3556
3966
|
if (opts.scheduled) {
|
|
@@ -3586,6 +3996,8 @@ class AssignmentMatcher {
|
|
|
3586
3996
|
slaExpiries,
|
|
3587
3997
|
scheduleActivations,
|
|
3588
3998
|
scheduleMisses,
|
|
3999
|
+
recurrenceMaterializations,
|
|
4000
|
+
recurrenceRetirements,
|
|
3589
4001
|
tookMs: Date.now() - startedAt,
|
|
3590
4002
|
};
|
|
3591
4003
|
}
|
|
@@ -3631,6 +4043,7 @@ class AssignmentMatcher {
|
|
|
3631
4043
|
completionDeadlines: options?.completionDeadlines ?? true,
|
|
3632
4044
|
slaExpiries: options?.slaExpiries ?? true,
|
|
3633
4045
|
scheduled: options?.scheduled ?? true,
|
|
4046
|
+
recurrence: options?.recurrence ?? true,
|
|
3634
4047
|
workflowStepTimeouts: options?.workflowStepTimeouts ?? this.enableWorkflows,
|
|
3635
4048
|
idleUsers: options?.idleUsers ?? this.idleUserTimeoutMs !== null,
|
|
3636
4049
|
};
|
|
@@ -3761,18 +4174,27 @@ class AssignmentMatcher {
|
|
|
3761
4174
|
async getWorkflowTargetedAssignments(userId) {
|
|
3762
4175
|
const targeted = [];
|
|
3763
4176
|
// Scan queued assignments for those with _targetUserId matching this user
|
|
3764
|
-
const queuedAssignments = await
|
|
4177
|
+
const [queuedAssignments, rejectedMembers] = await Promise.all([
|
|
4178
|
+
this.redisClient.hGetAll(this.assignmentsRefKey),
|
|
4179
|
+
this.redisClient.sMembers(this.keys.userRejected(userId)),
|
|
4180
|
+
]);
|
|
4181
|
+
const rejected = new Set(rejectedMembers);
|
|
3765
4182
|
for (const [assignmentId, json] of Object.entries(queuedAssignments)) {
|
|
3766
4183
|
try {
|
|
3767
4184
|
const assignment = JSON.parse(json);
|
|
3768
|
-
// Hard veto applies even to deterministic workflow targeting
|
|
4185
|
+
// Hard veto applies even to deterministic workflow targeting,
|
|
4186
|
+
// and so does the user's own prior rejection — re-granting a
|
|
4187
|
+
// rejected assignment forever violates the rejection contract.
|
|
3769
4188
|
if (assignment.vetoedUsers?.includes(userId))
|
|
3770
4189
|
continue;
|
|
4190
|
+
if (rejected.has(assignmentId))
|
|
4191
|
+
continue;
|
|
3771
4192
|
if (assignment._targetUserId === userId && assignment._workflowInstanceId) {
|
|
3772
4193
|
// This is a workflow assignment targeted at this user
|
|
3773
4194
|
targeted.push({
|
|
3774
4195
|
id: assignmentId,
|
|
3775
4196
|
priority: assignment.priority ?? 1000,
|
|
4197
|
+
tags: (assignment.tags ?? []).join(','),
|
|
3776
4198
|
});
|
|
3777
4199
|
}
|
|
3778
4200
|
}
|