assignment-user-matcher 1.0.11 → 1.1.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 +10 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +9 -0
- package/dist/matcher.class.d.ts +73 -0
- package/dist/matcher.class.d.ts.map +1 -0
- package/{src/matcher.class.ts → dist/matcher.class.js} +247 -200
- package/package.json +15 -2
- package/.github/workflows/npm-publish.yml +0 -82
- package/.mocharc.json +0 -11
- package/.prettierignore +0 -1
- package/.vscode/launch.json +0 -32
- package/docs/README.md +0 -406
- package/docs/classes/default.md +0 -423
- package/docs/interfaces/User.md +0 -45
- package/docs/modules.md +0 -91
- package/tests/matcher.test.ts +0 -441
- package/tsconfig.json +0 -22
|
@@ -1,96 +1,47 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
export type Assignment = {
|
|
14
|
-
id: string;
|
|
15
|
-
tags: string[];
|
|
16
|
-
priority?: number;
|
|
17
|
-
[key: string]: any;
|
|
18
|
-
};
|
|
19
|
-
|
|
20
|
-
export type Stats = {
|
|
21
|
-
users?: number;
|
|
22
|
-
usersWithoutAssignment?: string[];
|
|
23
|
-
remainingAssignments?: number;
|
|
24
|
-
};
|
|
25
|
-
|
|
26
|
-
export type options = {
|
|
27
|
-
relevantBatchSize?: number;
|
|
28
|
-
redisPrefix?: string;
|
|
29
|
-
maxUserBacklogSize?: number;
|
|
30
|
-
enableDefaultMatching?: boolean;
|
|
31
|
-
prioritizationFunction?: (...args: (Assignment | undefined)[]) => Promise<number>;
|
|
32
|
-
matchingFunction?: (
|
|
33
|
-
user: User,
|
|
34
|
-
assignmentTags: string,
|
|
35
|
-
assignmentPriority: number | string,
|
|
36
|
-
assignmentId?: string,
|
|
37
|
-
) => Promise<[number, number]>;
|
|
38
|
-
};
|
|
39
|
-
|
|
40
|
-
export default class AssignmentMatcher {
|
|
41
|
-
relevantBatchSize: number;
|
|
42
|
-
redisPrefix: string;
|
|
43
|
-
assignmentsKey: string;
|
|
44
|
-
assignmentsRefKey: string;
|
|
45
|
-
usersKey: string;
|
|
46
|
-
maxUserBacklogSize: number;
|
|
47
|
-
enableDefaultMatching: boolean;
|
|
48
|
-
|
|
49
|
-
constructor(
|
|
50
|
-
public redisClient: RedisClientType,
|
|
51
|
-
options?: options,
|
|
52
|
-
) {
|
|
53
|
-
this.relevantBatchSize = options?.relevantBatchSize ?? 50;
|
|
54
|
-
this.enableDefaultMatching = options?.enableDefaultMatching ?? true;
|
|
55
|
-
this.redisPrefix = options?.redisPrefix ?? '';
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
class AssignmentMatcher {
|
|
4
|
+
constructor(redisClient, options) {
|
|
5
|
+
var _a, _b, _c, _d, _e, _f, _g;
|
|
6
|
+
this.redisClient = redisClient;
|
|
7
|
+
this.autoReleaseInterval = null;
|
|
8
|
+
this.relevantBatchSize = (_a = options === null || options === void 0 ? void 0 : options.relevantBatchSize) !== null && _a !== void 0 ? _a : 50;
|
|
9
|
+
this.enableDefaultMatching = (_b = options === null || options === void 0 ? void 0 : options.enableDefaultMatching) !== null && _b !== void 0 ? _b : true;
|
|
10
|
+
this.redisPrefix = (_c = options === null || options === void 0 ? void 0 : options.redisPrefix) !== null && _c !== void 0 ? _c : '';
|
|
56
11
|
this.usersKey = this.redisPrefix + 'users';
|
|
57
12
|
this.assignmentsKey = this.redisPrefix + 'assignments';
|
|
58
13
|
this.assignmentsRefKey = this.redisPrefix + 'assignments:ref';
|
|
59
|
-
this.maxUserBacklogSize = options
|
|
60
|
-
this.
|
|
61
|
-
this.
|
|
14
|
+
this.maxUserBacklogSize = (_d = options === null || options === void 0 ? void 0 : options.maxUserBacklogSize) !== null && _d !== void 0 ? _d : 9;
|
|
15
|
+
this.matchExpirationMs = (_e = options === null || options === void 0 ? void 0 : options.matchExpirationMs) !== null && _e !== void 0 ? _e : 60000;
|
|
16
|
+
this.pendingAssignmentsKey = this.redisPrefix + 'assignments:pending:data';
|
|
17
|
+
this.pendingAssignmentsExpiryKey = this.redisPrefix + 'assignments:pending:expiry';
|
|
18
|
+
this.assignmentOwnerKey = this.redisPrefix + 'assignments:pending:owner';
|
|
19
|
+
this.allTagsKey = this.redisPrefix + 'all:tags';
|
|
20
|
+
this.calculatePriority = (_f = options === null || options === void 0 ? void 0 : options.prioritizationFunction) !== null && _f !== void 0 ? _f : this.calculatePriority;
|
|
21
|
+
this.matchScore = (_g = options === null || options === void 0 ? void 0 : options.matchingFunction) !== null && _g !== void 0 ? _g : this.matchScore;
|
|
62
22
|
this.initRedis();
|
|
63
23
|
}
|
|
64
|
-
|
|
65
|
-
private async initRedis() {
|
|
24
|
+
async initRedis() {
|
|
66
25
|
// Only attempt to connect if the client isn't already connected
|
|
67
26
|
if (!this.redisClient.isOpen) {
|
|
68
27
|
await this.redisClient.connect();
|
|
69
28
|
}
|
|
70
29
|
return this;
|
|
71
30
|
}
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
this.
|
|
76
|
-
|
|
77
|
-
JSON.stringify({
|
|
78
|
-
...user,
|
|
79
|
-
tags: [...user.tags, ...(this.enableDefaultMatching ? ['default'] : [])],
|
|
80
|
-
}),
|
|
81
|
-
);
|
|
82
|
-
|
|
31
|
+
async addUser(user) {
|
|
32
|
+
await this.redisClient.hSet(this.usersKey, user.id, JSON.stringify({
|
|
33
|
+
...user,
|
|
34
|
+
tags: [...user.tags, ...(this.enableDefaultMatching ? ['default'] : [])],
|
|
35
|
+
}));
|
|
83
36
|
return user;
|
|
84
37
|
}
|
|
85
|
-
|
|
86
|
-
async addAssignment(assignment: Assignment) {
|
|
38
|
+
async addAssignment(assignment) {
|
|
87
39
|
let { id, tags, priority, latitude, longitude } = assignment;
|
|
88
|
-
if (!priority)
|
|
89
|
-
|
|
40
|
+
if (!priority)
|
|
41
|
+
priority = await this.calculatePriority(assignment);
|
|
90
42
|
const assignmentPriorityKey = this.redisPrefix + `assignment:${id}:priority`;
|
|
91
43
|
const assignmentTagsKey = this.redisPrefix + `assignment:${id}:tags`;
|
|
92
44
|
const assignmentGeoKey = this.redisPrefix + `assignments:geo`;
|
|
93
|
-
|
|
94
45
|
const multi = this.redisClient
|
|
95
46
|
.multi()
|
|
96
47
|
.hSet(this.assignmentsRefKey, id, JSON.stringify(assignment))
|
|
@@ -98,10 +49,9 @@ export default class AssignmentMatcher {
|
|
|
98
49
|
// Ensure 'default' tag is persisted consistently when enabled
|
|
99
50
|
.hSet(assignmentTagsKey, 'tags', tags.join(',') + (this.enableDefaultMatching ? ',default' : ''))
|
|
100
51
|
.zAdd(this.assignmentsKey, {
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
52
|
+
score: priority,
|
|
53
|
+
value: id,
|
|
54
|
+
});
|
|
105
55
|
if (latitude && longitude) {
|
|
106
56
|
multi.geoAdd(assignmentGeoKey, {
|
|
107
57
|
longitude,
|
|
@@ -109,7 +59,6 @@ export default class AssignmentMatcher {
|
|
|
109
59
|
member: id,
|
|
110
60
|
});
|
|
111
61
|
}
|
|
112
|
-
|
|
113
62
|
// Also index assignment into per-tag sorted sets (by priority)
|
|
114
63
|
// This enables efficient weighted matching via ZUNIONSTORE.
|
|
115
64
|
const indexTags = [...tags, ...(this.enableDefaultMatching ? ['default'] : [])];
|
|
@@ -118,22 +67,20 @@ export default class AssignmentMatcher {
|
|
|
118
67
|
score: Number(priority),
|
|
119
68
|
value: id,
|
|
120
69
|
});
|
|
70
|
+
multi.zAdd(this.allTagsKey, { score: 0, value: tag });
|
|
121
71
|
}
|
|
122
|
-
|
|
123
72
|
await multi.exec();
|
|
124
|
-
|
|
125
73
|
return assignment;
|
|
126
74
|
}
|
|
127
|
-
|
|
128
|
-
async removeAssignment(id: string) {
|
|
75
|
+
async removeAssignment(id) {
|
|
129
76
|
const assignmentPriorityKey = this.redisPrefix + `assignment:${id}:priority`;
|
|
130
77
|
const assignmentTagsKey = this.redisPrefix + `assignment:${id}:tags`;
|
|
131
|
-
|
|
132
78
|
// Fetch tags to remove from per-tag indices
|
|
133
79
|
const [tagsCsv] = await this.redisClient.multi().hGet(assignmentTagsKey, 'tags').exec();
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
80
|
+
let tags = [];
|
|
81
|
+
if (typeof tagsCsv === 'string' && tagsCsv.length > 0) {
|
|
82
|
+
tags = tagsCsv.split(',');
|
|
83
|
+
}
|
|
137
84
|
const multi = this.redisClient.multi();
|
|
138
85
|
// Remove from reference and per-assignment hashes
|
|
139
86
|
multi.hDel(this.assignmentsRefKey, id);
|
|
@@ -145,71 +92,92 @@ export default class AssignmentMatcher {
|
|
|
145
92
|
for (const tag of tags) {
|
|
146
93
|
multi.zRem(this.redisPrefix + `tag:${tag}:assignments`, id.toString());
|
|
147
94
|
}
|
|
148
|
-
|
|
149
95
|
await multi.exec();
|
|
150
96
|
return id;
|
|
151
97
|
}
|
|
152
|
-
|
|
153
|
-
async removeUser(userId: string): Promise<string> {
|
|
98
|
+
async removeUser(userId) {
|
|
154
99
|
const multi = this.redisClient
|
|
155
100
|
.multi()
|
|
156
101
|
.del(this.redisPrefix + `user:${userId}:assignments`)
|
|
157
102
|
.hDel(this.usersKey, userId);
|
|
158
103
|
await multi.exec();
|
|
159
|
-
|
|
160
104
|
return userId;
|
|
161
105
|
}
|
|
162
|
-
|
|
163
|
-
async getAllAssignments(): Promise<Assignment[]> {
|
|
106
|
+
async getAllAssignments() {
|
|
164
107
|
const assignments = await this.redisClient.hGetAll(this.assignmentsRefKey);
|
|
165
108
|
return Object.values(assignments).map((assignment) => JSON.parse(assignment));
|
|
166
109
|
}
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
110
|
+
async matchScore(user, assignmentTags, assignmentPriority, assignmentId) {
|
|
111
|
+
const aTags = assignmentTags ? assignmentTags.split(',') : [];
|
|
112
|
+
const matchesPattern = (pattern, tag) => {
|
|
113
|
+
if (pattern === tag)
|
|
114
|
+
return true;
|
|
115
|
+
if (pattern.endsWith('*')) {
|
|
116
|
+
const prefix = pattern.slice(0, -1);
|
|
117
|
+
return tag.startsWith(prefix);
|
|
118
|
+
}
|
|
119
|
+
return false;
|
|
120
|
+
};
|
|
174
121
|
// If weighted skills are present, use them for scoring
|
|
175
122
|
if (user.routingWeights && Object.keys(user.routingWeights).length > 0) {
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
123
|
+
// Check for exclusions (weight 0)
|
|
124
|
+
for (const [pattern, weight] of Object.entries(user.routingWeights)) {
|
|
125
|
+
if (weight === 0) {
|
|
126
|
+
for (const t of aTags) {
|
|
127
|
+
if (matchesPattern(pattern, t)) {
|
|
128
|
+
return [0, Number(assignmentPriority) || 0];
|
|
129
|
+
}
|
|
130
|
+
}
|
|
181
131
|
}
|
|
182
132
|
}
|
|
183
133
|
let weightSum = 0;
|
|
184
134
|
for (const t of aTags) {
|
|
185
|
-
|
|
186
|
-
|
|
135
|
+
let matchedByRouting = false;
|
|
136
|
+
for (const [pattern, weight] of Object.entries(user.routingWeights)) {
|
|
137
|
+
if (typeof weight === 'number' && weight > 0) {
|
|
138
|
+
if (matchesPattern(pattern, t)) {
|
|
139
|
+
weightSum += weight;
|
|
140
|
+
matchedByRouting = true;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
// If enableDefaultMatching is true, and the tag is 'default', and it wasn't matched by any routing weight,
|
|
145
|
+
// we give it default weight 1.
|
|
146
|
+
if (this.enableDefaultMatching && t === 'default' && !matchedByRouting) {
|
|
147
|
+
weightSum += 1;
|
|
148
|
+
}
|
|
187
149
|
}
|
|
188
150
|
const base = Number(assignmentPriority) || 0;
|
|
189
|
-
// score: total positive weight overlap; priority: base weighted slightly by weight
|
|
190
151
|
return [weightSum, base + weightSum];
|
|
191
152
|
}
|
|
192
|
-
|
|
193
153
|
// Fallback to default tag-intersection scoring
|
|
194
154
|
const userTagSet = new Set(user.tags);
|
|
195
|
-
const assignmentTagSet = new Set(
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
155
|
+
const assignmentTagSet = new Set(aTags);
|
|
156
|
+
let intersectionSize = 0;
|
|
157
|
+
for (const userTag of userTagSet) {
|
|
158
|
+
let matched = false;
|
|
159
|
+
for (const assignmentTag of assignmentTagSet) {
|
|
160
|
+
if (matchesPattern(userTag, assignmentTag)) {
|
|
161
|
+
matched = true;
|
|
162
|
+
break;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
if (matched)
|
|
166
|
+
intersectionSize++;
|
|
167
|
+
}
|
|
168
|
+
const score = userTagSet.size > 0 ? intersectionSize / userTagSet.size : 0;
|
|
199
169
|
const base = Number(assignmentPriority) || 0;
|
|
200
170
|
return [score || 0, base + (score || 0)];
|
|
201
171
|
}
|
|
202
|
-
|
|
172
|
+
async calculatePriority(...args) {
|
|
203
173
|
const [assignment] = args;
|
|
204
|
-
return new Date().getTime() - assignment
|
|
174
|
+
return new Date().getTime() - (assignment === null || assignment === void 0 ? void 0 : assignment.createdAt) || 0;
|
|
205
175
|
}
|
|
206
|
-
|
|
207
|
-
get stats(): Promise<Stats> {
|
|
176
|
+
get stats() {
|
|
208
177
|
return (async () => {
|
|
209
178
|
const users = await this.redisClient.hGetAll(this.usersKey);
|
|
210
179
|
const usersWithoutAssignment = await this.usersWithoutAssignment;
|
|
211
180
|
const remainingAssignments = await this.redisClient.zCount(this.assignmentsKey, '-inf', '+inf');
|
|
212
|
-
|
|
213
181
|
return {
|
|
214
182
|
users: Object.keys(users).length,
|
|
215
183
|
usersWithoutAssignment,
|
|
@@ -217,21 +185,20 @@ export default class AssignmentMatcher {
|
|
|
217
185
|
};
|
|
218
186
|
})();
|
|
219
187
|
}
|
|
220
|
-
|
|
221
188
|
get usersWithoutAssignment() {
|
|
222
189
|
return (async () => {
|
|
223
190
|
const users = await this.redisClient.hGetAll(this.usersKey);
|
|
224
|
-
const usersWithoutAssignment
|
|
191
|
+
const usersWithoutAssignment = [];
|
|
225
192
|
for (const user of Object.values(users)) {
|
|
226
193
|
const { id } = JSON.parse(user);
|
|
227
194
|
const userAssignments = await this.getCurrentAssignmentsForUser(id);
|
|
228
|
-
if (userAssignments.length === 0)
|
|
195
|
+
if (userAssignments.length === 0)
|
|
196
|
+
usersWithoutAssignment.push(id);
|
|
229
197
|
}
|
|
230
198
|
return usersWithoutAssignment;
|
|
231
199
|
})();
|
|
232
200
|
}
|
|
233
|
-
|
|
234
|
-
async setAssignmentPriority(id: string, priority: number) {
|
|
201
|
+
async setAssignmentPriority(id, priority) {
|
|
235
202
|
const assignmentPriorityKey = this.redisPrefix + `assignment:${id}:priority`;
|
|
236
203
|
// Fetch tags to update per-tag indices
|
|
237
204
|
const assignmentTagsKey = this.redisPrefix + `assignment:${id}:tags`;
|
|
@@ -240,8 +207,7 @@ export default class AssignmentMatcher {
|
|
|
240
207
|
.hExists(this.assignmentsRefKey, id)
|
|
241
208
|
.hGet(assignmentTagsKey, 'tags')
|
|
242
209
|
.exec();
|
|
243
|
-
const tags = (typeof tagsCsv === 'string' && tagsCsv.length > 0 ? tagsCsv.split(',') : [])
|
|
244
|
-
|
|
210
|
+
const tags = (typeof tagsCsv === 'string' && tagsCsv.length > 0 ? tagsCsv.split(',') : []);
|
|
245
211
|
const multi = this.redisClient.multi();
|
|
246
212
|
multi.hSet(assignmentPriorityKey, 'priority', priority);
|
|
247
213
|
if (existsRef) {
|
|
@@ -252,18 +218,15 @@ export default class AssignmentMatcher {
|
|
|
252
218
|
}
|
|
253
219
|
}
|
|
254
220
|
await multi.exec();
|
|
255
|
-
|
|
256
221
|
return { id, priority };
|
|
257
222
|
}
|
|
258
|
-
|
|
259
|
-
async setAssignmentPriorityByTags(tags: string[], priority: number) {
|
|
223
|
+
async setAssignmentPriorityByTags(tags, priority) {
|
|
260
224
|
// Update priorities for all assignments that include any of the specified tags.
|
|
261
225
|
const assignments = await this.getAllAssignments();
|
|
262
226
|
const relevantAssignments = assignments.filter((assignment) => {
|
|
263
227
|
const assignmentTagSet = new Set(assignment.tags);
|
|
264
228
|
return tags.some((tag) => assignmentTagSet.has(tag));
|
|
265
229
|
});
|
|
266
|
-
|
|
267
230
|
if (relevantAssignments.length > 0) {
|
|
268
231
|
const multi = this.redisClient.multi();
|
|
269
232
|
for (const assignment of relevantAssignments) {
|
|
@@ -281,51 +244,53 @@ export default class AssignmentMatcher {
|
|
|
281
244
|
}
|
|
282
245
|
await multi.exec();
|
|
283
246
|
}
|
|
284
|
-
|
|
285
247
|
return relevantAssignments.map((assignment) => ({ id: assignment.id, priority }));
|
|
286
248
|
}
|
|
287
|
-
|
|
288
|
-
private async getUserRelatedAssignments(user: User) {
|
|
249
|
+
async getUserRelatedAssignments(user) {
|
|
289
250
|
// Build candidate assignments using per-tag zset union with user weights for scalability.
|
|
290
|
-
const positiveWeights
|
|
291
|
-
const zeroWeightTags
|
|
292
|
-
|
|
251
|
+
const positiveWeights = [];
|
|
252
|
+
const zeroWeightTags = [];
|
|
293
253
|
if (user.routingWeights && Object.keys(user.routingWeights).length > 0) {
|
|
294
254
|
for (const [tag, w] of Object.entries(user.routingWeights)) {
|
|
295
|
-
if (typeof w === 'number' && w > 0)
|
|
296
|
-
|
|
255
|
+
if (typeof w === 'number' && w > 0)
|
|
256
|
+
positiveWeights.push({ tag, weight: w });
|
|
257
|
+
else if (w === 0)
|
|
258
|
+
zeroWeightTags.push(tag);
|
|
297
259
|
}
|
|
298
|
-
}
|
|
260
|
+
}
|
|
261
|
+
else {
|
|
299
262
|
// Fallback: use unweighted tags (weight 1)
|
|
300
263
|
for (const tag of user.tags || []) {
|
|
301
264
|
positiveWeights.push({ tag, weight: 1 });
|
|
302
265
|
}
|
|
303
266
|
}
|
|
304
|
-
|
|
305
267
|
// Ensure default tag is included if enabled and not explicitly weighted to zero
|
|
306
268
|
if (this.enableDefaultMatching) {
|
|
307
269
|
const defaultInPos = positiveWeights.find((t) => t.tag === 'default');
|
|
308
270
|
const defaultZero = zeroWeightTags.includes('default');
|
|
309
|
-
if (!defaultInPos && !defaultZero)
|
|
271
|
+
if (!defaultInPos && !defaultZero)
|
|
272
|
+
positiveWeights.push({ tag: 'default', weight: 1 });
|
|
310
273
|
}
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
274
|
+
const userAssignments = [];
|
|
275
|
+
if (positiveWeights.length === 0)
|
|
276
|
+
return userAssignments;
|
|
277
|
+
// Expand wildcards
|
|
278
|
+
const expandedPositive = await this.expandTagWildcards(positiveWeights);
|
|
279
|
+
const expandedZero = await this.expandTagWildcards(zeroWeightTags.map((t) => ({ tag: t, weight: 0 })));
|
|
280
|
+
const finalZeroTags = expandedZero.map((t) => t.tag);
|
|
281
|
+
if (expandedPositive.length === 0)
|
|
282
|
+
return userAssignments;
|
|
316
283
|
const tempKey = this.redisPrefix + `tmp:user:${user.id}:candidates`;
|
|
317
284
|
const tempZeroKey = this.redisPrefix + `tmp:user:${user.id}:exclude`;
|
|
318
285
|
const tempFinalKey = this.redisPrefix + `tmp:user:${user.id}:final`;
|
|
319
|
-
|
|
320
|
-
const
|
|
321
|
-
const unionWeights = positiveWeights.map((pw) => pw.weight);
|
|
322
|
-
|
|
286
|
+
const unionKeys = expandedPositive.map((pw) => this.redisPrefix + `tag:${pw.tag}:assignments`);
|
|
287
|
+
const unionWeights = expandedPositive.map((pw) => pw.weight);
|
|
323
288
|
const multi = this.redisClient.multi();
|
|
324
289
|
// Weighted union of positive tag assignment zsets
|
|
325
290
|
multi.zUnionStore(tempKey, unionKeys, { WEIGHTS: unionWeights });
|
|
326
291
|
// Optional exclude set for zero-weight tags
|
|
327
|
-
if (
|
|
328
|
-
const zeroKeys =
|
|
292
|
+
if (finalZeroTags.length > 0) {
|
|
293
|
+
const zeroKeys = finalZeroTags.map((t) => this.redisPrefix + `tag:${t}:assignments`);
|
|
329
294
|
multi.zUnionStore(tempZeroKey, zeroKeys);
|
|
330
295
|
// Final = candidates - exclude
|
|
331
296
|
multi.zDiffStore(tempFinalKey, [tempKey, tempZeroKey]);
|
|
@@ -333,43 +298,41 @@ export default class AssignmentMatcher {
|
|
|
333
298
|
multi.expire(tempKey, 5);
|
|
334
299
|
multi.expire(tempZeroKey, 5);
|
|
335
300
|
multi.expire(tempFinalKey, 5);
|
|
336
|
-
}
|
|
301
|
+
}
|
|
302
|
+
else {
|
|
337
303
|
// No exclude; just use tempKey as final (copy into final for uniformity)
|
|
338
304
|
multi.zUnionStore(tempFinalKey, [tempKey]);
|
|
339
305
|
multi.expire(tempKey, 5);
|
|
340
306
|
multi.expire(tempFinalKey, 5);
|
|
341
307
|
}
|
|
342
|
-
|
|
343
308
|
await multi.exec();
|
|
344
|
-
|
|
345
309
|
// Pull top-N in ascending score to preserve previous behavior on ties (lex ascending)
|
|
346
310
|
const top = await this.redisClient.zRangeWithScores(tempFinalKey, 0, this.relevantBatchSize - 1);
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
311
|
+
if (top.length === 0)
|
|
312
|
+
return userAssignments;
|
|
350
313
|
// Fetch per-assignment stored (base) priority and tags in a single pipeline (fewer round trips)
|
|
351
314
|
const batched = this.redisClient.multi();
|
|
352
315
|
for (const entry of top) {
|
|
353
|
-
const assignmentId =
|
|
316
|
+
const assignmentId = entry.value;
|
|
354
317
|
const assignmentPriorityKey = this.redisPrefix + `assignment:${assignmentId}:priority`;
|
|
355
318
|
const assignmentTagsKey = this.redisPrefix + `assignment:${assignmentId}:tags`;
|
|
356
319
|
batched.hGet(assignmentPriorityKey, 'priority');
|
|
357
320
|
batched.hGet(assignmentTagsKey, 'tags');
|
|
358
321
|
}
|
|
359
322
|
const flat = await batched.exec();
|
|
360
|
-
const details = []
|
|
323
|
+
const details = [];
|
|
361
324
|
for (let i = 0; i < top.length; i++) {
|
|
362
|
-
const assignmentId =
|
|
325
|
+
const assignmentId = top[i].value;
|
|
363
326
|
const priority = Number(flat[i * 2]) || 0;
|
|
364
327
|
const tags = String(flat[i * 2 + 1] || '');
|
|
365
328
|
details.push({ id: assignmentId, basePriority: priority, tags });
|
|
366
329
|
}
|
|
367
330
|
// Prefer higher base priority first to satisfy tests and practical expectations
|
|
368
331
|
details.sort((a, b) => b.basePriority - a.basePriority);
|
|
369
|
-
|
|
370
|
-
const selected: Array<{ id: string; tags: string }> = [];
|
|
332
|
+
const selected = [];
|
|
371
333
|
for (const d of details) {
|
|
372
|
-
if (userAssignments.length >= this.maxUserBacklogSize)
|
|
334
|
+
if (userAssignments.length >= this.maxUserBacklogSize)
|
|
335
|
+
break;
|
|
373
336
|
// Use custom matchScore (supports weights) for a final check and tie-break
|
|
374
337
|
const [score, combinedPriority] = await this.matchScore(user, d.tags, d.basePriority, d.id);
|
|
375
338
|
if (score && combinedPriority) {
|
|
@@ -377,11 +340,16 @@ export default class AssignmentMatcher {
|
|
|
377
340
|
selected.push({ id: d.id, tags: d.tags });
|
|
378
341
|
}
|
|
379
342
|
}
|
|
380
|
-
|
|
381
343
|
// Batch-remove all selected assignments from indexes and references to reduce round trips
|
|
382
344
|
if (selected.length > 0) {
|
|
345
|
+
// Fetch JSONs first to store in pending
|
|
346
|
+
const jsonPromises = selected.map((s) => this.redisClient.hGet(this.assignmentsRefKey, s.id));
|
|
347
|
+
const jsons = await Promise.all(jsonPromises);
|
|
348
|
+
const now = Date.now();
|
|
383
349
|
const rm = this.redisClient.multi();
|
|
384
|
-
for (
|
|
350
|
+
for (let i = 0; i < selected.length; i++) {
|
|
351
|
+
const s = selected[i];
|
|
352
|
+
const json = jsons[i];
|
|
385
353
|
const assignmentPriorityKey = this.redisPrefix + `assignment:${s.id}:priority`;
|
|
386
354
|
const assignmentTagsKey = this.redisPrefix + `assignment:${s.id}:tags`;
|
|
387
355
|
// Remove from reference and per-assignment hashes
|
|
@@ -391,70 +359,149 @@ export default class AssignmentMatcher {
|
|
|
391
359
|
// Remove from global zset
|
|
392
360
|
rm.zRem(this.assignmentsKey, s.id);
|
|
393
361
|
// Remove from per-tag zsets
|
|
394
|
-
const tags = (s.tags ? s.tags.split(',').filter(Boolean) : [])
|
|
362
|
+
const tags = (s.tags ? s.tags.split(',').filter(Boolean) : []);
|
|
395
363
|
for (const tag of tags) {
|
|
396
364
|
rm.zRem(this.redisPrefix + `tag:${tag}:assignments`, s.id);
|
|
397
365
|
}
|
|
366
|
+
// Add to pending structures
|
|
367
|
+
if (json) {
|
|
368
|
+
rm.hSet(this.pendingAssignmentsKey, s.id, json);
|
|
369
|
+
rm.zAdd(this.pendingAssignmentsExpiryKey, { score: now + this.matchExpirationMs, value: s.id });
|
|
370
|
+
rm.hSet(this.assignmentOwnerKey, s.id, user.id);
|
|
371
|
+
}
|
|
398
372
|
}
|
|
399
373
|
await rm.exec();
|
|
400
374
|
}
|
|
401
|
-
|
|
402
375
|
return userAssignments;
|
|
403
376
|
}
|
|
404
|
-
async matchUsersAssignments(userId
|
|
377
|
+
async matchUsersAssignments(userId) {
|
|
405
378
|
// If a specific userId is provided, process only that user for precise per-user matching.
|
|
406
379
|
if (userId) {
|
|
407
380
|
const userJson = await this.redisClient.hGet(this.usersKey, userId);
|
|
408
|
-
if (!userJson)
|
|
381
|
+
if (!userJson)
|
|
382
|
+
return;
|
|
409
383
|
const user = JSON.parse(userJson);
|
|
410
384
|
const userMatchesCount = await this.redisClient.sCard(this.redisPrefix + `user:${user.id}:assignments`);
|
|
411
|
-
if (userMatchesCount >= this.maxUserBacklogSize)
|
|
412
|
-
|
|
385
|
+
if (userMatchesCount >= this.maxUserBacklogSize)
|
|
386
|
+
return;
|
|
413
387
|
const relevantAssignments = await this.getUserRelatedAssignments(user);
|
|
414
388
|
const relevantAssignmentKeys = relevantAssignments
|
|
415
389
|
.sort((a, b) => b.priority - a.priority)
|
|
416
390
|
.map((a) => `assignment:${a.id}`);
|
|
417
|
-
|
|
418
391
|
if (relevantAssignmentKeys.length > 0) {
|
|
419
392
|
await this.redisClient.sAdd(this.redisPrefix + `user:${user.id}:assignments`, relevantAssignmentKeys);
|
|
420
393
|
}
|
|
421
394
|
return;
|
|
422
395
|
}
|
|
423
|
-
|
|
424
396
|
// Otherwise, process all users in parallel as before.
|
|
425
|
-
let users
|
|
397
|
+
let users = [];
|
|
426
398
|
let cursor = 0;
|
|
427
|
-
|
|
428
399
|
// Fetch all users in a single loop
|
|
429
400
|
do {
|
|
430
401
|
const { cursor: nextCursor, tuples } = await this.redisClient.hScan(this.usersKey, cursor);
|
|
431
|
-
users.push(...tuples.map((t
|
|
402
|
+
users.push(...tuples.map((t) => JSON.parse(t.value)));
|
|
432
403
|
cursor = nextCursor;
|
|
433
404
|
} while (cursor !== 0);
|
|
434
|
-
|
|
435
405
|
// Process users in parallel
|
|
436
|
-
await Promise.all(
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
await this.redisClient.sAdd(this.redisPrefix + `user:${user.id}:assignments`, relevantAssignmentKeys);
|
|
450
|
-
}
|
|
451
|
-
}),
|
|
452
|
-
);
|
|
406
|
+
await Promise.all(users.map(async (user) => {
|
|
407
|
+
const userMatchesCount = await this.redisClient.sCard(this.redisPrefix + `user:${user.id}:assignments`);
|
|
408
|
+
if (userMatchesCount >= this.maxUserBacklogSize) {
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
411
|
+
const relevantAssignments = await this.getUserRelatedAssignments(user);
|
|
412
|
+
const relevantAssignmentKeys = relevantAssignments
|
|
413
|
+
.sort((a, b) => b.priority - a.priority)
|
|
414
|
+
.map((a) => `assignment:${a.id}`);
|
|
415
|
+
if (relevantAssignmentKeys.length > 0) {
|
|
416
|
+
await this.redisClient.sAdd(this.redisPrefix + `user:${user.id}:assignments`, relevantAssignmentKeys);
|
|
417
|
+
}
|
|
418
|
+
}));
|
|
453
419
|
}
|
|
454
|
-
|
|
455
|
-
async getCurrentAssignmentsForUser(userId: string): Promise<string[]> {
|
|
420
|
+
async getCurrentAssignmentsForUser(userId) {
|
|
456
421
|
const userAssignments = await this.redisClient.sMembers(this.redisPrefix + `user:${userId}:assignments`);
|
|
457
|
-
|
|
458
|
-
|
|
422
|
+
return userAssignments.map((el) => el.split(':')[1]);
|
|
423
|
+
}
|
|
424
|
+
async acceptAssignment(userId, assignmentId) {
|
|
425
|
+
const isAssigned = await this.redisClient.sIsMember(this.redisPrefix + `user:${userId}:assignments`, `assignment:${assignmentId}`);
|
|
426
|
+
if (!isAssigned)
|
|
427
|
+
throw new Error('Assignment not found for user');
|
|
428
|
+
const multi = this.redisClient.multi();
|
|
429
|
+
multi.sRem(this.redisPrefix + `user:${userId}:assignments`, `assignment:${assignmentId}`);
|
|
430
|
+
multi.hDel(this.pendingAssignmentsKey, assignmentId);
|
|
431
|
+
multi.zRem(this.pendingAssignmentsExpiryKey, assignmentId);
|
|
432
|
+
multi.hDel(this.assignmentOwnerKey, assignmentId);
|
|
433
|
+
await multi.exec();
|
|
434
|
+
return true;
|
|
435
|
+
}
|
|
436
|
+
async rejectAssignment(userId, assignmentId) {
|
|
437
|
+
const isAssigned = await this.redisClient.sIsMember(this.redisPrefix + `user:${userId}:assignments`, `assignment:${assignmentId}`);
|
|
438
|
+
if (!isAssigned)
|
|
439
|
+
throw new Error('Assignment not found for user');
|
|
440
|
+
const json = await this.redisClient.hGet(this.pendingAssignmentsKey, assignmentId);
|
|
441
|
+
const multi = this.redisClient.multi();
|
|
442
|
+
multi.sRem(this.redisPrefix + `user:${userId}:assignments`, `assignment:${assignmentId}`);
|
|
443
|
+
multi.hDel(this.pendingAssignmentsKey, assignmentId);
|
|
444
|
+
multi.zRem(this.pendingAssignmentsExpiryKey, assignmentId);
|
|
445
|
+
multi.hDel(this.assignmentOwnerKey, assignmentId);
|
|
446
|
+
await multi.exec();
|
|
447
|
+
if (json) {
|
|
448
|
+
await this.addAssignment(JSON.parse(json));
|
|
449
|
+
}
|
|
450
|
+
return true;
|
|
451
|
+
}
|
|
452
|
+
async processExpiredMatches() {
|
|
453
|
+
const now = Date.now();
|
|
454
|
+
const expiredIds = await this.redisClient.zRangeByScore(this.pendingAssignmentsExpiryKey, '-inf', now);
|
|
455
|
+
for (const id of expiredIds) {
|
|
456
|
+
const owner = await this.redisClient.hGet(this.assignmentOwnerKey, id);
|
|
457
|
+
const json = await this.redisClient.hGet(this.pendingAssignmentsKey, id);
|
|
458
|
+
const multi = this.redisClient.multi();
|
|
459
|
+
if (owner) {
|
|
460
|
+
multi.sRem(this.redisPrefix + `user:${owner}:assignments`, `assignment:${id}`);
|
|
461
|
+
}
|
|
462
|
+
multi.hDel(this.pendingAssignmentsKey, id);
|
|
463
|
+
multi.zRem(this.pendingAssignmentsExpiryKey, id);
|
|
464
|
+
multi.hDel(this.assignmentOwnerKey, id);
|
|
465
|
+
await multi.exec();
|
|
466
|
+
if (json) {
|
|
467
|
+
await this.addAssignment(JSON.parse(json));
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
return expiredIds.length;
|
|
471
|
+
}
|
|
472
|
+
startAutoReleaseInterval(intervalMs = 10000) {
|
|
473
|
+
if (this.autoReleaseInterval)
|
|
474
|
+
return;
|
|
475
|
+
this.autoReleaseInterval = setInterval(() => {
|
|
476
|
+
this.processExpiredMatches().catch(console.error);
|
|
477
|
+
}, intervalMs);
|
|
478
|
+
}
|
|
479
|
+
stopAutoReleaseInterval() {
|
|
480
|
+
if (this.autoReleaseInterval) {
|
|
481
|
+
clearInterval(this.autoReleaseInterval);
|
|
482
|
+
this.autoReleaseInterval = null;
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
async expandTagWildcards(tags) {
|
|
486
|
+
const expanded = [];
|
|
487
|
+
const wildcards = tags.filter((t) => t.tag.endsWith('*'));
|
|
488
|
+
const literals = tags.filter((t) => !t.tag.endsWith('*'));
|
|
489
|
+
expanded.push(...literals);
|
|
490
|
+
if (wildcards.length > 0) {
|
|
491
|
+
const promises = wildcards.map((w) => {
|
|
492
|
+
const prefix = w.tag.slice(0, -1);
|
|
493
|
+
return this.redisClient.zRangeByLex(this.allTagsKey, `[${prefix}`, `[${prefix}\xff`);
|
|
494
|
+
});
|
|
495
|
+
const results = await Promise.all(promises);
|
|
496
|
+
for (let i = 0; i < wildcards.length; i++) {
|
|
497
|
+
const w = wildcards[i];
|
|
498
|
+
const matchedTags = results[i];
|
|
499
|
+
for (const tag of matchedTags) {
|
|
500
|
+
expanded.push({ tag, weight: w.weight });
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
return expanded;
|
|
459
505
|
}
|
|
460
506
|
}
|
|
507
|
+
exports.default = AssignmentMatcher;
|