assignment-user-matcher 1.6.0 → 1.7.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 +73 -0
- 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 +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/managers/WorkflowManager.d.ts +8 -0
- package/dist/managers/WorkflowManager.d.ts.map +1 -1
- package/dist/managers/WorkflowManager.js +54 -0
- package/dist/matcher.class.d.ts +64 -3
- package/dist/matcher.class.d.ts.map +1 -1
- package/dist/matcher.class.js +216 -15
- 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/types/matcher.d.ts +153 -1
- package/dist/types/matcher.d.ts.map +1 -1
- package/dist/utils/keys.d.ts +1 -0
- package/dist/utils/keys.d.ts.map +1 -1
- package/dist/utils/keys.js +3 -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 +1 -1
package/dist/matcher.class.js
CHANGED
|
@@ -9,6 +9,7 @@ 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");
|
|
12
13
|
const decision_trace_1 = require("./tracing/decision-trace");
|
|
13
14
|
const features_1 = require("./learning/features");
|
|
14
15
|
const DecisionTraceManager_1 = require("./managers/DecisionTraceManager");
|
|
@@ -37,6 +38,12 @@ class AssignmentMatcher {
|
|
|
37
38
|
constructor(redisClient, options) {
|
|
38
39
|
this.redisClient = redisClient;
|
|
39
40
|
this.luaScriptSha = null;
|
|
41
|
+
// ============================================================================
|
|
42
|
+
// Maintenance — the periodic sweeps that make deadlines actually fire
|
|
43
|
+
// ============================================================================
|
|
44
|
+
this.maintenanceInterval = null;
|
|
45
|
+
this.maintenanceOptions = null;
|
|
46
|
+
this.maintenanceRunning = false;
|
|
40
47
|
this.autoReleaseInterval = null;
|
|
41
48
|
this.idleUserInterval = null;
|
|
42
49
|
this.relevantBatchSize = options?.relevantBatchSize ?? 50;
|
|
@@ -143,13 +150,14 @@ class AssignmentMatcher {
|
|
|
143
150
|
// Best-effort hook: do not propagate.
|
|
144
151
|
}
|
|
145
152
|
}
|
|
146
|
-
/** Keys for the
|
|
153
|
+
/** Keys for the assignment stores (used by pagination queries) */
|
|
147
154
|
get assignmentStoreKeys() {
|
|
148
155
|
return {
|
|
149
156
|
queued: this.assignmentsRefKey,
|
|
150
157
|
pending: this.pendingAssignmentsKey,
|
|
151
158
|
accepted: this.acceptedAssignmentsKey,
|
|
152
159
|
completed: this.completedAssignmentsKey,
|
|
160
|
+
parked: this.keys.parkedAssignments(),
|
|
153
161
|
};
|
|
154
162
|
}
|
|
155
163
|
async initRedis() {
|
|
@@ -658,9 +666,7 @@ class AssignmentMatcher {
|
|
|
658
666
|
let userList;
|
|
659
667
|
if (opts?.userIds && opts.userIds.length > 0) {
|
|
660
668
|
const jsons = await this.redisClient.hmGet(this.usersKey, opts.userIds);
|
|
661
|
-
userList = jsons
|
|
662
|
-
.filter((json) => Boolean(json))
|
|
663
|
-
.map((json) => JSON.parse(json));
|
|
669
|
+
userList = jsons.filter((json) => Boolean(json)).map((json) => JSON.parse(json));
|
|
664
670
|
}
|
|
665
671
|
else {
|
|
666
672
|
const all = await this.redisClient.hGetAll(this.usersKey);
|
|
@@ -1666,15 +1672,21 @@ class AssignmentMatcher {
|
|
|
1666
1672
|
for (const tag of tags) {
|
|
1667
1673
|
rm.zRem(this.keys.tagAssignments(tag), s.id);
|
|
1668
1674
|
}
|
|
1669
|
-
// Add to pending structures
|
|
1675
|
+
// Add to pending structures. An assignment carrying an
|
|
1676
|
+
// EscalationPolicy sets its own response deadline; everything
|
|
1677
|
+
// else uses the matcher-wide one and never pays for a parse.
|
|
1670
1678
|
if (json) {
|
|
1671
1679
|
rm.hSet(this.pendingAssignmentsKey, s.id, json);
|
|
1672
|
-
rm.zAdd(this.pendingAssignmentsExpiryKey, {
|
|
1680
|
+
rm.zAdd(this.pendingAssignmentsExpiryKey, {
|
|
1681
|
+
score: now + (0, policy_1.responseDeadlineFromJson)(json, this.matchExpirationMs),
|
|
1682
|
+
value: s.id,
|
|
1683
|
+
});
|
|
1673
1684
|
rm.hSet(this.assignmentOwnerKey, s.id, user.id);
|
|
1674
1685
|
}
|
|
1675
1686
|
}
|
|
1676
1687
|
await rm.exec();
|
|
1677
|
-
for (
|
|
1688
|
+
for (let i = 0; i < selected.length; i++) {
|
|
1689
|
+
const s = selected[i];
|
|
1678
1690
|
if (!claimedIds.has(s.id))
|
|
1679
1691
|
continue;
|
|
1680
1692
|
this.emitAssignmentLifecycle({
|
|
@@ -1682,7 +1694,7 @@ class AssignmentMatcher {
|
|
|
1682
1694
|
taskId: s.id,
|
|
1683
1695
|
workerId: user.id,
|
|
1684
1696
|
matchedAt: now,
|
|
1685
|
-
expiresAt: now + this.matchExpirationMs,
|
|
1697
|
+
expiresAt: now + (0, policy_1.responseDeadlineFromJson)(jsons[i], this.matchExpirationMs),
|
|
1686
1698
|
});
|
|
1687
1699
|
}
|
|
1688
1700
|
}
|
|
@@ -2045,14 +2057,17 @@ class AssignmentMatcher {
|
|
|
2045
2057
|
}
|
|
2046
2058
|
else {
|
|
2047
2059
|
// Pending under another user: transfer ownership and restart the
|
|
2048
|
-
// expiry clock for the new owner
|
|
2060
|
+
// expiry clock for the new owner (honouring the assignment's own
|
|
2061
|
+
// response deadline when it declares one).
|
|
2062
|
+
const pendingJson = await this.redisClient.hGet(this.pendingAssignmentsKey, assignmentId);
|
|
2063
|
+
const deadlineMs = (0, policy_1.responseDeadlineFromJson)(pendingJson, this.matchExpirationMs);
|
|
2049
2064
|
const transfer = this.redisClient
|
|
2050
2065
|
.multi()
|
|
2051
2066
|
.sRem(this.keys.userAssignments(previousOwnerId), `assignment:${assignmentId}`)
|
|
2052
2067
|
.sAdd(this.keys.userAssignments(userId), `assignment:${assignmentId}`)
|
|
2053
2068
|
.hSet(this.assignmentOwnerKey, assignmentId, userId)
|
|
2054
2069
|
.zAdd(this.pendingAssignmentsExpiryKey, {
|
|
2055
|
-
score: Date.now() +
|
|
2070
|
+
score: Date.now() + deadlineMs,
|
|
2056
2071
|
value: assignmentId,
|
|
2057
2072
|
});
|
|
2058
2073
|
await transfer.exec();
|
|
@@ -2062,7 +2077,7 @@ class AssignmentMatcher {
|
|
|
2062
2077
|
taskId: assignmentId,
|
|
2063
2078
|
workerId: userId,
|
|
2064
2079
|
matchedAt: reassignedAt,
|
|
2065
|
-
expiresAt: reassignedAt +
|
|
2080
|
+
expiresAt: reassignedAt + deadlineMs,
|
|
2066
2081
|
});
|
|
2067
2082
|
}
|
|
2068
2083
|
await this.touchUser(userId);
|
|
@@ -2433,16 +2448,41 @@ class AssignmentMatcher {
|
|
|
2433
2448
|
await this.readyPromise;
|
|
2434
2449
|
return this.workflow.getWorkflowMetrics();
|
|
2435
2450
|
}
|
|
2436
|
-
|
|
2451
|
+
/**
|
|
2452
|
+
* Requeue pending assignments whose response deadline elapsed, applying
|
|
2453
|
+
* each assignment's `EscalationPolicy` when it has one.
|
|
2454
|
+
*
|
|
2455
|
+
* Assignments without a policy take exactly the path they always did: the
|
|
2456
|
+
* owner loses the assignment, it returns to the open pool, and they may
|
|
2457
|
+
* win it again. With a policy the non-responder can be blocked, the
|
|
2458
|
+
* priority can climb, the tier tags can advance, and an exhausted ladder
|
|
2459
|
+
* can park the assignment instead of recirculating it forever.
|
|
2460
|
+
*
|
|
2461
|
+
* The wait clock (`assignmentsQueuedAt`) always survives: the requeue goes
|
|
2462
|
+
* through `addAssignment()`, whose `NX` keeps the original first-enqueue
|
|
2463
|
+
* time, so `oldestWaitingMs` measures the work item and not the tier.
|
|
2464
|
+
*/
|
|
2465
|
+
async processResponseDeadlines() {
|
|
2437
2466
|
await this.readyPromise;
|
|
2438
2467
|
const now = Date.now();
|
|
2439
2468
|
const expiredIds = await this.redisClient.zRangeByScore(this.pendingAssignmentsExpiryKey, '-inf', now);
|
|
2469
|
+
let escalations = 0;
|
|
2470
|
+
let parked = 0;
|
|
2440
2471
|
for (const id of expiredIds) {
|
|
2441
2472
|
const owner = await this.redisClient.hGet(this.assignmentOwnerKey, id);
|
|
2442
2473
|
const json = await this.redisClient.hGet(this.pendingAssignmentsKey, id);
|
|
2474
|
+
const assignment = json ? JSON.parse(json) : null;
|
|
2475
|
+
const policy = assignment ? (0, policy_1.normalizeEscalationPolicy)(assignment.escalation) : null;
|
|
2476
|
+
const decision = assignment && policy ? (0, policy_1.escalateAssignment)(assignment, policy) : null;
|
|
2443
2477
|
const multi = this.redisClient.multi();
|
|
2444
2478
|
if (owner) {
|
|
2445
2479
|
multi.sRem(this.keys.userAssignments(owner), `assignment:${id}`);
|
|
2480
|
+
// A blocking policy treats "never answered" as a soft rejection,
|
|
2481
|
+
// reusing the same rejected set an explicit reject writes to —
|
|
2482
|
+
// so the requeue cannot land back on the non-responder, and
|
|
2483
|
+
// decision traces already explain it as `rejectedPreviously`.
|
|
2484
|
+
if (decision?.blockPreviousOwner)
|
|
2485
|
+
multi.sAdd(this.keys.userRejected(owner), id);
|
|
2446
2486
|
}
|
|
2447
2487
|
multi.hDel(this.pendingAssignmentsKey, id);
|
|
2448
2488
|
multi.zRem(this.pendingAssignmentsExpiryKey, id);
|
|
@@ -2467,12 +2507,173 @@ class AssignmentMatcher {
|
|
|
2467
2507
|
timestamp: now,
|
|
2468
2508
|
});
|
|
2469
2509
|
}
|
|
2470
|
-
if (
|
|
2471
|
-
|
|
2510
|
+
if (!assignment)
|
|
2511
|
+
continue;
|
|
2512
|
+
if (decision && decision.exhausted) {
|
|
2513
|
+
this.emitAssignmentLifecycle({
|
|
2514
|
+
kind: 'escalationExhausted',
|
|
2515
|
+
taskId: id,
|
|
2516
|
+
level: decision.level,
|
|
2517
|
+
parked: decision.onExhausted === 'park',
|
|
2518
|
+
at: now,
|
|
2519
|
+
});
|
|
2520
|
+
if (decision.onExhausted === 'park') {
|
|
2521
|
+
// Held out of matching entirely: no requeue, and the wait
|
|
2522
|
+
// clock is cleared so a parked item stops inflating
|
|
2523
|
+
// oldestWaitingMs for work that is still winnable.
|
|
2524
|
+
await this.redisClient
|
|
2525
|
+
.multi()
|
|
2526
|
+
.hSet(this.keys.parkedAssignments(), id, JSON.stringify(assignment))
|
|
2527
|
+
.zRem(this.keys.assignmentsQueuedAt(), id)
|
|
2528
|
+
.exec();
|
|
2529
|
+
parked++;
|
|
2530
|
+
continue;
|
|
2531
|
+
}
|
|
2532
|
+
await this.addAssignment(assignment);
|
|
2533
|
+
continue;
|
|
2472
2534
|
}
|
|
2535
|
+
if (decision) {
|
|
2536
|
+
await this.addAssignment(decision.assignment);
|
|
2537
|
+
escalations++;
|
|
2538
|
+
this.emitAssignmentLifecycle({
|
|
2539
|
+
kind: 'escalated',
|
|
2540
|
+
taskId: id,
|
|
2541
|
+
fromWorkerId: owner ?? null,
|
|
2542
|
+
level: decision.level,
|
|
2543
|
+
blockedPreviousOwner: decision.blockPreviousOwner && Boolean(owner),
|
|
2544
|
+
reason: 'no-response',
|
|
2545
|
+
escalatedAt: now,
|
|
2546
|
+
});
|
|
2547
|
+
continue;
|
|
2548
|
+
}
|
|
2549
|
+
await this.addAssignment(assignment);
|
|
2473
2550
|
}
|
|
2474
|
-
return expiredIds.length;
|
|
2551
|
+
return { expired: expiredIds.length, escalations, parked };
|
|
2552
|
+
}
|
|
2553
|
+
/**
|
|
2554
|
+
* Backwards-compatible alias of `processResponseDeadlines()` returning
|
|
2555
|
+
* only the number of expired assignments.
|
|
2556
|
+
*/
|
|
2557
|
+
async processExpiredMatches() {
|
|
2558
|
+
const { expired } = await this.processResponseDeadlines();
|
|
2559
|
+
return expired;
|
|
2560
|
+
}
|
|
2561
|
+
/**
|
|
2562
|
+
* Assignments held out of matching because their escalation ladder was
|
|
2563
|
+
* exhausted under `onExhausted: 'park'` — nobody answered, all the way up.
|
|
2564
|
+
*/
|
|
2565
|
+
async getParkedAssignments() {
|
|
2566
|
+
await this.readyPromise;
|
|
2567
|
+
const all = await this.redisClient.hGetAll(this.keys.parkedAssignments());
|
|
2568
|
+
return Object.values(all).map((json) => JSON.parse(json));
|
|
2569
|
+
}
|
|
2570
|
+
/**
|
|
2571
|
+
* Return a parked assignment to the queue, optionally resetting its
|
|
2572
|
+
* escalation level so the ladder can run again from the top.
|
|
2573
|
+
*
|
|
2574
|
+
* @returns false when the id was not parked
|
|
2575
|
+
*/
|
|
2576
|
+
async unparkAssignment(id, opts) {
|
|
2577
|
+
await this.readyPromise;
|
|
2578
|
+
const json = await this.redisClient.hGet(this.keys.parkedAssignments(), id);
|
|
2579
|
+
if (!json)
|
|
2580
|
+
return false;
|
|
2581
|
+
const assignment = JSON.parse(json);
|
|
2582
|
+
if (opts?.resetEscalation)
|
|
2583
|
+
delete assignment._escalationLevel;
|
|
2584
|
+
await this.redisClient.hDel(this.keys.parkedAssignments(), id);
|
|
2585
|
+
await this.addAssignment(assignment);
|
|
2586
|
+
return true;
|
|
2587
|
+
}
|
|
2588
|
+
/** Current escalation level of an assignment (0 = never escalated). */
|
|
2589
|
+
async getEscalationLevel(id) {
|
|
2590
|
+
await this.readyPromise;
|
|
2591
|
+
const assignment = await this.getAssignment(id);
|
|
2592
|
+
return assignment ? (0, policy_1.escalationLevelOf)(assignment) : 0;
|
|
2593
|
+
}
|
|
2594
|
+
/**
|
|
2595
|
+
* Run every enabled maintenance sweep once: response deadlines and
|
|
2596
|
+
* escalations, workflow step timeouts, and idle-user release.
|
|
2597
|
+
*
|
|
2598
|
+
* Deadlines are not self-firing — something has to sweep them. Hosts that
|
|
2599
|
+
* already own a tick (a multi-tenant worker, a serverless schedule) should
|
|
2600
|
+
* call this instead of holding a timer per matcher; everyone else should
|
|
2601
|
+
* call `startMaintenance()` once and forget about it.
|
|
2602
|
+
*/
|
|
2603
|
+
async runMaintenanceOnce(options) {
|
|
2604
|
+
await this.readyPromise;
|
|
2605
|
+
const startedAt = Date.now();
|
|
2606
|
+
const opts = this.resolveMaintenanceOptions(options);
|
|
2607
|
+
let expiredMatches = 0;
|
|
2608
|
+
let escalations = 0;
|
|
2609
|
+
let parked = 0;
|
|
2610
|
+
let expiredSteps = 0;
|
|
2611
|
+
let releasedIdleUsers = 0;
|
|
2612
|
+
if (opts.responseDeadlines) {
|
|
2613
|
+
const result = await this.processResponseDeadlines();
|
|
2614
|
+
expiredMatches = result.expired;
|
|
2615
|
+
escalations = result.escalations;
|
|
2616
|
+
parked = result.parked;
|
|
2617
|
+
}
|
|
2618
|
+
if (opts.workflowStepTimeouts && this.enableWorkflows) {
|
|
2619
|
+
expiredSteps = await this.processExpiredWorkflowSteps();
|
|
2620
|
+
}
|
|
2621
|
+
if (opts.idleUsers && this.idleUserTimeoutMs !== null) {
|
|
2622
|
+
releasedIdleUsers = (await this.processIdleUsers()).length;
|
|
2623
|
+
}
|
|
2624
|
+
return {
|
|
2625
|
+
expiredMatches,
|
|
2626
|
+
escalations,
|
|
2627
|
+
parked,
|
|
2628
|
+
expiredSteps,
|
|
2629
|
+
releasedIdleUsers,
|
|
2630
|
+
tookMs: Date.now() - startedAt,
|
|
2631
|
+
};
|
|
2632
|
+
}
|
|
2633
|
+
/**
|
|
2634
|
+
* Start the periodic maintenance tick. Idempotent; a second call with
|
|
2635
|
+
* different options replaces the first.
|
|
2636
|
+
*
|
|
2637
|
+
* @param options.intervalMs how often to sweep (default 5000)
|
|
2638
|
+
*/
|
|
2639
|
+
startMaintenance(options) {
|
|
2640
|
+
this.stopMaintenance();
|
|
2641
|
+
this.maintenanceOptions = this.resolveMaintenanceOptions(options);
|
|
2642
|
+
const intervalMs = options?.intervalMs ?? 5000;
|
|
2643
|
+
this.maintenanceInterval = setInterval(() => {
|
|
2644
|
+
// Skip a tick rather than pile up overlapping sweeps when a pass
|
|
2645
|
+
// takes longer than the interval.
|
|
2646
|
+
if (this.maintenanceRunning)
|
|
2647
|
+
return;
|
|
2648
|
+
this.maintenanceRunning = true;
|
|
2649
|
+
this.runMaintenanceOnce(this.maintenanceOptions ?? undefined)
|
|
2650
|
+
.catch((err) => console.error('Maintenance tick failed:', err))
|
|
2651
|
+
.finally(() => {
|
|
2652
|
+
this.maintenanceRunning = false;
|
|
2653
|
+
});
|
|
2654
|
+
}, intervalMs);
|
|
2655
|
+
this.maintenanceInterval.unref?.();
|
|
2656
|
+
}
|
|
2657
|
+
/** Stop the periodic maintenance tick. Safe to call when not started. */
|
|
2658
|
+
stopMaintenance() {
|
|
2659
|
+
if (this.maintenanceInterval) {
|
|
2660
|
+
clearInterval(this.maintenanceInterval);
|
|
2661
|
+
this.maintenanceInterval = null;
|
|
2662
|
+
}
|
|
2663
|
+
this.maintenanceOptions = null;
|
|
2664
|
+
}
|
|
2665
|
+
/** Whether the maintenance tick is currently running. */
|
|
2666
|
+
isMaintenanceRunning() {
|
|
2667
|
+
return this.maintenanceInterval !== null;
|
|
2668
|
+
}
|
|
2669
|
+
resolveMaintenanceOptions(options) {
|
|
2670
|
+
return {
|
|
2671
|
+
responseDeadlines: options?.responseDeadlines ?? true,
|
|
2672
|
+
workflowStepTimeouts: options?.workflowStepTimeouts ?? this.enableWorkflows,
|
|
2673
|
+
idleUsers: options?.idleUsers ?? this.idleUserTimeoutMs !== null,
|
|
2674
|
+
};
|
|
2475
2675
|
}
|
|
2676
|
+
/** @deprecated Use `startMaintenance()`, which also sweeps workflow step timeouts. */
|
|
2476
2677
|
startAutoReleaseInterval(intervalMs = 10000) {
|
|
2477
2678
|
if (this.autoReleaseInterval)
|
|
2478
2679
|
return;
|
|
@@ -19,12 +19,17 @@ export interface AssignmentCounts {
|
|
|
19
19
|
queued: number;
|
|
20
20
|
pending: number;
|
|
21
21
|
accepted: number;
|
|
22
|
+
/** Assignments held out of matching by an exhausted escalation ladder */
|
|
23
|
+
parked: number;
|
|
24
|
+
/** queued + pending + accepted — parked items are counted separately */
|
|
22
25
|
total: number;
|
|
23
26
|
}
|
|
24
27
|
export interface AssignmentKeys {
|
|
25
28
|
queued: string;
|
|
26
29
|
pending: string;
|
|
27
30
|
accepted: string;
|
|
31
|
+
/** Optional parked store; omitted by callers that predate escalation policies */
|
|
32
|
+
parked?: string;
|
|
28
33
|
}
|
|
29
34
|
/**
|
|
30
35
|
* Get all assignments from all stores (queued, pending, accepted)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pagination.d.ts","sourceRoot":"","sources":["../../src/queries/pagination.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,KAAK,EAAE,eAAe,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAEpE,MAAM,MAAM,gBAAgB,GAAG,QAAQ,GAAG,SAAS,GAAG,UAAU,CAAC;AAEjE,MAAM,WAAW,iBAAiB;IAC9B,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,gBAAgB,GAAG,KAAK,CAAC;IAClC,YAAY,CAAC,EAAE,OAAO,CAAC;CAC1B;AAED,MAAM,WAAW,gBAAgB;IAC7B,WAAW,EAAE,UAAU,EAAE,CAAC;IAC1B,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,OAAO,EAAE,OAAO,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,gBAAgB;IAC7B,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,cAAc;IAC3B,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;
|
|
1
|
+
{"version":3,"file":"pagination.d.ts","sourceRoot":"","sources":["../../src/queries/pagination.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,KAAK,EAAE,eAAe,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAEpE,MAAM,MAAM,gBAAgB,GAAG,QAAQ,GAAG,SAAS,GAAG,UAAU,CAAC;AAEjE,MAAM,WAAW,iBAAiB;IAC9B,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,gBAAgB,GAAG,KAAK,CAAC;IAClC,YAAY,CAAC,EAAE,OAAO,CAAC;CAC1B;AAED,MAAM,WAAW,gBAAgB;IAC7B,WAAW,EAAE,UAAU,EAAE,CAAC;IAC1B,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,OAAO,EAAE,OAAO,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,gBAAgB;IAC7B,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;IACjB,yEAAyE;IACzE,MAAM,EAAE,MAAM,CAAC;IACf,wEAAwE;IACxE,KAAK,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,cAAc;IAC3B,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;IACjB,iFAAiF;IACjF,MAAM,CAAC,EAAE,MAAM,CAAC;CACnB;AAED;;GAEG;AACH,wBAAsB,2BAA2B,CAC7C,WAAW,EAAE,eAAe,EAC5B,IAAI,EAAE,cAAc,GACrB,OAAO,CAAC,UAAU,EAAE,CAAC,CASvB;AAED;;GAEG;AACH,wBAAsB,6BAA6B,CAC/C,WAAW,EAAE,eAAe,EAC5B,IAAI,EAAE,cAAc,GACrB,OAAO,CAAC,gBAAgB,CAAC,CAe3B;AAED;;GAEG;AACH,wBAAsB,iBAAiB,CACnC,WAAW,EAAE,eAAe,EAC5B,IAAI,EAAE,cAAc,EACpB,EAAE,EAAE,MAAM,GACX,OAAO,CAAC,CAAC,UAAU,GAAG;IAAE,OAAO,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,GAAG,IAAI,CAAC,CAmCrD;AAED;;GAEG;AACH,wBAAsB,wBAAwB,CAC1C,WAAW,EAAE,eAAe,EAC5B,IAAI,EAAE,cAAc,EACpB,GAAG,EAAE,MAAM,EAAE,GACd,OAAO,CAAC,UAAU,EAAE,CAAC,CA+BvB;AAED;;GAEG;AACH,wBAAsB,iCAAiC,CACnD,WAAW,EAAE,eAAe,EAC5B,IAAI,EAAE,cAAc,EACpB,OAAO,CAAC,EAAE,iBAAiB,GAC5B,OAAO,CAAC,gBAAgB,CAAC,CA2H3B"}
|
|
@@ -18,15 +18,17 @@ exports.getAllAssignmentsFromStores = getAllAssignmentsFromStores;
|
|
|
18
18
|
* Get assignment counts by status
|
|
19
19
|
*/
|
|
20
20
|
async function getAssignmentCountsFromStores(redisClient, keys) {
|
|
21
|
-
const [queued, pending, accepted] = await Promise.all([
|
|
21
|
+
const [queued, pending, accepted, parked] = await Promise.all([
|
|
22
22
|
redisClient.hLen(keys.queued),
|
|
23
23
|
redisClient.hLen(keys.pending),
|
|
24
24
|
redisClient.hLen(keys.accepted),
|
|
25
|
+
keys.parked ? redisClient.hLen(keys.parked) : Promise.resolve(0),
|
|
25
26
|
]);
|
|
26
27
|
return {
|
|
27
28
|
queued,
|
|
28
29
|
pending,
|
|
29
30
|
accepted,
|
|
31
|
+
parked,
|
|
30
32
|
total: queued + pending + accepted,
|
|
31
33
|
};
|
|
32
34
|
}
|
|
@@ -55,6 +57,16 @@ async function getAssignmentById(redisClient, keys, id) {
|
|
|
55
57
|
assignment._status = 'accepted';
|
|
56
58
|
return assignment;
|
|
57
59
|
}
|
|
60
|
+
// Parked items are out of the matching universe but must never read as
|
|
61
|
+
// "not found" — that would make an exhausted escalation look like data loss.
|
|
62
|
+
if (keys.parked) {
|
|
63
|
+
const parked = await redisClient.hGet(keys.parked, id);
|
|
64
|
+
if (parked) {
|
|
65
|
+
const assignment = JSON.parse(parked);
|
|
66
|
+
assignment._status = 'parked';
|
|
67
|
+
return assignment;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
58
70
|
return null;
|
|
59
71
|
}
|
|
60
72
|
exports.getAssignmentById = getAssignmentById;
|
package/dist/types/matcher.d.ts
CHANGED
|
@@ -22,8 +22,74 @@ export type Assignment = {
|
|
|
22
22
|
longitude?: number;
|
|
23
23
|
maxDistanceKm?: number;
|
|
24
24
|
requireGeo?: boolean;
|
|
25
|
+
escalation?: EscalationPolicy;
|
|
25
26
|
[key: string]: any;
|
|
26
27
|
};
|
|
28
|
+
/**
|
|
29
|
+
* What should happen when the user an assignment was matched to lets the
|
|
30
|
+
* response deadline run out without accepting or rejecting it.
|
|
31
|
+
*
|
|
32
|
+
* Without a policy, an unanswered assignment is simply requeued after the
|
|
33
|
+
* matcher-wide `matchExpirationMs` — and the same user may win it straight
|
|
34
|
+
* back. A policy makes that behaviour explicit and controllable: a
|
|
35
|
+
* per-assignment deadline, an optional block on the non-responder, a priority
|
|
36
|
+
* climb, and an optional tier ladder that moves the assignment to a different
|
|
37
|
+
* pool on each hop (primary → secondary → manager) with no workflow involved.
|
|
38
|
+
*
|
|
39
|
+
* @example
|
|
40
|
+
* ```typescript
|
|
41
|
+
* await matcher.addAssignment({
|
|
42
|
+
* id: 'incident-1',
|
|
43
|
+
* tags: ['sev:1', 'oncall-primary'],
|
|
44
|
+
* escalation: {
|
|
45
|
+
* respondWithinMs: 60_000,
|
|
46
|
+
* onNoResponse: 'block',
|
|
47
|
+
* priorityBoost: 500,
|
|
48
|
+
* tiers: [['oncall-primary'], ['oncall-secondary'], ['oncall-manager']],
|
|
49
|
+
* onExhausted: 'park',
|
|
50
|
+
* },
|
|
51
|
+
* });
|
|
52
|
+
* ```
|
|
53
|
+
*/
|
|
54
|
+
export interface EscalationPolicy {
|
|
55
|
+
/**
|
|
56
|
+
* Milliseconds the matched user has to respond before the assignment is
|
|
57
|
+
* taken back. Per-assignment override of `matchExpirationMs`.
|
|
58
|
+
*/
|
|
59
|
+
respondWithinMs: number;
|
|
60
|
+
/**
|
|
61
|
+
* What happens to the user who let the clock run out.
|
|
62
|
+
* - `'block'` — treated as a soft rejection: the user is added to their
|
|
63
|
+
* rejected set so the requeue cannot land back on them.
|
|
64
|
+
* - `'allow'` — the assignment returns to the open pool and the same user
|
|
65
|
+
* may win it again (the historical behaviour).
|
|
66
|
+
* @default 'allow'
|
|
67
|
+
*/
|
|
68
|
+
onNoResponse?: 'block' | 'allow';
|
|
69
|
+
/** Priority delta applied on each escalation so ignored work climbs the queue. */
|
|
70
|
+
priorityBoost?: number;
|
|
71
|
+
/**
|
|
72
|
+
* Tag ladder. Each escalation replaces the assignment's tier tags with the
|
|
73
|
+
* next entry, so tier routing needs no workflow. Tags not named by any
|
|
74
|
+
* tier are preserved across hops. Entry 0 describes the tags the
|
|
75
|
+
* assignment starts with; the first escalation moves it to entry 1.
|
|
76
|
+
*/
|
|
77
|
+
tiers?: string[][];
|
|
78
|
+
/**
|
|
79
|
+
* Maximum number of escalations.
|
|
80
|
+
* @default `tiers.length - 1` when tiers are given, otherwise unlimited
|
|
81
|
+
*/
|
|
82
|
+
maxEscalations?: number;
|
|
83
|
+
/**
|
|
84
|
+
* Terminal behaviour once the ladder is exhausted.
|
|
85
|
+
* - `'queue'` — requeue and keep offering it (default).
|
|
86
|
+
* - `'park'` — stop matching it and move it to the parked store, where
|
|
87
|
+
* `getParkedAssignments()` / `unparkAssignment()` can pick it up. This is
|
|
88
|
+
* the honest "escalated to the top and nobody answered" state.
|
|
89
|
+
* @default 'queue'
|
|
90
|
+
*/
|
|
91
|
+
onExhausted?: 'queue' | 'park';
|
|
92
|
+
}
|
|
27
93
|
export type GeoMatchResult = {
|
|
28
94
|
eligible: boolean;
|
|
29
95
|
distanceKm?: number;
|
|
@@ -298,6 +364,65 @@ export type AssignmentLifecycleEvent = {
|
|
|
298
364
|
taskId: string;
|
|
299
365
|
workerId: string;
|
|
300
366
|
completedAt: number;
|
|
367
|
+
}
|
|
368
|
+
/**
|
|
369
|
+
* An `EscalationPolicy` moved an unanswered assignment on. Always follows
|
|
370
|
+
* the `expired` event for the same assignment — `expired` says the deadline
|
|
371
|
+
* elapsed, `escalated` says what the policy did about it.
|
|
372
|
+
*/
|
|
373
|
+
| {
|
|
374
|
+
kind: 'escalated';
|
|
375
|
+
taskId: string;
|
|
376
|
+
fromWorkerId: string | null;
|
|
377
|
+
/** Level after this hop; 1 is the first escalation */
|
|
378
|
+
level: number;
|
|
379
|
+
/** Whether the timed-out owner was blocked from winning it back */
|
|
380
|
+
blockedPreviousOwner: boolean;
|
|
381
|
+
reason: 'no-response';
|
|
382
|
+
escalatedAt: number;
|
|
383
|
+
}
|
|
384
|
+
/** The ladder ran out of hops. `parked` reflects the policy's `onExhausted`. */
|
|
385
|
+
| {
|
|
386
|
+
kind: 'escalationExhausted';
|
|
387
|
+
taskId: string;
|
|
388
|
+
level: number;
|
|
389
|
+
parked: boolean;
|
|
390
|
+
at: number;
|
|
391
|
+
};
|
|
392
|
+
/** Outcome of one `processResponseDeadlines()` sweep. */
|
|
393
|
+
export type EscalationSweepResult = {
|
|
394
|
+
/** Pending assignments whose response deadline elapsed */
|
|
395
|
+
expired: number;
|
|
396
|
+
/** How many of those an escalation policy moved to the next hop */
|
|
397
|
+
escalations: number;
|
|
398
|
+
/** How many exhausted their ladder and were parked */
|
|
399
|
+
parked: number;
|
|
400
|
+
};
|
|
401
|
+
/** One pass of `runMaintenanceOnce()`. Counts are per pass, not cumulative. */
|
|
402
|
+
export type MaintenanceReport = {
|
|
403
|
+
/** Pending assignments whose response deadline elapsed */
|
|
404
|
+
expiredMatches: number;
|
|
405
|
+
/** How many of those an escalation policy moved on */
|
|
406
|
+
escalations: number;
|
|
407
|
+
/** How many exhausted their ladder and were parked */
|
|
408
|
+
parked: number;
|
|
409
|
+
/** Workflow steps whose timeout fired */
|
|
410
|
+
expiredSteps: number;
|
|
411
|
+
/** Idle users removed from the pool (see `idleUserTimeoutMs`) */
|
|
412
|
+
releasedIdleUsers: number;
|
|
413
|
+
/** Wall-clock duration of the pass */
|
|
414
|
+
tookMs: number;
|
|
415
|
+
};
|
|
416
|
+
/** Which sweeps `startMaintenance()` runs, and how often. */
|
|
417
|
+
export type MaintenanceOptions = {
|
|
418
|
+
/** Master tick interval for every enabled sweep. @default 5000 */
|
|
419
|
+
intervalMs?: number;
|
|
420
|
+
/** Response deadlines / escalation. @default true */
|
|
421
|
+
responseDeadlines?: boolean;
|
|
422
|
+
/** Workflow step timeouts. @default true when `enableWorkflows` */
|
|
423
|
+
workflowStepTimeouts?: boolean;
|
|
424
|
+
/** Idle-user release. @default true when `idleUserTimeoutMs` is set */
|
|
425
|
+
idleUsers?: boolean;
|
|
301
426
|
};
|
|
302
427
|
export type MatcherOptions = {
|
|
303
428
|
relevantBatchSize?: number;
|
|
@@ -655,6 +780,17 @@ export interface WorkflowStep {
|
|
|
655
780
|
maxRetries?: number;
|
|
656
781
|
/** Timeout override for this step in milliseconds */
|
|
657
782
|
timeoutMs?: number;
|
|
783
|
+
/**
|
|
784
|
+
* Step to advance to when this step's timeout expires, instead of the
|
|
785
|
+
* default failure path. The step's outstanding assignment is removed (so a
|
|
786
|
+
* late responder cannot act on a superseded tier) and the run continues at
|
|
787
|
+
* `onTimeoutStepId` with `context._escalatedFrom` set.
|
|
788
|
+
*
|
|
789
|
+
* Requires `timeoutMs` (or the workflow's `defaultTimeoutMs`). Does not
|
|
790
|
+
* consume `maxRetries` — an escalation is not a retry. Not supported on
|
|
791
|
+
* steps that are members of a parallel group.
|
|
792
|
+
*/
|
|
793
|
+
onTimeoutStepId?: string;
|
|
658
794
|
}
|
|
659
795
|
/** A workflow definition (template) */
|
|
660
796
|
export interface WorkflowDefinition {
|
|
@@ -670,6 +806,13 @@ export interface WorkflowDefinition {
|
|
|
670
806
|
steps: WorkflowStep[];
|
|
671
807
|
/** Default timeout for steps in milliseconds */
|
|
672
808
|
defaultTimeoutMs?: number;
|
|
809
|
+
/**
|
|
810
|
+
* Safety net for `onTimeoutStepId` ladders: once a run has escalated this
|
|
811
|
+
* many times it falls back to the ordinary failure path instead of
|
|
812
|
+
* climbing further, so a mis-wired cycle still terminates.
|
|
813
|
+
* @default 10
|
|
814
|
+
*/
|
|
815
|
+
maxEscalationDepth?: number;
|
|
673
816
|
/** Metadata for the workflow */
|
|
674
817
|
metadata?: Record<string, any>;
|
|
675
818
|
}
|
|
@@ -687,6 +830,13 @@ export interface WorkflowDefinitionInput {
|
|
|
687
830
|
steps: WorkflowStep[];
|
|
688
831
|
/** Default timeout for steps in milliseconds */
|
|
689
832
|
defaultTimeoutMs?: number;
|
|
833
|
+
/**
|
|
834
|
+
* Safety net for `onTimeoutStepId` ladders: once a run has escalated this
|
|
835
|
+
* many times it falls back to the ordinary failure path instead of
|
|
836
|
+
* climbing further, so a mis-wired cycle still terminates.
|
|
837
|
+
* @default 10
|
|
838
|
+
*/
|
|
839
|
+
maxEscalationDepth?: number;
|
|
690
840
|
/** Metadata for the workflow */
|
|
691
841
|
metadata?: Record<string, any>;
|
|
692
842
|
}
|
|
@@ -721,7 +871,9 @@ export interface WorkflowInstancePage {
|
|
|
721
871
|
* affect workflow processing.
|
|
722
872
|
*/
|
|
723
873
|
export type WorkflowTransition = {
|
|
724
|
-
kind: 'run.started' | 'step.ready' | 'step.completed' | 'step.failed' | 'step.expired'
|
|
874
|
+
kind: 'run.started' | 'step.ready' | 'step.completed' | 'step.failed' | 'step.expired'
|
|
875
|
+
/** A timed-out step escalated forward via `onTimeoutStepId` instead of failing */
|
|
876
|
+
| 'step.escalated' | 'run.completed' | 'run.failed' | 'run.cancelled';
|
|
725
877
|
instance: WorkflowInstance;
|
|
726
878
|
stepId?: string;
|
|
727
879
|
assignmentId?: string;
|