assignment-user-matcher 1.1.0 → 1.1.2
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/dist/matcher.class.d.ts +30 -0
- package/dist/matcher.class.d.ts.map +1 -1
- package/dist/matcher.class.js +180 -23
- package/package.json +1 -1
package/dist/matcher.class.d.ts
CHANGED
|
@@ -4,12 +4,14 @@ export interface User {
|
|
|
4
4
|
id: string;
|
|
5
5
|
tags: string[];
|
|
6
6
|
routingWeights?: Record<string, number>;
|
|
7
|
+
ip?: string;
|
|
7
8
|
[key: string]: any;
|
|
8
9
|
}
|
|
9
10
|
export type Assignment = {
|
|
10
11
|
id: string;
|
|
11
12
|
tags: string[];
|
|
12
13
|
priority?: number;
|
|
14
|
+
allowedCidrs?: string[];
|
|
13
15
|
[key: string]: any;
|
|
14
16
|
};
|
|
15
17
|
export type Stats = {
|
|
@@ -47,6 +49,34 @@ export default class AssignmentMatcher {
|
|
|
47
49
|
removeAssignment(id: string): Promise<string>;
|
|
48
50
|
removeUser(userId: string): Promise<string>;
|
|
49
51
|
getAllAssignments(): Promise<Assignment[]>;
|
|
52
|
+
/**
|
|
53
|
+
* Parse an IPv4 address into a BigInt representation
|
|
54
|
+
*/
|
|
55
|
+
private parseIPv4;
|
|
56
|
+
/**
|
|
57
|
+
* Parse an IPv6 address into a BigInt representation
|
|
58
|
+
* Handles full, compressed (::), and IPv4-mapped formats
|
|
59
|
+
*/
|
|
60
|
+
private parseIPv6;
|
|
61
|
+
/**
|
|
62
|
+
* Parse an IP address (auto-detect IPv4 or IPv6)
|
|
63
|
+
* Returns { value: BigInt, isIPv6: boolean } or null if invalid
|
|
64
|
+
*/
|
|
65
|
+
private parseIP;
|
|
66
|
+
/**
|
|
67
|
+
* Parse a CIDR notation string (e.g., '192.168.1.0/24' or '2001:db8::/32')
|
|
68
|
+
* Returns { network: BigInt, prefixLength: number, isIPv6: boolean } or null
|
|
69
|
+
*/
|
|
70
|
+
private parseCIDR;
|
|
71
|
+
/**
|
|
72
|
+
* Check if an IP address is within a CIDR range
|
|
73
|
+
*/
|
|
74
|
+
private isIpInCidr;
|
|
75
|
+
/**
|
|
76
|
+
* Check if a user's IP matches any of the allowed CIDRs
|
|
77
|
+
* Returns true if no CIDRs are specified (open assignment) or if IP matches any CIDR
|
|
78
|
+
*/
|
|
79
|
+
private checkCidrMatch;
|
|
50
80
|
private matchScore;
|
|
51
81
|
private calculatePriority;
|
|
52
82
|
get stats(): Promise<Stats>;
|
|
@@ -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,MAAM,WAAW,IAAI;IACjB,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,EAAE,CAAC;IAGf,cAAc,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;
|
|
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,MAAM,WAAW,IAAI;IACjB,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,EAAE,CAAC;IAGf,cAAc,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAGxC,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAC;CACtB;AAED,MAAM,MAAM,UAAU,GAAG;IACrB,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,EAAE,CAAC;IACf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,OAAO,CAAC,OAAO,CAAC;IA2BxE,qBAAqB,IAAI,OAAO,CAAC,MAAM,CAAC;IAwB9C,OAAO,CAAC,mBAAmB,CAA+B;IAE1D,wBAAwB,CAAC,UAAU,GAAE,MAAc;IAOnD,uBAAuB;YAOT,kBAAkB;CAwBnC"}
|
package/dist/matcher.class.js
CHANGED
|
@@ -2,23 +2,22 @@
|
|
|
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, _g;
|
|
6
5
|
this.redisClient = redisClient;
|
|
7
6
|
this.autoReleaseInterval = null;
|
|
8
|
-
this.relevantBatchSize =
|
|
9
|
-
this.enableDefaultMatching =
|
|
10
|
-
this.redisPrefix =
|
|
7
|
+
this.relevantBatchSize = options?.relevantBatchSize ?? 50;
|
|
8
|
+
this.enableDefaultMatching = options?.enableDefaultMatching ?? true;
|
|
9
|
+
this.redisPrefix = options?.redisPrefix ?? '';
|
|
11
10
|
this.usersKey = this.redisPrefix + 'users';
|
|
12
11
|
this.assignmentsKey = this.redisPrefix + 'assignments';
|
|
13
12
|
this.assignmentsRefKey = this.redisPrefix + 'assignments:ref';
|
|
14
|
-
this.maxUserBacklogSize =
|
|
15
|
-
this.matchExpirationMs =
|
|
13
|
+
this.maxUserBacklogSize = options?.maxUserBacklogSize ?? 9;
|
|
14
|
+
this.matchExpirationMs = options?.matchExpirationMs ?? 60000;
|
|
16
15
|
this.pendingAssignmentsKey = this.redisPrefix + 'assignments:pending:data';
|
|
17
16
|
this.pendingAssignmentsExpiryKey = this.redisPrefix + 'assignments:pending:expiry';
|
|
18
17
|
this.assignmentOwnerKey = this.redisPrefix + 'assignments:pending:owner';
|
|
19
18
|
this.allTagsKey = this.redisPrefix + 'all:tags';
|
|
20
|
-
this.calculatePriority =
|
|
21
|
-
this.matchScore =
|
|
19
|
+
this.calculatePriority = options?.prioritizationFunction ?? this.calculatePriority;
|
|
20
|
+
this.matchScore = options?.matchingFunction ?? this.matchScore;
|
|
22
21
|
this.initRedis();
|
|
23
22
|
}
|
|
24
23
|
async initRedis() {
|
|
@@ -99,6 +98,7 @@ class AssignmentMatcher {
|
|
|
99
98
|
const multi = this.redisClient
|
|
100
99
|
.multi()
|
|
101
100
|
.del(this.redisPrefix + `user:${userId}:assignments`)
|
|
101
|
+
.del(this.redisPrefix + `user:${userId}:rejected`)
|
|
102
102
|
.hDel(this.usersKey, userId);
|
|
103
103
|
await multi.exec();
|
|
104
104
|
return userId;
|
|
@@ -107,6 +107,145 @@ class AssignmentMatcher {
|
|
|
107
107
|
const assignments = await this.redisClient.hGetAll(this.assignmentsRefKey);
|
|
108
108
|
return Object.values(assignments).map((assignment) => JSON.parse(assignment));
|
|
109
109
|
}
|
|
110
|
+
// ==================== CIDR/IP Matching Utilities ====================
|
|
111
|
+
/**
|
|
112
|
+
* Parse an IPv4 address into a BigInt representation
|
|
113
|
+
*/
|
|
114
|
+
parseIPv4(ip) {
|
|
115
|
+
const parts = ip.split('.');
|
|
116
|
+
if (parts.length !== 4)
|
|
117
|
+
return null;
|
|
118
|
+
let result = 0n;
|
|
119
|
+
for (const part of parts) {
|
|
120
|
+
const num = parseInt(part, 10);
|
|
121
|
+
if (isNaN(num) || num < 0 || num > 255)
|
|
122
|
+
return null;
|
|
123
|
+
result = (result << 8n) | BigInt(num);
|
|
124
|
+
}
|
|
125
|
+
return result;
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Parse an IPv6 address into a BigInt representation
|
|
129
|
+
* Handles full, compressed (::), and IPv4-mapped formats
|
|
130
|
+
*/
|
|
131
|
+
parseIPv6(ip) {
|
|
132
|
+
// Handle IPv4-mapped IPv6 (::ffff:192.168.1.1)
|
|
133
|
+
const ipv4MappedMatch = ip.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i);
|
|
134
|
+
if (ipv4MappedMatch) {
|
|
135
|
+
const ipv4 = this.parseIPv4(ipv4MappedMatch[1]);
|
|
136
|
+
if (ipv4 === null)
|
|
137
|
+
return null;
|
|
138
|
+
return 0xffff00000000n | ipv4;
|
|
139
|
+
}
|
|
140
|
+
// Handle :: expansion
|
|
141
|
+
let fullIp = ip.toLowerCase();
|
|
142
|
+
if (fullIp.includes('::')) {
|
|
143
|
+
const parts = fullIp.split('::');
|
|
144
|
+
if (parts.length > 2)
|
|
145
|
+
return null; // Invalid: more than one ::
|
|
146
|
+
const leftParts = parts[0] ? parts[0].split(':') : [];
|
|
147
|
+
const rightParts = parts[1] ? parts[1].split(':') : [];
|
|
148
|
+
const missingGroups = 8 - leftParts.length - rightParts.length;
|
|
149
|
+
if (missingGroups < 0)
|
|
150
|
+
return null;
|
|
151
|
+
const allParts = [...leftParts, ...Array(missingGroups).fill('0'), ...rightParts];
|
|
152
|
+
fullIp = allParts.join(':');
|
|
153
|
+
}
|
|
154
|
+
const groups = fullIp.split(':');
|
|
155
|
+
if (groups.length !== 8)
|
|
156
|
+
return null;
|
|
157
|
+
let result = 0n;
|
|
158
|
+
for (const group of groups) {
|
|
159
|
+
if (group.length === 0 || group.length > 4)
|
|
160
|
+
return null;
|
|
161
|
+
const num = parseInt(group, 16);
|
|
162
|
+
if (isNaN(num) || num < 0 || num > 0xffff)
|
|
163
|
+
return null;
|
|
164
|
+
result = (result << 16n) | BigInt(num);
|
|
165
|
+
}
|
|
166
|
+
return result;
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Parse an IP address (auto-detect IPv4 or IPv6)
|
|
170
|
+
* Returns { value: BigInt, isIPv6: boolean } or null if invalid
|
|
171
|
+
*/
|
|
172
|
+
parseIP(ip) {
|
|
173
|
+
if (!ip || typeof ip !== 'string')
|
|
174
|
+
return null;
|
|
175
|
+
const trimmed = ip.trim();
|
|
176
|
+
// Try IPv4 first (contains dots, no colons)
|
|
177
|
+
if (trimmed.includes('.') && !trimmed.includes(':')) {
|
|
178
|
+
const value = this.parseIPv4(trimmed);
|
|
179
|
+
if (value !== null)
|
|
180
|
+
return { value, isIPv6: false };
|
|
181
|
+
}
|
|
182
|
+
// Try IPv6 (contains colons)
|
|
183
|
+
if (trimmed.includes(':')) {
|
|
184
|
+
const value = this.parseIPv6(trimmed);
|
|
185
|
+
if (value !== null)
|
|
186
|
+
return { value, isIPv6: true };
|
|
187
|
+
}
|
|
188
|
+
return null;
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Parse a CIDR notation string (e.g., '192.168.1.0/24' or '2001:db8::/32')
|
|
192
|
+
* Returns { network: BigInt, prefixLength: number, isIPv6: boolean } or null
|
|
193
|
+
*/
|
|
194
|
+
parseCIDR(cidr) {
|
|
195
|
+
if (!cidr || typeof cidr !== 'string')
|
|
196
|
+
return null;
|
|
197
|
+
const parts = cidr.trim().split('/');
|
|
198
|
+
if (parts.length !== 2)
|
|
199
|
+
return null;
|
|
200
|
+
const ip = this.parseIP(parts[0]);
|
|
201
|
+
if (!ip)
|
|
202
|
+
return null;
|
|
203
|
+
const prefixLength = parseInt(parts[1], 10);
|
|
204
|
+
const maxPrefix = ip.isIPv6 ? 128 : 32;
|
|
205
|
+
if (isNaN(prefixLength) || prefixLength < 0 || prefixLength > maxPrefix)
|
|
206
|
+
return null;
|
|
207
|
+
// Calculate network address by masking
|
|
208
|
+
const totalBits = ip.isIPv6 ? 128 : 32;
|
|
209
|
+
const hostBits = totalBits - prefixLength;
|
|
210
|
+
const mask = hostBits === totalBits ? 0n : ((1n << BigInt(totalBits)) - 1n) ^ ((1n << BigInt(hostBits)) - 1n);
|
|
211
|
+
const network = ip.value & mask;
|
|
212
|
+
return { network, prefixLength, isIPv6: ip.isIPv6 };
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Check if an IP address is within a CIDR range
|
|
216
|
+
*/
|
|
217
|
+
isIpInCidr(ip, cidr) {
|
|
218
|
+
const parsedIp = this.parseIP(ip);
|
|
219
|
+
const parsedCidr = this.parseCIDR(cidr);
|
|
220
|
+
if (!parsedIp || !parsedCidr)
|
|
221
|
+
return false;
|
|
222
|
+
// IP version must match CIDR version
|
|
223
|
+
if (parsedIp.isIPv6 !== parsedCidr.isIPv6)
|
|
224
|
+
return false;
|
|
225
|
+
const totalBits = parsedIp.isIPv6 ? 128 : 32;
|
|
226
|
+
const hostBits = totalBits - parsedCidr.prefixLength;
|
|
227
|
+
const mask = hostBits === totalBits ? 0n : ((1n << BigInt(totalBits)) - 1n) ^ ((1n << BigInt(hostBits)) - 1n);
|
|
228
|
+
return (parsedIp.value & mask) === parsedCidr.network;
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* Check if a user's IP matches any of the allowed CIDRs
|
|
232
|
+
* Returns true if no CIDRs are specified (open assignment) or if IP matches any CIDR
|
|
233
|
+
*/
|
|
234
|
+
checkCidrMatch(userIp, allowedCidrs) {
|
|
235
|
+
// If no CIDR restrictions, assignment is open to all
|
|
236
|
+
if (!allowedCidrs || allowedCidrs.length === 0)
|
|
237
|
+
return true;
|
|
238
|
+
// If CIDRs are specified but user has no IP, deny match
|
|
239
|
+
if (!userIp)
|
|
240
|
+
return false;
|
|
241
|
+
// Check if user IP matches any allowed CIDR
|
|
242
|
+
for (const cidr of allowedCidrs) {
|
|
243
|
+
if (this.isIpInCidr(userIp, cidr))
|
|
244
|
+
return true;
|
|
245
|
+
}
|
|
246
|
+
return false;
|
|
247
|
+
}
|
|
248
|
+
// ==================== End CIDR/IP Matching Utilities ====================
|
|
110
249
|
async matchScore(user, assignmentTags, assignmentPriority, assignmentId) {
|
|
111
250
|
const aTags = assignmentTags ? assignmentTags.split(',') : [];
|
|
112
251
|
const matchesPattern = (pattern, tag) => {
|
|
@@ -171,7 +310,7 @@ class AssignmentMatcher {
|
|
|
171
310
|
}
|
|
172
311
|
async calculatePriority(...args) {
|
|
173
312
|
const [assignment] = args;
|
|
174
|
-
return new Date().getTime() -
|
|
313
|
+
return new Date().getTime() - assignment?.createdAt || 0;
|
|
175
314
|
}
|
|
176
315
|
get stats() {
|
|
177
316
|
return (async () => {
|
|
@@ -283,28 +422,27 @@ class AssignmentMatcher {
|
|
|
283
422
|
const tempKey = this.redisPrefix + `tmp:user:${user.id}:candidates`;
|
|
284
423
|
const tempZeroKey = this.redisPrefix + `tmp:user:${user.id}:exclude`;
|
|
285
424
|
const tempFinalKey = this.redisPrefix + `tmp:user:${user.id}:final`;
|
|
425
|
+
const rejectedKey = this.redisPrefix + `user:${user.id}:rejected`;
|
|
286
426
|
const unionKeys = expandedPositive.map((pw) => this.redisPrefix + `tag:${pw.tag}:assignments`);
|
|
287
427
|
const unionWeights = expandedPositive.map((pw) => pw.weight);
|
|
288
428
|
const multi = this.redisClient.multi();
|
|
289
429
|
// Weighted union of positive tag assignment zsets
|
|
290
430
|
multi.zUnionStore(tempKey, unionKeys, { WEIGHTS: unionWeights });
|
|
431
|
+
const excludeKeys = [];
|
|
291
432
|
// Optional exclude set for zero-weight tags
|
|
292
433
|
if (finalZeroTags.length > 0) {
|
|
293
434
|
const zeroKeys = finalZeroTags.map((t) => this.redisPrefix + `tag:${t}:assignments`);
|
|
294
435
|
multi.zUnionStore(tempZeroKey, zeroKeys);
|
|
295
|
-
// Final = candidates - exclude
|
|
296
|
-
multi.zDiffStore(tempFinalKey, [tempKey, tempZeroKey]);
|
|
297
|
-
// Set short TTLs to clean up
|
|
298
|
-
multi.expire(tempKey, 5);
|
|
299
436
|
multi.expire(tempZeroKey, 5);
|
|
300
|
-
|
|
301
|
-
}
|
|
302
|
-
else {
|
|
303
|
-
// No exclude; just use tempKey as final (copy into final for uniformity)
|
|
304
|
-
multi.zUnionStore(tempFinalKey, [tempKey]);
|
|
305
|
-
multi.expire(tempKey, 5);
|
|
306
|
-
multi.expire(tempFinalKey, 5);
|
|
437
|
+
excludeKeys.push(tempZeroKey);
|
|
307
438
|
}
|
|
439
|
+
// Always exclude rejected assignments
|
|
440
|
+
excludeKeys.push(rejectedKey);
|
|
441
|
+
// Final = candidates - exclude (zero weights + rejected)
|
|
442
|
+
multi.zDiffStore(tempFinalKey, [tempKey, ...excludeKeys]);
|
|
443
|
+
// Set short TTLs to clean up
|
|
444
|
+
multi.expire(tempKey, 5);
|
|
445
|
+
multi.expire(tempFinalKey, 5);
|
|
308
446
|
await multi.exec();
|
|
309
447
|
// Pull top-N in ascending score to preserve previous behavior on ties (lex ascending)
|
|
310
448
|
const top = await this.redisClient.zRangeWithScores(tempFinalKey, 0, this.relevantBatchSize - 1);
|
|
@@ -318,14 +456,27 @@ class AssignmentMatcher {
|
|
|
318
456
|
const assignmentTagsKey = this.redisPrefix + `assignment:${assignmentId}:tags`;
|
|
319
457
|
batched.hGet(assignmentPriorityKey, 'priority');
|
|
320
458
|
batched.hGet(assignmentTagsKey, 'tags');
|
|
459
|
+
// Also fetch assignment JSON to access allowedCidrs for network matching
|
|
460
|
+
batched.hGet(this.assignmentsRefKey, assignmentId);
|
|
321
461
|
}
|
|
322
462
|
const flat = await batched.exec();
|
|
323
463
|
const details = [];
|
|
324
464
|
for (let i = 0; i < top.length; i++) {
|
|
325
465
|
const assignmentId = top[i].value;
|
|
326
|
-
const priority = Number(flat[i *
|
|
327
|
-
const tags = String(flat[i *
|
|
328
|
-
|
|
466
|
+
const priority = Number(flat[i * 3]) || 0;
|
|
467
|
+
const tags = String(flat[i * 3 + 1] || '');
|
|
468
|
+
const assignmentJson = flat[i * 3 + 2];
|
|
469
|
+
let allowedCidrs;
|
|
470
|
+
if (assignmentJson) {
|
|
471
|
+
try {
|
|
472
|
+
const parsed = JSON.parse(assignmentJson);
|
|
473
|
+
allowedCidrs = parsed.allowedCidrs;
|
|
474
|
+
}
|
|
475
|
+
catch {
|
|
476
|
+
// Ignore JSON parse errors
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
details.push({ id: assignmentId, basePriority: priority, tags, allowedCidrs });
|
|
329
480
|
}
|
|
330
481
|
// Prefer higher base priority first to satisfy tests and practical expectations
|
|
331
482
|
details.sort((a, b) => b.basePriority - a.basePriority);
|
|
@@ -333,6 +484,10 @@ class AssignmentMatcher {
|
|
|
333
484
|
for (const d of details) {
|
|
334
485
|
if (userAssignments.length >= this.maxUserBacklogSize)
|
|
335
486
|
break;
|
|
487
|
+
// Check CIDR restrictions: if assignment has allowedCidrs, user must have matching IP
|
|
488
|
+
if (!this.checkCidrMatch(user.ip, d.allowedCidrs)) {
|
|
489
|
+
continue; // Skip this assignment - user IP doesn't match allowed CIDRs
|
|
490
|
+
}
|
|
336
491
|
// Use custom matchScore (supports weights) for a final check and tie-break
|
|
337
492
|
const [score, combinedPriority] = await this.matchScore(user, d.tags, d.basePriority, d.id);
|
|
338
493
|
if (score && combinedPriority) {
|
|
@@ -443,6 +598,8 @@ class AssignmentMatcher {
|
|
|
443
598
|
multi.hDel(this.pendingAssignmentsKey, assignmentId);
|
|
444
599
|
multi.zRem(this.pendingAssignmentsExpiryKey, assignmentId);
|
|
445
600
|
multi.hDel(this.assignmentOwnerKey, assignmentId);
|
|
601
|
+
// Add to rejected list to prevent immediate re-assignment
|
|
602
|
+
multi.sAdd(this.redisPrefix + `user:${userId}:rejected`, assignmentId);
|
|
446
603
|
await multi.exec();
|
|
447
604
|
if (json) {
|
|
448
605
|
await this.addAssignment(JSON.parse(json));
|