assignment-user-matcher 1.0.14 → 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.
@@ -22,6 +22,7 @@ export type options = {
22
22
  redisPrefix?: string;
23
23
  maxUserBacklogSize?: number;
24
24
  enableDefaultMatching?: boolean;
25
+ matchExpirationMs?: number;
25
26
  prioritizationFunction?: (...args: (Assignment | undefined)[]) => Promise<number>;
26
27
  matchingFunction?: (user: User, assignmentTags: string, assignmentPriority: number | string, assignmentId?: string) => Promise<[number, number]>;
27
28
  };
@@ -34,6 +35,11 @@ export default class AssignmentMatcher {
34
35
  usersKey: string;
35
36
  maxUserBacklogSize: number;
36
37
  enableDefaultMatching: boolean;
38
+ matchExpirationMs: number;
39
+ pendingAssignmentsKey: string;
40
+ pendingAssignmentsExpiryKey: string;
41
+ assignmentOwnerKey: string;
42
+ allTagsKey: string;
37
43
  constructor(redisClient: RedisClientType, options?: options);
38
44
  private initRedis;
39
45
  addUser(user: User): Promise<User>;
@@ -56,5 +62,12 @@ export default class AssignmentMatcher {
56
62
  private getUserRelatedAssignments;
57
63
  matchUsersAssignments(userId?: string): Promise<void>;
58
64
  getCurrentAssignmentsForUser(userId: string): Promise<string[]>;
65
+ acceptAssignment(userId: string, assignmentId: string): Promise<boolean>;
66
+ rejectAssignment(userId: string, assignmentId: string): Promise<boolean>;
67
+ processExpiredMatches(): Promise<number>;
68
+ private autoReleaseInterval;
69
+ startAutoReleaseInterval(intervalMs?: number): void;
70
+ stopAutoReleaseInterval(): void;
71
+ private expandTagWildcards;
59
72
  }
60
73
  //# sourceMappingURL=matcher.class.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"matcher.class.d.ts","sourceRoot":"","sources":["../src/matcher.class.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,OAAO,CAAC;AACrC,MAAM,MAAM,eAAe,GAAG,UAAU,CAAC,OAAO,YAAY,CAAC,CAAC;AAE9D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IAE1D,wBAAwB,CAAC,UAAU,GAAE,MAAc;IAOnD,uBAAuB;YAOT,kBAAkB;CAwBnC"}
@@ -2,8 +2,9 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  class AssignmentMatcher {
4
4
  constructor(redisClient, options) {
5
- var _a, _b, _c, _d, _e, _f;
5
+ var _a, _b, _c, _d, _e, _f, _g;
6
6
  this.redisClient = redisClient;
7
+ this.autoReleaseInterval = null;
7
8
  this.relevantBatchSize = (_a = options === null || options === void 0 ? void 0 : options.relevantBatchSize) !== null && _a !== void 0 ? _a : 50;
8
9
  this.enableDefaultMatching = (_b = options === null || options === void 0 ? void 0 : options.enableDefaultMatching) !== null && _b !== void 0 ? _b : true;
9
10
  this.redisPrefix = (_c = options === null || options === void 0 ? void 0 : options.redisPrefix) !== null && _c !== void 0 ? _c : '';
@@ -11,8 +12,13 @@ class AssignmentMatcher {
11
12
  this.assignmentsKey = this.redisPrefix + 'assignments';
12
13
  this.assignmentsRefKey = this.redisPrefix + 'assignments:ref';
13
14
  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;
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;
16
22
  this.initRedis();
17
23
  }
18
24
  async initRedis() {
@@ -61,6 +67,7 @@ class AssignmentMatcher {
61
67
  score: Number(priority),
62
68
  value: id,
63
69
  });
70
+ multi.zAdd(this.allTagsKey, { score: 0, value: tag });
64
71
  }
65
72
  await multi.exec();
66
73
  return assignment;
@@ -70,7 +77,10 @@ class AssignmentMatcher {
70
77
  const assignmentTagsKey = this.redisPrefix + `assignment:${id}:tags`;
71
78
  // Fetch tags to remove from per-tag indices
72
79
  const [tagsCsv] = await this.redisClient.multi().hGet(assignmentTagsKey, 'tags').exec();
73
- const tags = (typeof tagsCsv === 'string' && tagsCsv.length > 0 ? tagsCsv.split(',') : []);
80
+ let tags = [];
81
+ if (typeof tagsCsv === 'string' && tagsCsv.length > 0) {
82
+ tags = tagsCsv.split(',');
83
+ }
74
84
  const multi = this.redisClient.multi();
75
85
  // Remove from reference and per-assignment hashes
76
86
  multi.hDel(this.assignmentsRefKey, id);
@@ -98,30 +108,64 @@ class AssignmentMatcher {
98
108
  return Object.values(assignments).map((assignment) => JSON.parse(assignment));
99
109
  }
100
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
+ };
101
121
  // If weighted skills are present, use them for scoring
102
122
  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];
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
+ }
108
131
  }
109
132
  }
110
133
  let weightSum = 0;
111
134
  for (const t of aTags) {
112
- const w = user.routingWeights[t];
113
- if (typeof w === 'number' && w > 0)
114
- weightSum += w;
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
+ }
115
149
  }
116
150
  const base = Number(assignmentPriority) || 0;
117
- // score: total positive weight overlap; priority: base weighted slightly by weight
118
151
  return [weightSum, base + weightSum];
119
152
  }
120
153
  // Fallback to default tag-intersection scoring
121
154
  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;
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;
125
169
  const base = Number(assignmentPriority) || 0;
126
170
  return [score || 0, base + (score || 0)];
127
171
  }
@@ -230,17 +274,23 @@ class AssignmentMatcher {
230
274
  const userAssignments = [];
231
275
  if (positiveWeights.length === 0)
232
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;
233
283
  const tempKey = this.redisPrefix + `tmp:user:${user.id}:candidates`;
234
284
  const tempZeroKey = this.redisPrefix + `tmp:user:${user.id}:exclude`;
235
285
  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);
286
+ const unionKeys = expandedPositive.map((pw) => this.redisPrefix + `tag:${pw.tag}:assignments`);
287
+ const unionWeights = expandedPositive.map((pw) => pw.weight);
238
288
  const multi = this.redisClient.multi();
239
289
  // Weighted union of positive tag assignment zsets
240
290
  multi.zUnionStore(tempKey, unionKeys, { WEIGHTS: unionWeights });
241
291
  // Optional exclude set for zero-weight tags
242
- if (zeroWeightTags.length > 0) {
243
- const zeroKeys = zeroWeightTags.map((t) => this.redisPrefix + `tag:${t}:assignments`);
292
+ if (finalZeroTags.length > 0) {
293
+ const zeroKeys = finalZeroTags.map((t) => this.redisPrefix + `tag:${t}:assignments`);
244
294
  multi.zUnionStore(tempZeroKey, zeroKeys);
245
295
  // Final = candidates - exclude
246
296
  multi.zDiffStore(tempFinalKey, [tempKey, tempZeroKey]);
@@ -292,8 +342,14 @@ class AssignmentMatcher {
292
342
  }
293
343
  // Batch-remove all selected assignments from indexes and references to reduce round trips
294
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();
295
349
  const rm = this.redisClient.multi();
296
- for (const s of selected) {
350
+ for (let i = 0; i < selected.length; i++) {
351
+ const s = selected[i];
352
+ const json = jsons[i];
297
353
  const assignmentPriorityKey = this.redisPrefix + `assignment:${s.id}:priority`;
298
354
  const assignmentTagsKey = this.redisPrefix + `assignment:${s.id}:tags`;
299
355
  // Remove from reference and per-assignment hashes
@@ -307,6 +363,12 @@ class AssignmentMatcher {
307
363
  for (const tag of tags) {
308
364
  rm.zRem(this.redisPrefix + `tag:${tag}:assignments`, s.id);
309
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
+ }
310
372
  }
311
373
  await rm.exec();
312
374
  }
@@ -359,5 +421,87 @@ class AssignmentMatcher {
359
421
  const userAssignments = await this.redisClient.sMembers(this.redisPrefix + `user:${userId}:assignments`);
360
422
  return userAssignments.map((el) => el.split(':')[1]);
361
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;
505
+ }
362
506
  }
363
507
  exports.default = AssignmentMatcher;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "assignment-user-matcher",
3
- "version": "1.0.14",
3
+ "version": "1.1.0",
4
4
  "main": "dist/index.js",
5
5
  "module": "dist/index.js",
6
6
  "types": "dist/index.d.ts",