assignment-user-matcher 1.0.10 → 1.0.14
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/LICENCE +53 -0
- package/README.md +196 -148
- 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 +60 -0
- package/dist/matcher.class.d.ts.map +1 -0
- package/dist/matcher.class.js +363 -0
- package/package.json +16 -3
- package/.github/workflows/npm-publish.yml +0 -84
- package/.mocharc.json +0 -11
- package/.prettierignore +0 -1
- package/.vscode/launch.json +0 -32
- package/docs/README.md +0 -109
- package/docs/classes/default.md +0 -397
- package/docs/interfaces/User.md +0 -34
- package/docs/modules.md +0 -91
- package/src/matcher.class.ts +0 -291
- package/tests/matcher.test.ts +0 -372
- package/tsconfig.json +0 -22
|
@@ -0,0 +1,363 @@
|
|
|
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;
|
|
6
|
+
this.redisClient = redisClient;
|
|
7
|
+
this.relevantBatchSize = (_a = options === null || options === void 0 ? void 0 : options.relevantBatchSize) !== null && _a !== void 0 ? _a : 50;
|
|
8
|
+
this.enableDefaultMatching = (_b = options === null || options === void 0 ? void 0 : options.enableDefaultMatching) !== null && _b !== void 0 ? _b : true;
|
|
9
|
+
this.redisPrefix = (_c = options === null || options === void 0 ? void 0 : options.redisPrefix) !== null && _c !== void 0 ? _c : '';
|
|
10
|
+
this.usersKey = this.redisPrefix + 'users';
|
|
11
|
+
this.assignmentsKey = this.redisPrefix + 'assignments';
|
|
12
|
+
this.assignmentsRefKey = this.redisPrefix + 'assignments:ref';
|
|
13
|
+
this.maxUserBacklogSize = (_d = options === null || options === void 0 ? void 0 : options.maxUserBacklogSize) !== null && _d !== void 0 ? _d : 9;
|
|
14
|
+
this.calculatePriority = (_e = options === null || options === void 0 ? void 0 : options.prioritizationFunction) !== null && _e !== void 0 ? _e : this.calculatePriority;
|
|
15
|
+
this.matchScore = (_f = options === null || options === void 0 ? void 0 : options.matchingFunction) !== null && _f !== void 0 ? _f : this.matchScore;
|
|
16
|
+
this.initRedis();
|
|
17
|
+
}
|
|
18
|
+
async initRedis() {
|
|
19
|
+
// Only attempt to connect if the client isn't already connected
|
|
20
|
+
if (!this.redisClient.isOpen) {
|
|
21
|
+
await this.redisClient.connect();
|
|
22
|
+
}
|
|
23
|
+
return this;
|
|
24
|
+
}
|
|
25
|
+
async addUser(user) {
|
|
26
|
+
await this.redisClient.hSet(this.usersKey, user.id, JSON.stringify({
|
|
27
|
+
...user,
|
|
28
|
+
tags: [...user.tags, ...(this.enableDefaultMatching ? ['default'] : [])],
|
|
29
|
+
}));
|
|
30
|
+
return user;
|
|
31
|
+
}
|
|
32
|
+
async addAssignment(assignment) {
|
|
33
|
+
let { id, tags, priority, latitude, longitude } = assignment;
|
|
34
|
+
if (!priority)
|
|
35
|
+
priority = await this.calculatePriority(assignment);
|
|
36
|
+
const assignmentPriorityKey = this.redisPrefix + `assignment:${id}:priority`;
|
|
37
|
+
const assignmentTagsKey = this.redisPrefix + `assignment:${id}:tags`;
|
|
38
|
+
const assignmentGeoKey = this.redisPrefix + `assignments:geo`;
|
|
39
|
+
const multi = this.redisClient
|
|
40
|
+
.multi()
|
|
41
|
+
.hSet(this.assignmentsRefKey, id, JSON.stringify(assignment))
|
|
42
|
+
.hSet(assignmentPriorityKey, 'priority', priority)
|
|
43
|
+
// Ensure 'default' tag is persisted consistently when enabled
|
|
44
|
+
.hSet(assignmentTagsKey, 'tags', tags.join(',') + (this.enableDefaultMatching ? ',default' : ''))
|
|
45
|
+
.zAdd(this.assignmentsKey, {
|
|
46
|
+
score: priority,
|
|
47
|
+
value: id,
|
|
48
|
+
});
|
|
49
|
+
if (latitude && longitude) {
|
|
50
|
+
multi.geoAdd(assignmentGeoKey, {
|
|
51
|
+
longitude,
|
|
52
|
+
latitude,
|
|
53
|
+
member: id,
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
// Also index assignment into per-tag sorted sets (by priority)
|
|
57
|
+
// This enables efficient weighted matching via ZUNIONSTORE.
|
|
58
|
+
const indexTags = [...tags, ...(this.enableDefaultMatching ? ['default'] : [])];
|
|
59
|
+
for (const tag of indexTags) {
|
|
60
|
+
multi.zAdd(this.redisPrefix + `tag:${tag}:assignments`, {
|
|
61
|
+
score: Number(priority),
|
|
62
|
+
value: id,
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
await multi.exec();
|
|
66
|
+
return assignment;
|
|
67
|
+
}
|
|
68
|
+
async removeAssignment(id) {
|
|
69
|
+
const assignmentPriorityKey = this.redisPrefix + `assignment:${id}:priority`;
|
|
70
|
+
const assignmentTagsKey = this.redisPrefix + `assignment:${id}:tags`;
|
|
71
|
+
// Fetch tags to remove from per-tag indices
|
|
72
|
+
const [tagsCsv] = await this.redisClient.multi().hGet(assignmentTagsKey, 'tags').exec();
|
|
73
|
+
const tags = (typeof tagsCsv === 'string' && tagsCsv.length > 0 ? tagsCsv.split(',') : []);
|
|
74
|
+
const multi = this.redisClient.multi();
|
|
75
|
+
// Remove from reference and per-assignment hashes
|
|
76
|
+
multi.hDel(this.assignmentsRefKey, id);
|
|
77
|
+
multi.del(assignmentPriorityKey);
|
|
78
|
+
multi.del(assignmentTagsKey);
|
|
79
|
+
// Remove from global zset
|
|
80
|
+
multi.zRem(this.assignmentsKey, id.toString());
|
|
81
|
+
// Remove from per-tag zsets
|
|
82
|
+
for (const tag of tags) {
|
|
83
|
+
multi.zRem(this.redisPrefix + `tag:${tag}:assignments`, id.toString());
|
|
84
|
+
}
|
|
85
|
+
await multi.exec();
|
|
86
|
+
return id;
|
|
87
|
+
}
|
|
88
|
+
async removeUser(userId) {
|
|
89
|
+
const multi = this.redisClient
|
|
90
|
+
.multi()
|
|
91
|
+
.del(this.redisPrefix + `user:${userId}:assignments`)
|
|
92
|
+
.hDel(this.usersKey, userId);
|
|
93
|
+
await multi.exec();
|
|
94
|
+
return userId;
|
|
95
|
+
}
|
|
96
|
+
async getAllAssignments() {
|
|
97
|
+
const assignments = await this.redisClient.hGetAll(this.assignmentsRefKey);
|
|
98
|
+
return Object.values(assignments).map((assignment) => JSON.parse(assignment));
|
|
99
|
+
}
|
|
100
|
+
async matchScore(user, assignmentTags, assignmentPriority, assignmentId) {
|
|
101
|
+
// If weighted skills are present, use them for scoring
|
|
102
|
+
if (user.routingWeights && Object.keys(user.routingWeights).length > 0) {
|
|
103
|
+
const aTags = assignmentTags ? assignmentTags.split(',') : [];
|
|
104
|
+
// If any assignment tag has explicit weight 0, treat as a hard exclude
|
|
105
|
+
for (const t of aTags) {
|
|
106
|
+
if (user.routingWeights[t] === 0) {
|
|
107
|
+
return [0, Number(assignmentPriority) || 0];
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
let weightSum = 0;
|
|
111
|
+
for (const t of aTags) {
|
|
112
|
+
const w = user.routingWeights[t];
|
|
113
|
+
if (typeof w === 'number' && w > 0)
|
|
114
|
+
weightSum += w;
|
|
115
|
+
}
|
|
116
|
+
const base = Number(assignmentPriority) || 0;
|
|
117
|
+
// score: total positive weight overlap; priority: base weighted slightly by weight
|
|
118
|
+
return [weightSum, base + weightSum];
|
|
119
|
+
}
|
|
120
|
+
// Fallback to default tag-intersection scoring
|
|
121
|
+
const userTagSet = new Set(user.tags);
|
|
122
|
+
const assignmentTagSet = new Set((assignmentTags || '').split(',').filter(Boolean));
|
|
123
|
+
const intersection = new Set([...userTagSet].filter((tag) => assignmentTagSet.has(tag)));
|
|
124
|
+
const score = userTagSet.size > 0 ? intersection.size / userTagSet.size : 0;
|
|
125
|
+
const base = Number(assignmentPriority) || 0;
|
|
126
|
+
return [score || 0, base + (score || 0)];
|
|
127
|
+
}
|
|
128
|
+
async calculatePriority(...args) {
|
|
129
|
+
const [assignment] = args;
|
|
130
|
+
return new Date().getTime() - (assignment === null || assignment === void 0 ? void 0 : assignment.createdAt) || 0;
|
|
131
|
+
}
|
|
132
|
+
get stats() {
|
|
133
|
+
return (async () => {
|
|
134
|
+
const users = await this.redisClient.hGetAll(this.usersKey);
|
|
135
|
+
const usersWithoutAssignment = await this.usersWithoutAssignment;
|
|
136
|
+
const remainingAssignments = await this.redisClient.zCount(this.assignmentsKey, '-inf', '+inf');
|
|
137
|
+
return {
|
|
138
|
+
users: Object.keys(users).length,
|
|
139
|
+
usersWithoutAssignment,
|
|
140
|
+
remainingAssignments,
|
|
141
|
+
};
|
|
142
|
+
})();
|
|
143
|
+
}
|
|
144
|
+
get usersWithoutAssignment() {
|
|
145
|
+
return (async () => {
|
|
146
|
+
const users = await this.redisClient.hGetAll(this.usersKey);
|
|
147
|
+
const usersWithoutAssignment = [];
|
|
148
|
+
for (const user of Object.values(users)) {
|
|
149
|
+
const { id } = JSON.parse(user);
|
|
150
|
+
const userAssignments = await this.getCurrentAssignmentsForUser(id);
|
|
151
|
+
if (userAssignments.length === 0)
|
|
152
|
+
usersWithoutAssignment.push(id);
|
|
153
|
+
}
|
|
154
|
+
return usersWithoutAssignment;
|
|
155
|
+
})();
|
|
156
|
+
}
|
|
157
|
+
async setAssignmentPriority(id, priority) {
|
|
158
|
+
const assignmentPriorityKey = this.redisPrefix + `assignment:${id}:priority`;
|
|
159
|
+
// Fetch tags to update per-tag indices
|
|
160
|
+
const assignmentTagsKey = this.redisPrefix + `assignment:${id}:tags`;
|
|
161
|
+
const [existsRef, tagsCsv] = await this.redisClient
|
|
162
|
+
.multi()
|
|
163
|
+
.hExists(this.assignmentsRefKey, id)
|
|
164
|
+
.hGet(assignmentTagsKey, 'tags')
|
|
165
|
+
.exec();
|
|
166
|
+
const tags = (typeof tagsCsv === 'string' && tagsCsv.length > 0 ? tagsCsv.split(',') : []);
|
|
167
|
+
const multi = this.redisClient.multi();
|
|
168
|
+
multi.hSet(assignmentPriorityKey, 'priority', priority);
|
|
169
|
+
if (existsRef) {
|
|
170
|
+
// Update global zset score and per-tag zset scores only if assignment still exists
|
|
171
|
+
multi.zAdd(this.assignmentsKey, { score: Number(priority), value: id });
|
|
172
|
+
for (const tag of tags) {
|
|
173
|
+
multi.zAdd(this.redisPrefix + `tag:${tag}:assignments`, { score: Number(priority), value: id });
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
await multi.exec();
|
|
177
|
+
return { id, priority };
|
|
178
|
+
}
|
|
179
|
+
async setAssignmentPriorityByTags(tags, priority) {
|
|
180
|
+
// Update priorities for all assignments that include any of the specified tags.
|
|
181
|
+
const assignments = await this.getAllAssignments();
|
|
182
|
+
const relevantAssignments = assignments.filter((assignment) => {
|
|
183
|
+
const assignmentTagSet = new Set(assignment.tags);
|
|
184
|
+
return tags.some((tag) => assignmentTagSet.has(tag));
|
|
185
|
+
});
|
|
186
|
+
if (relevantAssignments.length > 0) {
|
|
187
|
+
const multi = this.redisClient.multi();
|
|
188
|
+
for (const assignment of relevantAssignments) {
|
|
189
|
+
const id = assignment.id;
|
|
190
|
+
const assignmentPriorityKey = this.redisPrefix + `assignment:${id}:priority`;
|
|
191
|
+
// Update the stored priority
|
|
192
|
+
multi.hSet(assignmentPriorityKey, 'priority', priority);
|
|
193
|
+
// Update global zset score
|
|
194
|
+
multi.zAdd(this.assignmentsKey, { score: Number(priority), value: id });
|
|
195
|
+
// Update per-tag zset scores
|
|
196
|
+
const idxTags = [...assignment.tags, ...(this.enableDefaultMatching ? ['default'] : [])];
|
|
197
|
+
for (const tag of idxTags) {
|
|
198
|
+
multi.zAdd(this.redisPrefix + `tag:${tag}:assignments`, { score: Number(priority), value: id });
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
await multi.exec();
|
|
202
|
+
}
|
|
203
|
+
return relevantAssignments.map((assignment) => ({ id: assignment.id, priority }));
|
|
204
|
+
}
|
|
205
|
+
async getUserRelatedAssignments(user) {
|
|
206
|
+
// Build candidate assignments using per-tag zset union with user weights for scalability.
|
|
207
|
+
const positiveWeights = [];
|
|
208
|
+
const zeroWeightTags = [];
|
|
209
|
+
if (user.routingWeights && Object.keys(user.routingWeights).length > 0) {
|
|
210
|
+
for (const [tag, w] of Object.entries(user.routingWeights)) {
|
|
211
|
+
if (typeof w === 'number' && w > 0)
|
|
212
|
+
positiveWeights.push({ tag, weight: w });
|
|
213
|
+
else if (w === 0)
|
|
214
|
+
zeroWeightTags.push(tag);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
else {
|
|
218
|
+
// Fallback: use unweighted tags (weight 1)
|
|
219
|
+
for (const tag of user.tags || []) {
|
|
220
|
+
positiveWeights.push({ tag, weight: 1 });
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
// Ensure default tag is included if enabled and not explicitly weighted to zero
|
|
224
|
+
if (this.enableDefaultMatching) {
|
|
225
|
+
const defaultInPos = positiveWeights.find((t) => t.tag === 'default');
|
|
226
|
+
const defaultZero = zeroWeightTags.includes('default');
|
|
227
|
+
if (!defaultInPos && !defaultZero)
|
|
228
|
+
positiveWeights.push({ tag: 'default', weight: 1 });
|
|
229
|
+
}
|
|
230
|
+
const userAssignments = [];
|
|
231
|
+
if (positiveWeights.length === 0)
|
|
232
|
+
return userAssignments;
|
|
233
|
+
const tempKey = this.redisPrefix + `tmp:user:${user.id}:candidates`;
|
|
234
|
+
const tempZeroKey = this.redisPrefix + `tmp:user:${user.id}:exclude`;
|
|
235
|
+
const tempFinalKey = this.redisPrefix + `tmp:user:${user.id}:final`;
|
|
236
|
+
const unionKeys = positiveWeights.map((pw) => this.redisPrefix + `tag:${pw.tag}:assignments`);
|
|
237
|
+
const unionWeights = positiveWeights.map((pw) => pw.weight);
|
|
238
|
+
const multi = this.redisClient.multi();
|
|
239
|
+
// Weighted union of positive tag assignment zsets
|
|
240
|
+
multi.zUnionStore(tempKey, unionKeys, { WEIGHTS: unionWeights });
|
|
241
|
+
// Optional exclude set for zero-weight tags
|
|
242
|
+
if (zeroWeightTags.length > 0) {
|
|
243
|
+
const zeroKeys = zeroWeightTags.map((t) => this.redisPrefix + `tag:${t}:assignments`);
|
|
244
|
+
multi.zUnionStore(tempZeroKey, zeroKeys);
|
|
245
|
+
// Final = candidates - exclude
|
|
246
|
+
multi.zDiffStore(tempFinalKey, [tempKey, tempZeroKey]);
|
|
247
|
+
// Set short TTLs to clean up
|
|
248
|
+
multi.expire(tempKey, 5);
|
|
249
|
+
multi.expire(tempZeroKey, 5);
|
|
250
|
+
multi.expire(tempFinalKey, 5);
|
|
251
|
+
}
|
|
252
|
+
else {
|
|
253
|
+
// No exclude; just use tempKey as final (copy into final for uniformity)
|
|
254
|
+
multi.zUnionStore(tempFinalKey, [tempKey]);
|
|
255
|
+
multi.expire(tempKey, 5);
|
|
256
|
+
multi.expire(tempFinalKey, 5);
|
|
257
|
+
}
|
|
258
|
+
await multi.exec();
|
|
259
|
+
// Pull top-N in ascending score to preserve previous behavior on ties (lex ascending)
|
|
260
|
+
const top = await this.redisClient.zRangeWithScores(tempFinalKey, 0, this.relevantBatchSize - 1);
|
|
261
|
+
if (top.length === 0)
|
|
262
|
+
return userAssignments;
|
|
263
|
+
// Fetch per-assignment stored (base) priority and tags in a single pipeline (fewer round trips)
|
|
264
|
+
const batched = this.redisClient.multi();
|
|
265
|
+
for (const entry of top) {
|
|
266
|
+
const assignmentId = entry.value;
|
|
267
|
+
const assignmentPriorityKey = this.redisPrefix + `assignment:${assignmentId}:priority`;
|
|
268
|
+
const assignmentTagsKey = this.redisPrefix + `assignment:${assignmentId}:tags`;
|
|
269
|
+
batched.hGet(assignmentPriorityKey, 'priority');
|
|
270
|
+
batched.hGet(assignmentTagsKey, 'tags');
|
|
271
|
+
}
|
|
272
|
+
const flat = await batched.exec();
|
|
273
|
+
const details = [];
|
|
274
|
+
for (let i = 0; i < top.length; i++) {
|
|
275
|
+
const assignmentId = top[i].value;
|
|
276
|
+
const priority = Number(flat[i * 2]) || 0;
|
|
277
|
+
const tags = String(flat[i * 2 + 1] || '');
|
|
278
|
+
details.push({ id: assignmentId, basePriority: priority, tags });
|
|
279
|
+
}
|
|
280
|
+
// Prefer higher base priority first to satisfy tests and practical expectations
|
|
281
|
+
details.sort((a, b) => b.basePriority - a.basePriority);
|
|
282
|
+
const selected = [];
|
|
283
|
+
for (const d of details) {
|
|
284
|
+
if (userAssignments.length >= this.maxUserBacklogSize)
|
|
285
|
+
break;
|
|
286
|
+
// Use custom matchScore (supports weights) for a final check and tie-break
|
|
287
|
+
const [score, combinedPriority] = await this.matchScore(user, d.tags, d.basePriority, d.id);
|
|
288
|
+
if (score && combinedPriority) {
|
|
289
|
+
userAssignments.push({ id: d.id, priority: combinedPriority });
|
|
290
|
+
selected.push({ id: d.id, tags: d.tags });
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
// Batch-remove all selected assignments from indexes and references to reduce round trips
|
|
294
|
+
if (selected.length > 0) {
|
|
295
|
+
const rm = this.redisClient.multi();
|
|
296
|
+
for (const s of selected) {
|
|
297
|
+
const assignmentPriorityKey = this.redisPrefix + `assignment:${s.id}:priority`;
|
|
298
|
+
const assignmentTagsKey = this.redisPrefix + `assignment:${s.id}:tags`;
|
|
299
|
+
// Remove from reference and per-assignment hashes
|
|
300
|
+
rm.hDel(this.assignmentsRefKey, s.id);
|
|
301
|
+
rm.del(assignmentPriorityKey);
|
|
302
|
+
rm.del(assignmentTagsKey);
|
|
303
|
+
// Remove from global zset
|
|
304
|
+
rm.zRem(this.assignmentsKey, s.id);
|
|
305
|
+
// Remove from per-tag zsets
|
|
306
|
+
const tags = (s.tags ? s.tags.split(',').filter(Boolean) : []);
|
|
307
|
+
for (const tag of tags) {
|
|
308
|
+
rm.zRem(this.redisPrefix + `tag:${tag}:assignments`, s.id);
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
await rm.exec();
|
|
312
|
+
}
|
|
313
|
+
return userAssignments;
|
|
314
|
+
}
|
|
315
|
+
async matchUsersAssignments(userId) {
|
|
316
|
+
// If a specific userId is provided, process only that user for precise per-user matching.
|
|
317
|
+
if (userId) {
|
|
318
|
+
const userJson = await this.redisClient.hGet(this.usersKey, userId);
|
|
319
|
+
if (!userJson)
|
|
320
|
+
return;
|
|
321
|
+
const user = JSON.parse(userJson);
|
|
322
|
+
const userMatchesCount = await this.redisClient.sCard(this.redisPrefix + `user:${user.id}:assignments`);
|
|
323
|
+
if (userMatchesCount >= this.maxUserBacklogSize)
|
|
324
|
+
return;
|
|
325
|
+
const relevantAssignments = await this.getUserRelatedAssignments(user);
|
|
326
|
+
const relevantAssignmentKeys = relevantAssignments
|
|
327
|
+
.sort((a, b) => b.priority - a.priority)
|
|
328
|
+
.map((a) => `assignment:${a.id}`);
|
|
329
|
+
if (relevantAssignmentKeys.length > 0) {
|
|
330
|
+
await this.redisClient.sAdd(this.redisPrefix + `user:${user.id}:assignments`, relevantAssignmentKeys);
|
|
331
|
+
}
|
|
332
|
+
return;
|
|
333
|
+
}
|
|
334
|
+
// Otherwise, process all users in parallel as before.
|
|
335
|
+
let users = [];
|
|
336
|
+
let cursor = 0;
|
|
337
|
+
// Fetch all users in a single loop
|
|
338
|
+
do {
|
|
339
|
+
const { cursor: nextCursor, tuples } = await this.redisClient.hScan(this.usersKey, cursor);
|
|
340
|
+
users.push(...tuples.map((t) => JSON.parse(t.value)));
|
|
341
|
+
cursor = nextCursor;
|
|
342
|
+
} while (cursor !== 0);
|
|
343
|
+
// Process users in parallel
|
|
344
|
+
await Promise.all(users.map(async (user) => {
|
|
345
|
+
const userMatchesCount = await this.redisClient.sCard(this.redisPrefix + `user:${user.id}:assignments`);
|
|
346
|
+
if (userMatchesCount >= this.maxUserBacklogSize) {
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
const relevantAssignments = await this.getUserRelatedAssignments(user);
|
|
350
|
+
const relevantAssignmentKeys = relevantAssignments
|
|
351
|
+
.sort((a, b) => b.priority - a.priority)
|
|
352
|
+
.map((a) => `assignment:${a.id}`);
|
|
353
|
+
if (relevantAssignmentKeys.length > 0) {
|
|
354
|
+
await this.redisClient.sAdd(this.redisPrefix + `user:${user.id}:assignments`, relevantAssignmentKeys);
|
|
355
|
+
}
|
|
356
|
+
}));
|
|
357
|
+
}
|
|
358
|
+
async getCurrentAssignmentsForUser(userId) {
|
|
359
|
+
const userAssignments = await this.redisClient.sMembers(this.redisPrefix + `user:${userId}:assignments`);
|
|
360
|
+
return userAssignments.map((el) => el.split(':')[1]);
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
exports.default = AssignmentMatcher;
|
package/package.json
CHANGED
|
@@ -1,7 +1,20 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "assignment-user-matcher",
|
|
3
|
-
"version": "1.0.
|
|
4
|
-
"main": "index.js",
|
|
3
|
+
"version": "1.0.14",
|
|
4
|
+
"main": "dist/index.js",
|
|
5
|
+
"module": "dist/index.js",
|
|
6
|
+
"types": "dist/index.d.ts",
|
|
7
|
+
"files": [
|
|
8
|
+
"dist"
|
|
9
|
+
],
|
|
10
|
+
"exports": {
|
|
11
|
+
"./package.json": "./package.json",
|
|
12
|
+
".": {
|
|
13
|
+
"types": "./dist/index.d.ts",
|
|
14
|
+
"require": "./dist/index.js",
|
|
15
|
+
"import": "./dist/index.js"
|
|
16
|
+
}
|
|
17
|
+
},
|
|
5
18
|
"author": "Viljar Võidula",
|
|
6
19
|
"license": "MIT",
|
|
7
20
|
"private": false,
|
|
@@ -27,7 +40,7 @@
|
|
|
27
40
|
"rimraf": "4.4.1",
|
|
28
41
|
"sinon": "20.0.0",
|
|
29
42
|
"ts-node": "10.9.2",
|
|
30
|
-
"typedoc": "0.
|
|
43
|
+
"typedoc": "^0.25.0",
|
|
31
44
|
"typedoc-plugin-markdown": "3.17.1",
|
|
32
45
|
"typescript": "4.9.5"
|
|
33
46
|
},
|
|
@@ -1,84 +0,0 @@
|
|
|
1
|
-
name: CI and NPM Publish
|
|
2
|
-
|
|
3
|
-
on:
|
|
4
|
-
push:
|
|
5
|
-
branches:
|
|
6
|
-
- 'main'
|
|
7
|
-
- '**'
|
|
8
|
-
tags:
|
|
9
|
-
- '*'
|
|
10
|
-
|
|
11
|
-
jobs:
|
|
12
|
-
test:
|
|
13
|
-
runs-on: ubuntu-latest
|
|
14
|
-
env:
|
|
15
|
-
FORCE_JAVASCRIPT_ACTIONS_TO_NODE20: true
|
|
16
|
-
services:
|
|
17
|
-
redis:
|
|
18
|
-
image: redis:latest
|
|
19
|
-
ports:
|
|
20
|
-
- 6379:6379
|
|
21
|
-
steps:
|
|
22
|
-
- name: Checkout code
|
|
23
|
-
uses: actions/checkout@v4
|
|
24
|
-
|
|
25
|
-
- name: Install pnpm action
|
|
26
|
-
uses: pnpm/action-setup@v4
|
|
27
|
-
with:
|
|
28
|
-
version: 9
|
|
29
|
-
run_install: false
|
|
30
|
-
|
|
31
|
-
- name: Set up Node.js
|
|
32
|
-
uses: actions/setup-node@v4
|
|
33
|
-
with:
|
|
34
|
-
node-version: 22
|
|
35
|
-
cache: 'pnpm'
|
|
36
|
-
|
|
37
|
-
- name: Install dependencies using pnpm
|
|
38
|
-
run: pnpm install --frozen-lockfile
|
|
39
|
-
|
|
40
|
-
- name: Run tests
|
|
41
|
-
run: pnpm run test
|
|
42
|
-
|
|
43
|
-
# - name: Upload coverage to Codecov
|
|
44
|
-
# uses: codecov/codecov-action@v4
|
|
45
|
-
# with:
|
|
46
|
-
# token: ${{ secrets.CODECOV_TOKEN }}
|
|
47
|
-
# fail_ci_if_error: true
|
|
48
|
-
|
|
49
|
-
publish_npm:
|
|
50
|
-
name: Publish to NPM
|
|
51
|
-
runs-on: ubuntu-latest
|
|
52
|
-
env:
|
|
53
|
-
FORCE_JAVASCRIPT_ACTIONS_TO_NODE20: true
|
|
54
|
-
needs: test
|
|
55
|
-
if: success() && startsWith(github.ref, 'refs/tags/')
|
|
56
|
-
steps:
|
|
57
|
-
|
|
58
|
-
- name: Checkout code
|
|
59
|
-
uses: actions/checkout@v4
|
|
60
|
-
|
|
61
|
-
- name: Install pnpm action
|
|
62
|
-
uses: pnpm/action-setup@v4
|
|
63
|
-
with:
|
|
64
|
-
version: 9
|
|
65
|
-
run_install: false
|
|
66
|
-
|
|
67
|
-
- name: Set up Node.js
|
|
68
|
-
uses: actions/setup-node@v4
|
|
69
|
-
with:
|
|
70
|
-
node-version: 22
|
|
71
|
-
cache: 'pnpm'
|
|
72
|
-
registry-url: 'https://registry.npmjs.org'
|
|
73
|
-
|
|
74
|
-
- name: Install dependencies using pnpm
|
|
75
|
-
run: pnpm install --frozen-lockfile
|
|
76
|
-
|
|
77
|
-
- name: Build package
|
|
78
|
-
run: pnpm run build # Runs "rimraf dist && tsc"
|
|
79
|
-
|
|
80
|
-
- name: Publish to NPM
|
|
81
|
-
run: pnpm publish --no-git-checks
|
|
82
|
-
env:
|
|
83
|
-
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
|
84
|
-
|
package/.mocharc.json
DELETED
package/.prettierignore
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
package.lock.json
|
package/.vscode/launch.json
DELETED
|
@@ -1,32 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
// Use IntelliSense to learn about possible attributes.
|
|
3
|
-
// Hover to view descriptions of existing attributes.
|
|
4
|
-
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
|
|
5
|
-
"version": "0.2.0",
|
|
6
|
-
"configurations": [
|
|
7
|
-
{
|
|
8
|
-
"name": "Current TS File",
|
|
9
|
-
"type": "node",
|
|
10
|
-
"request": "launch",
|
|
11
|
-
"runtimeExecutable": "/home/viljar/.nvm/versions/node/v20.9.0/bin/node",
|
|
12
|
-
"args": ["${relativeFile}"],
|
|
13
|
-
"runtimeArgs": ["--nolazy", "-r", "ts-node/register"],
|
|
14
|
-
"sourceMaps": true,
|
|
15
|
-
"cwd": "${workspaceRoot}"
|
|
16
|
-
},
|
|
17
|
-
{
|
|
18
|
-
"name": "Launch Tests",
|
|
19
|
-
"type": "node",
|
|
20
|
-
"request": "launch",
|
|
21
|
-
"runtimeExecutable": "/home/viljar/.nvm/versions/node/v20.9.0/bin/node",
|
|
22
|
-
"program": "${workspaceFolder}/node_modules/mocha/bin/_mocha",
|
|
23
|
-
"runtimeArgs": ["-r", "ts-node/register"],
|
|
24
|
-
"console": "integratedTerminal",
|
|
25
|
-
"outputCapture": "console",
|
|
26
|
-
|
|
27
|
-
"env": {
|
|
28
|
-
"TS_NODE_PROJECT": "${workspaceFolder}/tsconfig.json"
|
|
29
|
-
}
|
|
30
|
-
}
|
|
31
|
-
]
|
|
32
|
-
}
|
package/docs/README.md
DELETED
|
@@ -1,109 +0,0 @@
|
|
|
1
|
-
assignment-engine / [Exports](modules.md)
|
|
2
|
-
|
|
3
|
-
Install with `npm install match-assignment`.
|
|
4
|
-
|
|
5
|
-
## API
|
|
6
|
-
|
|
7
|
-
```js
|
|
8
|
-
// default export is the main rimraf function, or use named imports
|
|
9
|
-
import matcher from 'match-assignment';
|
|
10
|
-
import { createClient } from 'redis';
|
|
11
|
-
|
|
12
|
-
const redisClient = await createClient({});
|
|
13
|
-
const assignmentMatcher = new AssignmentMatcher(redisClient, options);
|
|
14
|
-
```
|
|
15
|
-
|
|
16
|
-
## Options
|
|
17
|
-
|
|
18
|
-
```js
|
|
19
|
-
// default export is the main rimraf function, or use named imports
|
|
20
|
-
type options = {
|
|
21
|
-
relevantBatchSize?: number, // 50
|
|
22
|
-
redisPrefix?: string, // ''
|
|
23
|
-
maxUserBacklogSize?: number, // default: 9
|
|
24
|
-
enableDefaultMatching: boolean // default: true
|
|
25
|
-
prioritizationFunction?: (
|
|
26
|
-
...args: (Assignment | undefined)[]
|
|
27
|
-
) => Promise<number>,
|
|
28
|
-
matchingFunction?: (
|
|
29
|
-
user: User,
|
|
30
|
-
assignmentTags: string,
|
|
31
|
-
assignmentPriority: number | string,
|
|
32
|
-
assignmentId?: string
|
|
33
|
-
) => Promise<[number, number]>,
|
|
34
|
-
};
|
|
35
|
-
```
|
|
36
|
-
|
|
37
|
-
## Disclaimer
|
|
38
|
-
|
|
39
|
-
`match-assignment` is optimized for **small sets of users processing large sets of assignments** such as (call centers, customer support, back-office operations) in near real time.
|
|
40
|
-
|
|
41
|
-
## Why ?
|
|
42
|
-
|
|
43
|
-
Matching users to assignments based on their tags, cost, and priority is a common problem in many applications, such as job matching platforms, dating apps, or recommendation systems. Solving this problem efficiently and accurately can lead to better user experiences, increased engagement, and improved business outcomes. However, implementing an efficient and scalable matching algorithm can be a complex task, especially when dealing with large datasets and near **real-time matching** requirements. That's where `match-assignment` comes into play
|
|
44
|
-
|
|
45
|
-
## How ?
|
|
46
|
-
|
|
47
|
-
`match-assignment` is built on assumption that users are matched with assignments based on common intersection of tags (`string[]`) and also provides prioritization mechanic (so most important assignments would be processed faster)
|
|
48
|
-
|
|
49
|
-
## Example
|
|
50
|
-
|
|
51
|
-
```js
|
|
52
|
-
#!/usr/bin/env ./node_modules/.bin/ts-node-script
|
|
53
|
-
import AssignmentMatcher from './src/matcher.class';
|
|
54
|
-
import { createClient } from 'redis';
|
|
55
|
-
|
|
56
|
-
async function bootstrap(userCount: number, assignmentCount: number) {
|
|
57
|
-
const redisClient = await createClient({});
|
|
58
|
-
const assignmentMatcher = new AssignmentMatcher(redisClient, {
|
|
59
|
-
relevantBatchSize: 50,
|
|
60
|
-
maxUserBacklogSize: 100,
|
|
61
|
-
});
|
|
62
|
-
|
|
63
|
-
let userAccumulator = 0;
|
|
64
|
-
let assignmentAccumulator = 0;
|
|
65
|
-
for (let i = 0; i < userCount; i++) {
|
|
66
|
-
userAccumulator += 1;
|
|
67
|
-
|
|
68
|
-
await assignmentMatcher.addUser({
|
|
69
|
-
id: i.toString(),
|
|
70
|
-
tags: ['tag1', 'tag2', 'tag3'],
|
|
71
|
-
});
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
for (let i = 0; i < assignmentCount; i++) {
|
|
75
|
-
await assignmentMatcher.addAssignment({
|
|
76
|
-
id: i.toString(),
|
|
77
|
-
tags: ['tag1', 'tag2', 'tag3'],
|
|
78
|
-
createdAt: new Date().getTime(),
|
|
79
|
-
});
|
|
80
|
-
assignmentAccumulator += 1;
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
performance.mark('match-start');
|
|
84
|
-
await assignmentMatcher.matchUsersAssignments();
|
|
85
|
-
performance.mark('match-end');
|
|
86
|
-
const matchMeasure = performance.measure('match', 'match-start', 'match-end');
|
|
87
|
-
|
|
88
|
-
performance.mark('current-assignment-start');
|
|
89
|
-
await assignmentMatcher.getCurrentAssignmentsForUser('1');
|
|
90
|
-
performance.mark('current-assignment-end');
|
|
91
|
-
const currentTask = performance.measure(
|
|
92
|
-
'current',
|
|
93
|
-
'current-assignment-start',
|
|
94
|
-
'current-assignment-end'
|
|
95
|
-
);
|
|
96
|
-
|
|
97
|
-
for (let j = 0; j < userAccumulator; j++) {
|
|
98
|
-
await assignmentMatcher.getCurrentAssignmentsForUser(j.toString());
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
console.debug(
|
|
102
|
-
`users count: ${userAccumulator} | assignmentCount: ${assignmentAccumulator} | matching execution time ${matchMeasure.duration}ms | current assignment time ${currentTask.duration}ms`
|
|
103
|
-
);
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
bootstrap(100, 1000).then(() => {
|
|
107
|
-
process.exit(1);
|
|
108
|
-
});
|
|
109
|
-
```
|